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