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