blob: ea847459342c8b4e0348076257766bee7ca50aa1 [file] [log] [blame]
Sahil Lele372d1f32015-07-31 15:01:41 -07001/*
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 */
16package org.onosproject.maven;
17
18import com.fasterxml.jackson.databind.ObjectMapper;
19import com.fasterxml.jackson.databind.node.ArrayNode;
20import com.fasterxml.jackson.databind.node.ObjectNode;
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -070021import com.google.common.io.ByteStreams;
22import com.google.common.io.Files;
Sahil Lele372d1f32015-07-31 15:01:41 -070023import com.thoughtworks.qdox.JavaProjectBuilder;
24import com.thoughtworks.qdox.model.DocletTag;
25import com.thoughtworks.qdox.model.JavaAnnotation;
26import com.thoughtworks.qdox.model.JavaClass;
27import com.thoughtworks.qdox.model.JavaMethod;
28import com.thoughtworks.qdox.model.JavaParameter;
29import com.thoughtworks.qdox.model.JavaType;
30import org.apache.maven.plugin.AbstractMojo;
31import org.apache.maven.plugin.MojoExecutionException;
32import org.apache.maven.plugins.annotations.LifecyclePhase;
33import org.apache.maven.plugins.annotations.Mojo;
34import org.apache.maven.plugins.annotations.Parameter;
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -070035import org.apache.maven.project.MavenProject;
Sahil Lele372d1f32015-07-31 15:01:41 -070036
37import java.io.File;
38import java.io.FileWriter;
39import java.io.IOException;
40import java.io.PrintWriter;
41import java.util.HashMap;
42import java.util.Map;
43import java.util.Optional;
44
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -070045import static com.google.common.base.Strings.isNullOrEmpty;
46
Sahil Lele372d1f32015-07-31 15:01:41 -070047/**
48 * Produces ONOS Swagger api-doc.
49 */
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -070050@Mojo(name = "swagger", defaultPhase = LifecyclePhase.GENERATE_SOURCES)
Sahil Lele372d1f32015-07-31 15:01:41 -070051public class OnosSwaggerMojo extends AbstractMojo {
52 private final ObjectMapper mapper = new ObjectMapper();
53
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -070054 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
Sahil Lele372d1f32015-07-31 15:01:41 -070058 private static final String PATH = "javax.ws.rs.Path";
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -070059 private static final String PATH_PARAM = "javax.ws.rs.PathParam";
60 private static final String QUERY_PARAM = "javax.ws.rs.QueryParam";
Sahil Lele372d1f32015-07-31 15:01:41 -070061 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 */
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -070078 @Parameter(defaultValue = "${project.build.directory}")
Sahil Lele372d1f32015-07-31 15:01:41 -070079 protected File dstDirectory;
80
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -070081 /**
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
Sahil Lele372d1f32015-07-31 15:01:41 -0700118 @Override
119 public void execute() throws MojoExecutionException {
Sahil Lele372d1f32015-07-31 15:01:41 -0700120 try {
121 JavaProjectBuilder builder = new JavaProjectBuilder();
122 builder.addSourceTree(new File(srcDirectory, "src/main/java"));
123
124 ObjectNode root = initializeRoot();
Sahil Lele372d1f32015-07-31 15:01:41 -0700125 ArrayNode tags = mapper.createArrayNode();
Sahil Lele372d1f32015-07-31 15:01:41 -0700126 ObjectNode paths = mapper.createObjectNode();
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700127
128 root.set("tags", tags);
Sahil Lele372d1f32015-07-31 15:01:41 -0700129 root.set("paths", paths);
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700130
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
Sahil Lele372d1f32015-07-31 15:01:41 -0700144 } catch (Exception e) {
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700145 getLog().warn("Unable to generate ONOS REST API documentation", e);
Sahil Lele372d1f32015-07-31 15:01:41 -0700146 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);
Sahil Lele372d1f32015-07-31 15:01:41 -0700156
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700157 root.put("basePath", webContext);
158 info.put("version", apiVersion);
159 info.put("title", apiTitle);
160 info.put("description", apiDescription);
Sahil Lele372d1f32015-07-31 15:01:41 -0700161
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) {
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700176 // If the class does not have a Path tag then ignore it
177 JavaAnnotation annotation = getPathAnnotation(javaClass);
Sahil Lele372d1f32015-07-31 15:01:41 -0700178 if (annotation == null) {
179 return;
180 }
181
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700182 String path = getPath(annotation);
183 if (path == null) {
184 return;
Sahil Lele372d1f32015-07-31 15:01:41 -0700185 }
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700186
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);
Sahil Lele372d1f32015-07-31 15:01:41 -0700193 if (javaClass.getComment() != null) {
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700194 tagObject.put("description", shortText(javaClass.getComment()));
Sahil Lele372d1f32015-07-31 15:01:41 -0700195 }
196 tags.add(tagObject);
197
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700198 // Create an array node add to all methods from this class.
Sahil Lele372d1f32015-07-31 15:01:41 -0700199 ArrayNode tagArray = mapper.createArrayNode();
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700200 tagArray.add(tagPath);
Sahil Lele372d1f32015-07-31 15:01:41 -0700201
202 processAllMethods(javaClass, resourcePath, paths, tagArray);
203 }
204
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700205 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
Sahil Lele372d1f32015-07-31 15:01:41 -0700211 // 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,
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700238 Map<String, ObjectNode> pathMap,
239 String resourcePath, ArrayNode tagArray) {
Sahil Lele372d1f32015-07-31 15:01:41 -0700240 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)) {
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700245 fullPath = resourcePath + "/" + getPath(annotation);
246 fullPath = fullPath.replaceFirst("^//", "/");
Sahil Lele372d1f32015-07-31 15:01:41 -0700247 }
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
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700300 // Temporary solution to add responses to a method
Sahil Lele372d1f32015-07-31 15:01:41 -0700301 // 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
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700315 // Checks if the annotations has a value of JSON and returns the string
316 // that Swagger requires
Sahil Lele372d1f32015-07-31 15:01:41 -0700317 private String getIOType(JavaAnnotation annotation) {
318 if (annotation.getNamedParameter("value").toString().equals(JSON)) {
319 return "application/json";
320 }
321 return "";
322 }
323
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700324 // If the annotation has a Path tag, returns the value with leading and
325 // trailing double quotes and slash removed.
Sahil Lele372d1f32015-07-31 15:01:41 -0700326 private String getPath(JavaAnnotation annotation) {
327 String path = annotation.getNamedParameter("value").toString();
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700328 return path == null ? null : path.replaceAll("(^[\\\"/]*|[/\\\"]*$)", "");
Sahil Lele372d1f32015-07-31 15:01:41 -0700329 }
330
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700331 // Processes parameters of javaMethod and enters the proper key-values into the methodNode
Sahil Lele372d1f32015-07-31 15:01:41 -0700332 private void processParameters(JavaMethod javaMethod, ObjectNode methodNode) {
333 ArrayNode parameters = mapper.createArrayNode();
334 methodNode.set("parameters", parameters);
335 boolean required = true;
336
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700337 for (JavaParameter javaParameter : javaMethod.getParameters()) {
Sahil Lele372d1f32015-07-31 15:01:41 -0700338 ObjectNode individualParameterNode = mapper.createObjectNode();
339 Optional<JavaAnnotation> optional = javaParameter.getAnnotations().stream().filter(
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700340 annotation -> annotation.getType().getName().equals(PATH_PARAM) ||
341 annotation.getType().getName().equals(QUERY_PARAM)).findAny();
Sahil Lele372d1f32015-07-31 15:01:41 -0700342 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("\"", ""));
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700350 if (pathType.getType().getName().equals(PATH_PARAM)) {
Sahil Lele372d1f32015-07-31 15:01:41 -0700351 individualParameterNode.put("in", "path");
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700352 } else if (pathType.getType().getName().equals(QUERY_PARAM)) {
Sahil Lele372d1f32015-07-31 15:01:41 -0700353 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
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700383 // Returns the Swagger specified strings for the type of a parameter
Sahil Lele372d1f32015-07-31 15:01:41 -0700384 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
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700401 // 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);
Sahil Lele372d1f32015-07-31 15:01:41 -0700413 }
414 }
415
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700416 // 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
Sahil Lele372d1f32015-07-31 15:01:41 -0700438 private String setNickname(String method, String path) {
439 if (!path.equals("")) {
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700440 return (method + path.replace('/', '_').replace("{", "").replace("}", "")).toLowerCase();
Sahil Lele372d1f32015-07-31 15:01:41 -0700441 } else {
442 return method.toLowerCase();
443 }
444 }
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700445
446 private String shortText(String comment) {
447 int i = comment.indexOf('.');
448 return i > 0 ? comment.substring(0, i) : comment;
449 }
450
Sahil Lele372d1f32015-07-31 15:01:41 -0700451}