2 * Copyright 2015 Open Networking Laboratory
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.onosproject.maven;
18 import com.fasterxml.jackson.databind.ObjectMapper;
19 import com.fasterxml.jackson.databind.node.ArrayNode;
20 import com.fasterxml.jackson.databind.node.ObjectNode;
21 import com.google.common.io.ByteStreams;
22 import com.google.common.io.Files;
23 import com.thoughtworks.qdox.JavaProjectBuilder;
24 import com.thoughtworks.qdox.model.DocletTag;
25 import com.thoughtworks.qdox.model.JavaAnnotation;
26 import com.thoughtworks.qdox.model.JavaClass;
27 import com.thoughtworks.qdox.model.JavaMethod;
28 import com.thoughtworks.qdox.model.JavaParameter;
29 import com.thoughtworks.qdox.model.JavaType;
30 import org.apache.maven.plugin.AbstractMojo;
31 import org.apache.maven.plugin.MojoExecutionException;
32 import org.apache.maven.plugins.annotations.LifecyclePhase;
33 import org.apache.maven.plugins.annotations.Mojo;
34 import org.apache.maven.plugins.annotations.Parameter;
35 import org.apache.maven.project.MavenProject;
38 import java.io.FileWriter;
39 import java.io.IOException;
40 import java.io.PrintWriter;
41 import java.util.HashMap;
43 import java.util.Optional;
45 import static com.google.common.base.Strings.isNullOrEmpty;
48 * Produces ONOS Swagger api-doc.
50 @Mojo(name = "swagger", defaultPhase = LifecyclePhase.GENERATE_SOURCES)
51 public class OnosSwaggerMojo extends AbstractMojo {
52 private final ObjectMapper mapper = new ObjectMapper();
54 private static final String JSON_FILE = "swagger.json";
55 private static final String GEN_SRC = "generated-sources";
56 private static final String REG_SRC = "registrator.javat";
58 private static final String PATH = "javax.ws.rs.Path";
59 private static final String PATH_PARAM = "javax.ws.rs.PathParam";
60 private static final String QUERY_PARAM = "javax.ws.rs.QueryParam";
61 private static final String POST = "javax.ws.rs.POST";
62 private static final String GET = "javax.ws.rs.GET";
63 private static final String PUT = "javax.ws.rs.PUT";
64 private static final String DELETE = "javax.ws.rs.DELETE";
65 private static final String PRODUCES = "javax.ws.rs.Produces";
66 private static final String CONSUMES = "javax.ws.rs.Consumes";
67 private static final String JSON = "MediaType.APPLICATION_JSON";
70 * The directory where the generated catalogue file will be put.
72 @Parameter(defaultValue = "${basedir}")
73 protected File srcDirectory;
76 * The directory where the generated catalogue file will be put.
78 @Parameter(defaultValue = "${project.build.directory}")
79 protected File dstDirectory;
82 * REST API web-context
84 @Parameter(defaultValue = "${web.context}")
85 protected String webContext;
90 @Parameter(defaultValue = "${api.version}")
91 protected String apiVersion;
94 * REST API description
96 @Parameter(defaultValue = "${api.description}")
97 protected String apiDescription;
102 @Parameter(defaultValue = "${api.title}")
103 protected String apiTitle;
108 @Parameter(defaultValue = "${api.package}")
109 protected String apiPackage;
114 @Parameter(defaultValue = "${project}")
115 protected MavenProject project;
119 public void execute() throws MojoExecutionException {
121 JavaProjectBuilder builder = new JavaProjectBuilder();
122 builder.addSourceTree(new File(srcDirectory, "src/main/java"));
124 ObjectNode root = initializeRoot();
125 ArrayNode tags = mapper.createArrayNode();
126 ObjectNode paths = mapper.createObjectNode();
128 root.set("tags", tags);
129 root.set("paths", paths);
131 builder.getClasses().forEach(jc -> processClass(jc, paths, tags));
133 if (paths.size() > 0) {
134 getLog().info("Generating ONOS REST API documentation...");
137 if (!isNullOrEmpty(apiPackage)) {
142 project.addCompileSourceRoot(new File(dstDirectory, GEN_SRC).getPath());
144 } catch (Exception e) {
145 getLog().warn("Unable to generate ONOS REST API documentation", e);
150 // initializes top level root with Swagger required specifications
151 private ObjectNode initializeRoot() {
152 ObjectNode root = mapper.createObjectNode();
153 root.put("swagger", "2.0");
154 ObjectNode info = mapper.createObjectNode();
155 root.set("info", info);
157 root.put("basePath", webContext);
158 info.put("version", apiVersion);
159 info.put("title", apiTitle);
160 info.put("description", apiDescription);
162 ArrayNode produces = mapper.createArrayNode();
163 produces.add("application/json");
164 root.set("produces", produces);
166 ArrayNode consumes = mapper.createArrayNode();
167 consumes.add("application/json");
168 root.set("consumes", consumes);
173 // Checks whether javaClass has a path tag associated with it and if it does
174 // processes its methods and creates a tag for the class on the root
175 void processClass(JavaClass javaClass, ObjectNode paths, ArrayNode tags) {
176 // If the class does not have a Path tag then ignore it
177 JavaAnnotation annotation = getPathAnnotation(javaClass);
178 if (annotation == null) {
182 String path = getPath(annotation);
187 String resourcePath = "/" + path;
188 String tagPath = path.isEmpty() ? "/" : path;
190 // Create tag node for this class.
191 ObjectNode tagObject = mapper.createObjectNode();
192 tagObject.put("name", tagPath);
193 if (javaClass.getComment() != null) {
194 tagObject.put("description", shortText(javaClass.getComment()));
198 // Create an array node add to all methods from this class.
199 ArrayNode tagArray = mapper.createArrayNode();
200 tagArray.add(tagPath);
202 processAllMethods(javaClass, resourcePath, paths, tagArray);
205 private JavaAnnotation getPathAnnotation(JavaClass javaClass) {
206 Optional<JavaAnnotation> optional = javaClass.getAnnotations()
207 .stream().filter(a -> a.getType().getName().equals(PATH)).findAny();
208 return optional.isPresent() ? optional.get() : null;
211 // Checks whether a class's methods are REST methods and then places all the
212 // methods under a specific path into the paths node
213 private void processAllMethods(JavaClass javaClass, String resourcePath,
214 ObjectNode paths, ArrayNode tagArray) {
215 // map of the path to its methods represented by an ObjectNode
216 Map<String, ObjectNode> pathMap = new HashMap<>();
218 javaClass.getMethods().forEach(javaMethod -> {
219 javaMethod.getAnnotations().forEach(annotation -> {
220 String name = annotation.getType().getName();
221 if (name.equals(POST) || name.equals(GET) || name.equals(DELETE) || name.equals(PUT)) {
222 // substring(12) removes "javax.ws.rs."
223 String method = annotation.getType().toString().substring(12).toLowerCase();
224 processRestMethod(javaMethod, method, pathMap, resourcePath, tagArray);
229 // for each path add its methods to the path node
230 for (Map.Entry<String, ObjectNode> entry : pathMap.entrySet()) {
231 paths.set(entry.getKey(), entry.getValue());
237 private void processRestMethod(JavaMethod javaMethod, String method,
238 Map<String, ObjectNode> pathMap,
239 String resourcePath, ArrayNode tagArray) {
240 String fullPath = resourcePath, consumes = "", produces = "",
241 comment = javaMethod.getComment();
242 for (JavaAnnotation annotation : javaMethod.getAnnotations()) {
243 String name = annotation.getType().getName();
244 if (name.equals(PATH)) {
245 fullPath = resourcePath + "/" + getPath(annotation);
246 fullPath = fullPath.replaceFirst("^//", "/");
248 if (name.equals(CONSUMES)) {
249 consumes = getIOType(annotation);
251 if (name.equals(PRODUCES)) {
252 produces = getIOType(annotation);
255 ObjectNode methodNode = mapper.createObjectNode();
256 methodNode.set("tags", tagArray);
258 addSummaryDescriptions(methodNode, comment);
259 processParameters(javaMethod, methodNode);
261 processConsumesProduces(methodNode, "consumes", consumes);
262 processConsumesProduces(methodNode, "produces", produces);
264 addResponses(methodNode);
266 ObjectNode operations = pathMap.get(fullPath);
267 if (operations == null) {
268 operations = mapper.createObjectNode();
269 operations.set(method, methodNode);
270 pathMap.put(fullPath, operations);
272 operations.set(method, methodNode);
276 private void processConsumesProduces(ObjectNode methodNode, String type, String io) {
277 if (!io.equals("")) {
278 ArrayNode array = mapper.createArrayNode();
279 methodNode.set(type, array);
284 private void addSummaryDescriptions(ObjectNode methodNode, String comment) {
285 String summary = "", description;
286 if (comment != null) {
287 if (comment.contains(".")) {
288 int periodIndex = comment.indexOf(".");
289 summary = comment.substring(0, periodIndex);
290 description = comment.length() > periodIndex + 1 ?
291 comment.substring(periodIndex + 1).trim() : "";
293 description = comment;
295 methodNode.put("summary", summary);
296 methodNode.put("description", description);
300 // Temporary solution to add responses to a method
301 // TODO Provide annotations in the web resources for responses and parse them
302 private void addResponses(ObjectNode methodNode) {
303 ObjectNode responses = mapper.createObjectNode();
304 methodNode.set("responses", responses);
306 ObjectNode success = mapper.createObjectNode();
307 success.put("description", "successful operation");
308 responses.set("200", success);
310 ObjectNode defaultObj = mapper.createObjectNode();
311 defaultObj.put("description", "Unexpected error");
312 responses.set("default", defaultObj);
315 // Checks if the annotations has a value of JSON and returns the string
316 // that Swagger requires
317 private String getIOType(JavaAnnotation annotation) {
318 if (annotation.getNamedParameter("value").toString().equals(JSON)) {
319 return "application/json";
324 // If the annotation has a Path tag, returns the value with leading and
325 // trailing double quotes and slash removed.
326 private String getPath(JavaAnnotation annotation) {
327 String path = annotation.getNamedParameter("value").toString();
328 return path == null ? null : path.replaceAll("(^[\\\"/]*|[/\\\"]*$)", "");
331 // Processes parameters of javaMethod and enters the proper key-values into the methodNode
332 private void processParameters(JavaMethod javaMethod, ObjectNode methodNode) {
333 ArrayNode parameters = mapper.createArrayNode();
334 methodNode.set("parameters", parameters);
335 boolean required = true;
337 for (JavaParameter javaParameter : javaMethod.getParameters()) {
338 ObjectNode individualParameterNode = mapper.createObjectNode();
339 Optional<JavaAnnotation> optional = javaParameter.getAnnotations().stream().filter(
340 annotation -> annotation.getType().getName().equals(PATH_PARAM) ||
341 annotation.getType().getName().equals(QUERY_PARAM)).findAny();
342 JavaAnnotation pathType = optional.isPresent() ? optional.get() : null;
344 String annotationName = javaParameter.getName();
347 if (pathType != null) { //the parameter is a path or query parameter
348 individualParameterNode.put("name",
349 pathType.getNamedParameter("value").toString().replace("\"", ""));
350 if (pathType.getType().getName().equals(PATH_PARAM)) {
351 individualParameterNode.put("in", "path");
352 } else if (pathType.getType().getName().equals(QUERY_PARAM)) {
353 individualParameterNode.put("in", "query");
355 individualParameterNode.put("type", getType(javaParameter.getType()));
356 } else { // the parameter is a body parameter
357 individualParameterNode.put("name", annotationName);
358 individualParameterNode.put("in", "body");
360 // TODO add actual hardcoded schemas and a type
361 // body parameters must have a schema associated with them
362 ArrayNode schema = mapper.createArrayNode();
363 individualParameterNode.set("schema", schema);
365 for (DocletTag p : javaMethod.getTagsByName("param")) {
366 if (p.getValue().contains(annotationName)) {
368 String description = p.getValue().split(" ", 2)[1].trim();
369 if (description.contains("optional")) {
372 individualParameterNode.put("description", description);
373 } catch (Exception e) {
378 individualParameterNode.put("required", required);
379 parameters.add(individualParameterNode);
383 // Returns the Swagger specified strings for the type of a parameter
384 private String getType(JavaType javaType) {
385 String type = javaType.getFullyQualifiedName();
387 if (type.equals(String.class.getName())) {
389 } else if (type.equals("int")) {
391 } else if (type.equals(boolean.class.getName())) {
393 } else if (type.equals(long.class.getName())) {
401 // Writes the swagger.json file using the supplied JSON root.
402 private void genCatalog(ObjectNode root) {
403 File swaggerCfg = new File(dstDirectory, JSON_FILE);
404 if (dstDirectory.exists() || dstDirectory.mkdirs()) {
405 try (FileWriter fw = new FileWriter(swaggerCfg);
406 PrintWriter pw = new PrintWriter(fw)) {
407 pw.println(root.toString());
408 } catch (IOException e) {
409 getLog().warn("Unable to write " + JSON_FILE);
412 getLog().warn("Unable to create " + dstDirectory);
416 // Generates the registrator Java component.
417 private void genRegistrator() {
418 File dir = new File(dstDirectory, GEN_SRC);
419 File reg = new File(dir, apiPackage.replaceAll("\\.", "/") + "/ApiDocRegistrator.java");
420 File pkg = reg.getParentFile();
421 if (pkg.exists() || pkg.mkdirs()) {
423 String src = new String(ByteStreams.toByteArray(getClass().getResourceAsStream(REG_SRC)));
424 src = src.replace("${api.package}", apiPackage)
425 .replace("${web.context}", webContext)
426 .replace("${api.title}", apiTitle)
427 .replace("${api.description}", apiTitle);
428 Files.write(src.getBytes(), reg);
429 } catch (IOException e) {
430 getLog().warn("Unable to write " + reg);
433 getLog().warn("Unable to create " + reg);
437 // Returns "nickname" based on method and path for a REST method
438 private String setNickname(String method, String path) {
439 if (!path.equals("")) {
440 return (method + path.replace('/', '_').replace("{", "").replace("}", "")).toLowerCase();
442 return method.toLowerCase();
446 private String shortText(String comment) {
447 int i = comment.indexOf('.');
448 return i > 0 ? comment.substring(0, i) : comment;