ea847459342c8b4e0348076257766bee7ca50aa1
[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.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;
36
37 import java.io.File;
38 import java.io.FileWriter;
39 import java.io.IOException;
40 import java.io.PrintWriter;
41 import java.util.HashMap;
42 import java.util.Map;
43 import java.util.Optional;
44
45 import static com.google.common.base.Strings.isNullOrEmpty;
46
47 /**
48  * Produces ONOS Swagger api-doc.
49  */
50 @Mojo(name = "swagger", defaultPhase = LifecyclePhase.GENERATE_SOURCES)
51 public class OnosSwaggerMojo extends AbstractMojo {
52     private final ObjectMapper mapper = new ObjectMapper();
53
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";
57
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";
68
69     /**
70      * The directory where the generated catalogue file will be put.
71      */
72     @Parameter(defaultValue = "${basedir}")
73     protected File srcDirectory;
74
75     /**
76      * The directory where the generated catalogue file will be put.
77      */
78     @Parameter(defaultValue = "${project.build.directory}")
79     protected File dstDirectory;
80
81     /**
82      * REST API web-context
83      */
84     @Parameter(defaultValue = "${web.context}")
85     protected String webContext;
86
87     /**
88      * REST API version
89      */
90     @Parameter(defaultValue = "${api.version}")
91     protected String apiVersion;
92
93     /**
94      * REST API description
95      */
96     @Parameter(defaultValue = "${api.description}")
97     protected String apiDescription;
98
99     /**
100      * REST API title
101      */
102     @Parameter(defaultValue = "${api.title}")
103     protected String apiTitle;
104
105     /**
106      * REST API title
107      */
108     @Parameter(defaultValue = "${api.package}")
109     protected String apiPackage;
110
111     /**
112      * Maven project
113      */
114     @Parameter(defaultValue = "${project}")
115     protected MavenProject project;
116
117
118     @Override
119     public void execute() throws MojoExecutionException {
120         try {
121             JavaProjectBuilder builder = new JavaProjectBuilder();
122             builder.addSourceTree(new File(srcDirectory, "src/main/java"));
123
124             ObjectNode root = initializeRoot();
125             ArrayNode tags = mapper.createArrayNode();
126             ObjectNode paths = mapper.createObjectNode();
127
128             root.set("tags", tags);
129             root.set("paths", paths);
130
131             builder.getClasses().forEach(jc -> processClass(jc, paths, tags));
132
133             if (paths.size() > 0) {
134                 getLog().info("Generating ONOS REST API documentation...");
135                 genCatalog(root);
136
137                 if (!isNullOrEmpty(apiPackage)) {
138                     genRegistrator();
139                 }
140             }
141
142             project.addCompileSourceRoot(new File(dstDirectory, GEN_SRC).getPath());
143
144         } catch (Exception e) {
145             getLog().warn("Unable to generate ONOS REST API documentation", e);
146             throw e;
147         }
148     }
149
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);
156
157         root.put("basePath", webContext);
158         info.put("version", apiVersion);
159         info.put("title", apiTitle);
160         info.put("description", apiDescription);
161
162         ArrayNode produces = mapper.createArrayNode();
163         produces.add("application/json");
164         root.set("produces", produces);
165
166         ArrayNode consumes = mapper.createArrayNode();
167         consumes.add("application/json");
168         root.set("consumes", consumes);
169
170         return root;
171     }
172
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) {
179             return;
180         }
181
182         String path = getPath(annotation);
183         if (path == null) {
184             return;
185         }
186
187         String resourcePath = "/" + path;
188         String tagPath = path.isEmpty() ? "/" : path;
189
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()));
195         }
196         tags.add(tagObject);
197
198         // Create an array node add to all methods from this class.
199         ArrayNode tagArray = mapper.createArrayNode();
200         tagArray.add(tagPath);
201
202         processAllMethods(javaClass, resourcePath, paths, tagArray);
203     }
204
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;
209     }
210
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<>();
217
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);
225                 }
226             });
227         });
228
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());
232         }
233
234
235     }
236
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("^//", "/");
247             }
248             if (name.equals(CONSUMES)) {
249                 consumes = getIOType(annotation);
250             }
251             if (name.equals(PRODUCES)) {
252                 produces = getIOType(annotation);
253             }
254         }
255         ObjectNode methodNode = mapper.createObjectNode();
256         methodNode.set("tags", tagArray);
257
258         addSummaryDescriptions(methodNode, comment);
259         processParameters(javaMethod, methodNode);
260
261         processConsumesProduces(methodNode, "consumes", consumes);
262         processConsumesProduces(methodNode, "produces", produces);
263
264         addResponses(methodNode);
265
266         ObjectNode operations = pathMap.get(fullPath);
267         if (operations == null) {
268             operations = mapper.createObjectNode();
269             operations.set(method, methodNode);
270             pathMap.put(fullPath, operations);
271         } else {
272             operations.set(method, methodNode);
273         }
274     }
275
276     private void processConsumesProduces(ObjectNode methodNode, String type, String io) {
277         if (!io.equals("")) {
278             ArrayNode array = mapper.createArrayNode();
279             methodNode.set(type, array);
280             array.add(io);
281         }
282     }
283
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() : "";
292             } else {
293                 description = comment;
294             }
295             methodNode.put("summary", summary);
296             methodNode.put("description", description);
297         }
298     }
299
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);
305
306         ObjectNode success = mapper.createObjectNode();
307         success.put("description", "successful operation");
308         responses.set("200", success);
309
310         ObjectNode defaultObj = mapper.createObjectNode();
311         defaultObj.put("description", "Unexpected error");
312         responses.set("default", defaultObj);
313     }
314
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";
320         }
321         return "";
322     }
323
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("(^[\\\"/]*|[/\\\"]*$)", "");
329     }
330
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;
336
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;
343
344             String annotationName = javaParameter.getName();
345
346
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");
354                 }
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");
359
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);
364             }
365             for (DocletTag p : javaMethod.getTagsByName("param")) {
366                 if (p.getValue().contains(annotationName)) {
367                     try {
368                         String description = p.getValue().split(" ", 2)[1].trim();
369                         if (description.contains("optional")) {
370                             required = false;
371                         }
372                         individualParameterNode.put("description", description);
373                     } catch (Exception e) {
374                         e.printStackTrace();
375                     }
376                 }
377             }
378             individualParameterNode.put("required", required);
379             parameters.add(individualParameterNode);
380         }
381     }
382
383     // Returns the Swagger specified strings for the type of a parameter
384     private String getType(JavaType javaType) {
385         String type = javaType.getFullyQualifiedName();
386         String value;
387         if (type.equals(String.class.getName())) {
388             value = "string";
389         } else if (type.equals("int")) {
390             value = "integer";
391         } else if (type.equals(boolean.class.getName())) {
392             value = "boolean";
393         } else if (type.equals(long.class.getName())) {
394             value = "number";
395         } else {
396             value = "";
397         }
398         return value;
399     }
400
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);
410             }
411         } else {
412             getLog().warn("Unable to create " + dstDirectory);
413         }
414     }
415
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()) {
422             try {
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);
431             }
432         } else {
433             getLog().warn("Unable to create " + reg);
434         }
435     }
436
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();
441         } else {
442             return method.toLowerCase();
443         }
444     }
445
446     private String shortText(String comment) {
447         int i = comment.indexOf('.');
448         return i > 0 ? comment.substring(0, i) : comment;
449     }
450
451 }