0ee5382e43e092746d009065f43bfdf512790b4a
[onosfw.git] /
1 /*
2  * Copyright 2015 Open Networking Laboratory
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 package org.onosproject.maven;
17
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.base.Charsets;
22 import com.google.common.io.ByteStreams;
23 import com.google.common.io.Files;
24 import com.thoughtworks.qdox.JavaProjectBuilder;
25 import com.thoughtworks.qdox.model.DocletTag;
26 import com.thoughtworks.qdox.model.JavaAnnotation;
27 import com.thoughtworks.qdox.model.JavaClass;
28 import com.thoughtworks.qdox.model.JavaMethod;
29 import com.thoughtworks.qdox.model.JavaParameter;
30 import com.thoughtworks.qdox.model.JavaType;
31 import org.apache.maven.plugin.AbstractMojo;
32 import org.apache.maven.plugin.MojoExecutionException;
33 import org.apache.maven.plugins.annotations.LifecyclePhase;
34 import org.apache.maven.plugins.annotations.Mojo;
35 import org.apache.maven.plugins.annotations.Parameter;
36 import org.apache.maven.project.MavenProject;
37
38 import java.io.File;
39 import java.io.FileWriter;
40 import java.io.IOException;
41 import java.io.PrintWriter;
42 import java.util.HashMap;
43 import java.util.Map;
44 import java.util.Optional;
45
46 import static com.google.common.base.Strings.isNullOrEmpty;
47
48 /**
49  * Produces ONOS Swagger api-doc.
50  */
51 @Mojo(name = "swagger", defaultPhase = LifecyclePhase.GENERATE_SOURCES)
52 public class OnosSwaggerMojo extends AbstractMojo {
53     private final ObjectMapper mapper = new ObjectMapper();
54
55     private static final String JSON_FILE = "swagger.json";
56     private static final String GEN_SRC = "generated-sources";
57     private static final String REG_SRC = "registrator.javat";
58
59     private static final String PATH = "javax.ws.rs.Path";
60     private static final String PATH_PARAM = "javax.ws.rs.PathParam";
61     private static final String QUERY_PARAM = "javax.ws.rs.QueryParam";
62     private static final String POST = "javax.ws.rs.POST";
63     private static final String GET = "javax.ws.rs.GET";
64     private static final String PUT = "javax.ws.rs.PUT";
65     private static final String DELETE = "javax.ws.rs.DELETE";
66     private static final String PRODUCES = "javax.ws.rs.Produces";
67     private static final String CONSUMES = "javax.ws.rs.Consumes";
68     private static final String JSON = "MediaType.APPLICATION_JSON";
69     private static final String OCTET_STREAM = "MediaType.APPLICATION_OCTET_STREAM";
70
71     /**
72      * The directory where the generated catalogue file will be put.
73      */
74     @Parameter(defaultValue = "${basedir}")
75     protected File srcDirectory;
76
77     /**
78      * The directory where the generated catalogue file will be put.
79      */
80     @Parameter(defaultValue = "${project.build.directory}")
81     protected File dstDirectory;
82
83     /**
84      * REST API web-context
85      */
86     @Parameter(defaultValue = "${web.context}")
87     protected String webContext;
88
89     /**
90      * REST API version
91      */
92     @Parameter(defaultValue = "${api.version}")
93     protected String apiVersion;
94
95     /**
96      * REST API description
97      */
98     @Parameter(defaultValue = "${api.description}")
99     protected String apiDescription;
100
101     /**
102      * REST API title
103      */
104     @Parameter(defaultValue = "${api.title}")
105     protected String apiTitle;
106
107     /**
108      * REST API title
109      */
110     @Parameter(defaultValue = "${api.package}")
111     protected String apiPackage;
112
113     /**
114      * Maven project
115      */
116     @Parameter(defaultValue = "${project}")
117     protected MavenProject project;
118
119
120     @Override
121     public void execute() throws MojoExecutionException {
122         try {
123             JavaProjectBuilder builder = new JavaProjectBuilder();
124             builder.addSourceTree(new File(srcDirectory, "src/main/java"));
125
126             ObjectNode root = initializeRoot();
127             ArrayNode tags = mapper.createArrayNode();
128             ObjectNode paths = mapper.createObjectNode();
129             ObjectNode definitions = mapper.createObjectNode();
130
131             root.set("tags", tags);
132             root.set("paths", paths);
133             root.set("definitions", definitions);
134
135             builder.getClasses().forEach(jc -> processClass(jc, paths, tags, definitions));
136
137             if (paths.size() > 0) {
138                 getLog().info("Generating ONOS REST API documentation...");
139                 genCatalog(root);
140
141                 if (!isNullOrEmpty(apiPackage)) {
142                     genRegistrator();
143                 }
144             }
145
146             project.addCompileSourceRoot(new File(dstDirectory, GEN_SRC).getPath());
147
148         } catch (Exception e) {
149             getLog().warn("Unable to generate ONOS REST API documentation", e);
150             throw e;
151         }
152     }
153
154     // initializes top level root with Swagger required specifications
155     private ObjectNode initializeRoot() {
156         ObjectNode root = mapper.createObjectNode();
157         root.put("swagger", "2.0");
158         ObjectNode info = mapper.createObjectNode();
159         root.set("info", info);
160
161         root.put("basePath", webContext);
162         info.put("version", apiVersion);
163         info.put("title", apiTitle);
164         info.put("description", apiDescription);
165
166         ArrayNode produces = mapper.createArrayNode();
167         produces.add("application/json");
168         root.set("produces", produces);
169
170         ArrayNode consumes = mapper.createArrayNode();
171         consumes.add("application/json");
172         root.set("consumes", consumes);
173
174         return root;
175     }
176
177     // Checks whether javaClass has a path tag associated with it and if it does
178     // processes its methods and creates a tag for the class on the root
179     void processClass(JavaClass javaClass, ObjectNode paths, ArrayNode tags, ObjectNode definitions) {
180         // If the class does not have a Path tag then ignore it
181         JavaAnnotation annotation = getPathAnnotation(javaClass);
182         if (annotation == null) {
183             return;
184         }
185
186         String path = getPath(annotation);
187         if (path == null) {
188             return;
189         }
190
191         String resourcePath = "/" + path;
192         String tagPath = path.isEmpty() ? "/" : path;
193
194         // Create tag node for this class.
195         ObjectNode tagObject = mapper.createObjectNode();
196         tagObject.put("name", tagPath);
197         if (javaClass.getComment() != null) {
198             tagObject.put("description", shortText(javaClass.getComment()));
199         }
200         tags.add(tagObject);
201
202         // Create an array node add to all methods from this class.
203         ArrayNode tagArray = mapper.createArrayNode();
204         tagArray.add(tagPath);
205
206         processAllMethods(javaClass, resourcePath, paths, tagArray, definitions);
207     }
208
209     private JavaAnnotation getPathAnnotation(JavaClass javaClass) {
210         Optional<JavaAnnotation> optional = javaClass.getAnnotations()
211                 .stream().filter(a -> a.getType().getName().equals(PATH)).findAny();
212         return optional.isPresent() ? optional.get() : null;
213     }
214
215     // Checks whether a class's methods are REST methods and then places all the
216     // methods under a specific path into the paths node
217     private void processAllMethods(JavaClass javaClass, String resourcePath,
218                                    ObjectNode paths, ArrayNode tagArray, ObjectNode definitions) {
219         // map of the path to its methods represented by an ObjectNode
220         Map<String, ObjectNode> pathMap = new HashMap<>();
221
222         javaClass.getMethods().forEach(javaMethod -> {
223             javaMethod.getAnnotations().forEach(annotation -> {
224                 String name = annotation.getType().getName();
225                 if (name.equals(POST) || name.equals(GET) || name.equals(DELETE) || name.equals(PUT)) {
226                     // substring(12) removes "javax.ws.rs."
227                     String method = annotation.getType().toString().substring(12).toLowerCase();
228                     processRestMethod(javaMethod, method, pathMap, resourcePath, tagArray, definitions);
229                 }
230             });
231         });
232
233         // for each path add its methods to the path node
234         for (Map.Entry<String, ObjectNode> entry : pathMap.entrySet()) {
235             paths.set(entry.getKey(), entry.getValue());
236         }
237
238
239     }
240
241     private void processRestMethod(JavaMethod javaMethod, String method,
242                                    Map<String, ObjectNode> pathMap,
243                                    String resourcePath, ArrayNode tagArray, ObjectNode definitions) {
244         String fullPath = resourcePath, consumes = "", produces = "",
245                 comment = javaMethod.getComment();
246         DocletTag tag = javaMethod.getTagByName("rsModel");
247         for (JavaAnnotation annotation : javaMethod.getAnnotations()) {
248             String name = annotation.getType().getName();
249             if (name.equals(PATH)) {
250                 fullPath = resourcePath + "/" + getPath(annotation);
251                 fullPath = fullPath.replaceFirst("^//", "/");
252             }
253             if (name.equals(CONSUMES)) {
254                 consumes = getIOType(annotation);
255             }
256             if (name.equals(PRODUCES)) {
257                 produces = getIOType(annotation);
258             }
259         }
260         ObjectNode methodNode = mapper.createObjectNode();
261         methodNode.set("tags", tagArray);
262
263         addSummaryDescriptions(methodNode, comment);
264         addJsonSchemaDefinition(definitions, tag);
265
266         processParameters(javaMethod, methodNode, method, tag);
267
268         processConsumesProduces(methodNode, "consumes", consumes);
269         processConsumesProduces(methodNode, "produces", produces);
270         if (tag == null || ((method.toLowerCase().equals("post") || method.toLowerCase().equals("put"))
271                 && !(tag.getParameters().size() > 1))) {
272             addResponses(methodNode, tag, false);
273         } else {
274             addResponses(methodNode, tag, true);
275         }
276
277         ObjectNode operations = pathMap.get(fullPath);
278         if (operations == null) {
279             operations = mapper.createObjectNode();
280             operations.set(method, methodNode);
281             pathMap.put(fullPath, operations);
282         } else {
283             operations.set(method, methodNode);
284         }
285     }
286
287     private void addJsonSchemaDefinition(ObjectNode definitions, DocletTag tag) {
288         File definitionsDirectory = new File(srcDirectory + "/src/main/resources/definitions");
289         if (tag != null) {
290             tag.getParameters().stream().forEach(param -> {
291                 try {
292                     File config = new File(definitionsDirectory.getAbsolutePath() + "/"
293                                                    + param + ".json");
294                     String lines = Files.readLines(config, Charsets.UTF_8).stream().reduce((t, u) -> t + u).
295                             get();
296                     definitions.putPOJO(param, lines);
297                 } catch (IOException e) {
298                     e.printStackTrace();
299                 }
300             });
301
302         }
303     }
304
305     private void processConsumesProduces(ObjectNode methodNode, String type, String io) {
306         if (!io.equals("")) {
307             ArrayNode array = mapper.createArrayNode();
308             methodNode.set(type, array);
309             array.add(io);
310         }
311     }
312
313     private void addSummaryDescriptions(ObjectNode methodNode, String comment) {
314         String summary = "", description;
315         if (comment != null) {
316             if (comment.contains(".")) {
317                 int periodIndex = comment.indexOf(".");
318                 summary = comment.substring(0, periodIndex);
319                 description = comment.length() > periodIndex + 1 ?
320                         comment.substring(periodIndex + 1).trim() : "";
321             } else {
322                 description = comment;
323             }
324             methodNode.put("summary", summary);
325             methodNode.put("description", description);
326         }
327     }
328
329     // Temporary solution to add responses to a method
330     private void addResponses(ObjectNode methodNode, DocletTag tag, boolean responseJson) {
331         ObjectNode responses = mapper.createObjectNode();
332         methodNode.set("responses", responses);
333
334         ObjectNode success = mapper.createObjectNode();
335         success.put("description", "successful operation");
336         responses.set("200", success);
337         if (tag != null && responseJson) {
338             ObjectNode schema = mapper.createObjectNode();
339             tag.getParameters().stream().forEach(
340                     param -> schema.put("$ref", "#/definitions/" + param));
341             success.set("schema", schema);
342         }
343
344         ObjectNode defaultObj = mapper.createObjectNode();
345         defaultObj.put("description", "Unexpected error");
346         responses.set("default", defaultObj);
347     }
348
349     // Checks if the annotations has a value of JSON and returns the string
350     // that Swagger requires
351     private String getIOType(JavaAnnotation annotation) {
352         if (annotation.getNamedParameter("value").toString().equals(JSON)) {
353             return "application/json";
354         } else if (annotation.getNamedParameter("value").toString().equals(OCTET_STREAM)){
355             return "application/octet_stream";
356         }
357         return "";
358     }
359
360     // If the annotation has a Path tag, returns the value with leading and
361     // trailing double quotes and slash removed.
362     private String getPath(JavaAnnotation annotation) {
363         String path = annotation.getNamedParameter("value").toString();
364         return path == null ? null : path.replaceAll("(^[\\\"/]*|[/\\\"]*$)", "");
365     }
366
367     // Processes parameters of javaMethod and enters the proper key-values into the methodNode
368     private void processParameters(JavaMethod javaMethod, ObjectNode methodNode, String method, DocletTag tag) {
369         ArrayNode parameters = mapper.createArrayNode();
370         methodNode.set("parameters", parameters);
371         boolean required = true;
372
373         for (JavaParameter javaParameter : javaMethod.getParameters()) {
374             ObjectNode individualParameterNode = mapper.createObjectNode();
375             Optional<JavaAnnotation> optional = javaParameter.getAnnotations().stream().filter(
376                     annotation -> annotation.getType().getName().equals(PATH_PARAM) ||
377                             annotation.getType().getName().equals(QUERY_PARAM)).findAny();
378             JavaAnnotation pathType = optional.isPresent() ? optional.get() : null;
379
380             String annotationName = javaParameter.getName();
381
382
383             if (pathType != null) { //the parameter is a path or query parameter
384                 individualParameterNode.put("name",
385                                             pathType.getNamedParameter("value")
386                                                     .toString().replace("\"", ""));
387                 if (pathType.getType().getName().equals(PATH_PARAM)) {
388                     individualParameterNode.put("in", "path");
389                 } else if (pathType.getType().getName().equals(QUERY_PARAM)) {
390                     individualParameterNode.put("in", "query");
391                 }
392                 individualParameterNode.put("type", getType(javaParameter.getType()));
393             } else { // the parameter is a body parameter
394                 individualParameterNode.put("name", annotationName);
395                 individualParameterNode.put("in", "body");
396
397                 // Adds the reference to the Json model for the input
398                 // that goes in the post or put operation
399                 if (tag != null && (method.toLowerCase().equals("post") ||
400                         method.toLowerCase().equals("put"))) {
401                     ObjectNode schema = mapper.createObjectNode();
402                     tag.getParameters().stream().forEach(param -> {
403                         schema.put("$ref", "#/definitions/" + param);
404                     });
405                     individualParameterNode.set("schema", schema);
406                 }
407             }
408             for (DocletTag p : javaMethod.getTagsByName("param")) {
409                 if (p.getValue().contains(annotationName)) {
410                     try {
411                         String description = p.getValue().split(" ", 2)[1].trim();
412                         if (description.contains("optional")) {
413                             required = false;
414                         }
415                         individualParameterNode.put("description", description);
416                     } catch (Exception e) {
417                         e.printStackTrace();
418                     }
419                 }
420             }
421             individualParameterNode.put("required", required);
422             parameters.add(individualParameterNode);
423         }
424     }
425
426     // Returns the Swagger specified strings for the type of a parameter
427     private String getType(JavaType javaType) {
428         String type = javaType.getFullyQualifiedName();
429         String value;
430         if (type.equals(String.class.getName())) {
431             value = "string";
432         } else if (type.equals("int")) {
433             value = "integer";
434         } else if (type.equals(boolean.class.getName())) {
435             value = "boolean";
436         } else if (type.equals(long.class.getName())) {
437             value = "number";
438         } else {
439             value = "";
440         }
441         return value;
442     }
443
444     // Writes the swagger.json file using the supplied JSON root.
445     private void genCatalog(ObjectNode root) {
446         File swaggerCfg = new File(dstDirectory, JSON_FILE);
447         if (dstDirectory.exists() || dstDirectory.mkdirs()) {
448             try (FileWriter fw = new FileWriter(swaggerCfg);
449                  PrintWriter pw = new PrintWriter(fw)) {
450                 pw.println(root.toString());
451             } catch (IOException e) {
452                 getLog().warn("Unable to write " + JSON_FILE);
453             }
454         } else {
455             getLog().warn("Unable to create " + dstDirectory);
456         }
457     }
458
459     // Generates the registrator Java component.
460     private void genRegistrator() {
461         File dir = new File(dstDirectory, GEN_SRC);
462         File reg = new File(dir, apiPackage.replaceAll("\\.", "/") + "/ApiDocRegistrator.java");
463         File pkg = reg.getParentFile();
464         if (pkg.exists() || pkg.mkdirs()) {
465             try {
466                 String src = new String(ByteStreams.toByteArray(getClass().getResourceAsStream(REG_SRC)));
467                 src = src.replace("${api.package}", apiPackage)
468                         .replace("${web.context}", webContext)
469                         .replace("${api.title}", apiTitle)
470                         .replace("${api.description}", apiTitle);
471                 Files.write(src.getBytes(), reg);
472             } catch (IOException e) {
473                 getLog().warn("Unable to write " + reg);
474             }
475         } else {
476             getLog().warn("Unable to create " + reg);
477         }
478     }
479
480     // Returns "nickname" based on method and path for a REST method
481     private String setNickname(String method, String path) {
482         if (!path.equals("")) {
483             return (method + path.replace('/', '_').replace("{", "").replace("}", "")).toLowerCase();
484         } else {
485             return method.toLowerCase();
486         }
487     }
488
489     private String shortText(String comment) {
490         int i = comment.indexOf('.');
491         return i > 0 ? comment.substring(0, i) : comment;
492     }
493
494 }