blob: 518bf8c6fd820ea30559271d3129ca512dde5be2 [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;
Ray Milkey275af2c2018-06-15 13:05:08 -070022import com.google.common.collect.ImmutableList;
Brian O'Connore8468b52016-07-25 13:42:36 -070023import com.google.common.io.ByteStreams;
24import com.google.common.io.Files;
25import com.thoughtworks.qdox.JavaProjectBuilder;
26import com.thoughtworks.qdox.model.DocletTag;
27import com.thoughtworks.qdox.model.JavaAnnotation;
28import com.thoughtworks.qdox.model.JavaClass;
29import com.thoughtworks.qdox.model.JavaMethod;
30import com.thoughtworks.qdox.model.JavaParameter;
31import com.thoughtworks.qdox.model.JavaType;
32
33import java.io.File;
34import java.io.FileWriter;
35import java.io.IOException;
36import java.io.PrintWriter;
Yuta HIGUCHIbcc2ce92018-03-07 16:42:11 -080037import java.time.Year;
Ray Milkey275af2c2018-06-15 13:05:08 -070038import java.util.Arrays;
Brian O'Connore8468b52016-07-25 13:42:36 -070039import java.util.HashMap;
40import java.util.List;
41import java.util.Map;
42import java.util.Optional;
43
44import static com.google.common.base.Strings.isNullOrEmpty;
45
46/**
47 * Generates Swagger JSON artifacts from the Java source files.
48 */
49public class SwaggerGenerator {
50
51 private final ObjectMapper mapper = new ObjectMapper();
52
53 private static final String JSON_FILE = "swagger.json";
54 private static final String GEN_SRC = "generated-sources";
55 private static final String REG_SRC = "/registrator.javat";
56
57 private static final String PATH = "javax.ws.rs.Path";
58 private static final String PATH_PARAM = "javax.ws.rs.PathParam";
59 private static final String QUERY_PARAM = "javax.ws.rs.QueryParam";
60 private static final String POST = "javax.ws.rs.POST";
slowrfaa9fce2017-10-17 15:59:04 -070061 private static final String PATCH = "javax.ws.rs.PATCH";
Brian O'Connore8468b52016-07-25 13:42:36 -070062 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 private static final String OCTET_STREAM = "MediaType.APPLICATION_OCTET_STREAM";
slowrac691982017-10-02 16:22:00 -070069 private static final String RESPONSES = "io.swagger.annotations.ApiResponses";
Brian O'Connore8468b52016-07-25 13:42:36 -070070
71 private final List<File> srcs;
72 private final List<File> resources;
73 private final File srcDirectory;
74 private final File resourceDirectory;
75 private final File genSrcOutputDirectory;
76 private final File genResourcesOutputDirectory;
77 private final String webContext;
78 private final String apiTitle;
79 private final String apiVersion;
80 private final String apiPackage;
81 private final String apiDescription;
82
Ray Milkey275af2c2018-06-15 13:05:08 -070083 private String x(File f) {
84 return f == null ? "null" : f.getAbsolutePath();
85 }
86
Brian O'Connore8468b52016-07-25 13:42:36 -070087 public SwaggerGenerator(List<File> srcs, List<File> resources,
88 File srcDirectory, File resourceDirectory,
89 File genSrcOutputDirectory, File genResourcesOutputDirectory,
90 String webContext, String apiTitle, String apiVersion,
91 String apiPackage, String apiDescription) {
92 this.srcs = srcs;
93 this.resources = resources;
94 this.srcDirectory = srcDirectory;
95 this.resourceDirectory = resourceDirectory;
96 this.genSrcOutputDirectory = genSrcOutputDirectory;
97 this.genResourcesOutputDirectory = genResourcesOutputDirectory;
98 this.webContext = webContext;
99
100 this.apiTitle = apiTitle;
101 this.apiVersion = apiVersion;
102 this.apiPackage = apiPackage;
103 this.apiDescription = apiDescription;
104 }
105
106 public void execute() {
107 try {
108 JavaProjectBuilder builder = new JavaProjectBuilder();
109 if (srcDirectory != null) {
110 builder.addSourceTree(new File(srcDirectory, "src/main/java"));
111 }
112 if (srcs != null) {
113 srcs.forEach(src -> {
Brian O'Connoree674952016-09-13 16:31:45 -0700114 if (src.toString().endsWith(".java")) {
115 try {
116 builder.addSource(src);
117 } catch (IOException e) {
118 throw new RuntimeException(e);
119 }
Brian O'Connore8468b52016-07-25 13:42:36 -0700120 }
121 });
122 }
123
124 ObjectNode root = initializeRoot(webContext, apiTitle, apiVersion, apiDescription);
125 ArrayNode tags = mapper.createArrayNode();
126 ObjectNode paths = mapper.createObjectNode();
127 ObjectNode definitions = mapper.createObjectNode();
128
129 root.set("tags", tags);
130 root.set("paths", paths);
131 root.set("definitions", definitions);
132
133 // TODO: Process resources to allow lookup of files by name
134
135 builder.getClasses().forEach(jc -> processClass(jc, paths, tags, definitions, srcDirectory));
136
137 if (paths.size() > 0) {
138 genCatalog(genResourcesOutputDirectory, root);
139 if (!isNullOrEmpty(apiPackage)) {
140 genRegistrator(genSrcOutputDirectory, webContext, apiTitle, apiVersion,
141 apiPackage, apiDescription);
142 }
143 }
144 } catch (Exception e) {
145 e.printStackTrace();
146 throw new RuntimeException("Unable to generate ONOS REST API documentation", e);
147 }
148 }
149
150 // initializes top level root with Swagger required specifications
151 private ObjectNode initializeRoot(String webContext, String apiTitle,
152 String apiVersion, String apiDescription) {
153 ObjectNode root = mapper.createObjectNode();
154 root.put("swagger", "2.0");
155 ObjectNode info = mapper.createObjectNode();
156 root.set("info", info);
157
158 root.put("basePath", webContext);
159 info.put("version", apiVersion);
160 info.put("title", apiTitle);
161 info.put("description", apiDescription);
162
163 ArrayNode produces = mapper.createArrayNode();
164 produces.add("application/json");
165 root.set("produces", produces);
166
167 ArrayNode consumes = mapper.createArrayNode();
168 consumes.add("application/json");
169 root.set("consumes", consumes);
170
171 return root;
172 }
173
174 // Checks whether javaClass has a path tag associated with it and if it does
175 // processes its methods and creates a tag for the class on the root
176 void processClass(JavaClass javaClass, ObjectNode paths, ArrayNode tags,
177 ObjectNode definitions, File srcDirectory) {
178 // If the class does not have a Path tag then ignore it
179 JavaAnnotation annotation = getPathAnnotation(javaClass);
180 if (annotation == null) {
181 return;
182 }
183
184 String path = getPath(annotation);
185 if (path == null) {
186 return;
187 }
188
189 String resourcePath = "/" + path;
190 String tagPath = path.isEmpty() ? "/" : path;
191
192 // Create tag node for this class.
193 ObjectNode tagObject = mapper.createObjectNode();
194 tagObject.put("name", tagPath);
195 if (javaClass.getComment() != null) {
196 tagObject.put("description", shortText(javaClass.getComment()));
197 }
198 tags.add(tagObject);
199
200 // Create an array node add to all methods from this class.
201 ArrayNode tagArray = mapper.createArrayNode();
202 tagArray.add(tagPath);
203
204 processAllMethods(javaClass, resourcePath, paths, tagArray, definitions, srcDirectory);
205 }
206
207 private JavaAnnotation getPathAnnotation(JavaClass javaClass) {
208 Optional<JavaAnnotation> optional = javaClass.getAnnotations()
209 .stream().filter(a -> a.getType().getName().equals(PATH)).findAny();
210 return optional.orElse(null);
211 }
212
213 // Checks whether a class's methods are REST methods and then places all the
214 // methods under a specific path into the paths node
215 private void processAllMethods(JavaClass javaClass, String resourcePath,
216 ObjectNode paths, ArrayNode tagArray, ObjectNode definitions,
217 File srcDirectory) {
218 // map of the path to its methods represented by an ObjectNode
219 Map<String, ObjectNode> pathMap = new HashMap<>();
220
221 javaClass.getMethods().forEach(javaMethod -> {
222 javaMethod.getAnnotations().forEach(annotation -> {
223 String name = annotation.getType().getName();
slowrfaa9fce2017-10-17 15:59:04 -0700224 if (name.equals(PATCH) || name.equals(POST) || name.equals(GET) || name.equals(DELETE) ||
225 name.equals(PUT)) {
Brian O'Connore8468b52016-07-25 13:42:36 -0700226 // substring(12) removes "javax.ws.rs."
227 String method = annotation.getType().toString().substring(12).toLowerCase();
228 processRestMethod(javaMethod, method, pathMap, resourcePath, tagArray, definitions, srcDirectory);
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,
244 ObjectNode definitions, File srcDirectory) {
245 String fullPath = resourcePath, consumes = "", produces = "",
246 comment = javaMethod.getComment();
247 DocletTag tag = javaMethod.getTagByName("onos.rsModel");
248 for (JavaAnnotation annotation : javaMethod.getAnnotations()) {
249 String name = annotation.getType().getName();
250 if (name.equals(PATH)) {
251 fullPath = resourcePath + "/" + getPath(annotation);
252 fullPath = fullPath.replaceFirst("^//", "/");
253 }
254 if (name.equals(CONSUMES)) {
255 consumes = getIOType(annotation);
256 }
257 if (name.equals(PRODUCES)) {
258 produces = getIOType(annotation);
259 }
260 }
261 ObjectNode methodNode = mapper.createObjectNode();
262 methodNode.set("tags", tagArray);
263
264 addSummaryDescriptions(methodNode, comment);
265 addJsonSchemaDefinition(srcDirectory, definitions, tag);
266
267 processParameters(javaMethod, methodNode, method, tag);
268
269 processConsumesProduces(methodNode, "consumes", consumes);
270 processConsumesProduces(methodNode, "produces", produces);
slowrac691982017-10-02 16:22:00 -0700271 if (tag == null || !(tag.getParameters().size() > 1)) {
272 addResponses(javaMethod, methodNode, tag, false);
Brian O'Connore8468b52016-07-25 13:42:36 -0700273 } else {
slowrac691982017-10-02 16:22:00 -0700274 addResponses(javaMethod, methodNode, tag, true);
Brian O'Connore8468b52016-07-25 13:42:36 -0700275 }
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(File srcDirectory, ObjectNode definitions, DocletTag tag) {
288 final File definitionsDirectory;
289 if (resourceDirectory != null) {
290 definitionsDirectory = new File(resourceDirectory, "definitions");
291 } else if (srcDirectory != null) {
292 definitionsDirectory = new File(srcDirectory + "/src/main/resources/definitions");
293 } else {
294 definitionsDirectory = null;
295 }
296 if (tag != null) {
297 tag.getParameters().forEach(param -> {
298 try {
299 File config;
300 if (definitionsDirectory != null) {
301 config = new File(definitionsDirectory.getAbsolutePath() + "/" + param + ".json");
302 } else {
303 config = resources.stream().filter(f -> f.getName().equals(param + ".json")).findFirst().orElse(null);
304 }
305 definitions.set(param, mapper.readTree(config));
306 } catch (IOException e) {
307 throw new RuntimeException(String.format("Could not process %s in %s@%s: %s",
308 tag.getName(), tag.getContext(), tag.getLineNumber(),
309 e.getMessage()), e);
310 }
311 });
312 }
313 }
314
315 private void processConsumesProduces(ObjectNode methodNode, String type, String io) {
316 if (!io.equals("")) {
317 ArrayNode array = mapper.createArrayNode();
318 methodNode.set(type, array);
319 array.add(io);
320 }
321 }
322
323 private void addSummaryDescriptions(ObjectNode methodNode, String comment) {
324 String summary = "", description;
325 if (comment != null) {
326 if (comment.contains(".")) {
327 int periodIndex = comment.indexOf(".");
328 summary = comment.substring(0, periodIndex);
329 description = comment.length() > periodIndex + 1 ?
330 comment.substring(periodIndex + 1).trim() : "";
331 } else {
332 description = comment;
333 }
334 methodNode.put("summary", summary);
335 methodNode.put("description", description);
336 }
337 }
338
slowrac691982017-10-02 16:22:00 -0700339 private Optional<JavaAnnotation> getResponsesAnnotation(JavaMethod javaMethod) {
340 return javaMethod.getAnnotations().stream().filter(
341 a -> a.getType().getName().equals(RESPONSES)
342 ).findAny();
343 }
344
345 // TODO: add json schema for responses
346 private void addResponses(JavaMethod javaMethod, ObjectNode methodNode, DocletTag tag, boolean responseJson) {
Brian O'Connore8468b52016-07-25 13:42:36 -0700347 ObjectNode responses = mapper.createObjectNode();
348 methodNode.set("responses", responses);
349
slowrac691982017-10-02 16:22:00 -0700350 Optional<JavaAnnotation> responsesAnnotation = getResponsesAnnotation(javaMethod);
Brian O'Connore8468b52016-07-25 13:42:36 -0700351
slowrac691982017-10-02 16:22:00 -0700352 if (responsesAnnotation.isPresent()) {
353 Object annotationsObj = responsesAnnotation.get().getNamedParameter("value");
354 if (annotationsObj != null && annotationsObj instanceof List) {
355 List<JavaAnnotation> responseAnnotation = (List<JavaAnnotation>) annotationsObj;
356 responseAnnotation.forEach(
357 javaAnnotation -> {
358 ObjectNode response = mapper.createObjectNode();
359 response.put("description",
360 String.valueOf(javaAnnotation.getNamedParameter("message"))
361 .replaceAll("^\"|\"$", ""));
362 responses.set(String.valueOf(javaAnnotation.getNamedParameter("code")), response);
363 }
364 );
365 }
366 } else {
367 ObjectNode success = mapper.createObjectNode();
368 success.put("description", "successful operation");
369 responses.set("200", success);
370
371 ObjectNode defaultObj = mapper.createObjectNode();
372 defaultObj.put("description", "Unexpected error");
373 responses.set("default", defaultObj);
374
375 if (tag != null && responseJson) {
376 ObjectNode schema = mapper.createObjectNode();
377 tag.getParameters().stream().forEach(
378 param -> schema.put("$ref", "#/definitions/" + param));
379 success.set("schema", schema);
380 }
381 }
Brian O'Connore8468b52016-07-25 13:42:36 -0700382 }
383
384 // Checks if the annotations has a value of JSON and returns the string
385 // that Swagger requires
386 private String getIOType(JavaAnnotation annotation) {
387 if (annotation.getNamedParameter("value").toString().equals(JSON)) {
388 return "application/json";
389 } else if (annotation.getNamedParameter("value").toString().equals(OCTET_STREAM)) {
390 return "application/octet_stream";
391 }
392 return "";
393 }
394
395 // If the annotation has a Path tag, returns the value with leading and
396 // trailing double quotes and slash removed.
397 private String getPath(JavaAnnotation annotation) {
398 String path = annotation.getNamedParameter("value").toString();
399 return path == null ? null : path.replaceAll("(^[\\\"/]*|[/\\\"]*$)", "");
400 }
401
402 // Processes parameters of javaMethod and enters the proper key-values into the methodNode
403 private void processParameters(JavaMethod javaMethod, ObjectNode methodNode, String method, DocletTag tag) {
404 ArrayNode parameters = mapper.createArrayNode();
405 methodNode.set("parameters", parameters);
406 boolean required = true;
407
408 for (JavaParameter javaParameter : javaMethod.getParameters()) {
409 ObjectNode individualParameterNode = mapper.createObjectNode();
410 Optional<JavaAnnotation> optional = javaParameter.getAnnotations().stream().filter(
411 annotation -> annotation.getType().getName().equals(PATH_PARAM) ||
412 annotation.getType().getName().equals(QUERY_PARAM)).findAny();
413 JavaAnnotation pathType = optional.orElse(null);
414
415 String annotationName = javaParameter.getName();
416
417
418 if (pathType != null) { //the parameter is a path or query parameter
419 individualParameterNode.put("name",
420 pathType.getNamedParameter("value")
421 .toString().replace("\"", ""));
422 if (pathType.getType().getName().equals(PATH_PARAM)) {
423 individualParameterNode.put("in", "path");
424 } else if (pathType.getType().getName().equals(QUERY_PARAM)) {
425 individualParameterNode.put("in", "query");
426 }
427 individualParameterNode.put("type", getType(javaParameter.getType()));
428 } else { // the parameter is a body parameter
429 individualParameterNode.put("name", annotationName);
430 individualParameterNode.put("in", "body");
431
432 // Adds the reference to the Json model for the input
433 // that goes in the post or put operation
434 if (tag != null && (method.toLowerCase().equals("post") ||
435 method.toLowerCase().equals("put"))) {
436 ObjectNode schema = mapper.createObjectNode();
437 tag.getParameters().stream().forEach(param -> {
438 schema.put("$ref", "#/definitions/" + param);
439 });
440 individualParameterNode.set("schema", schema);
441 }
442 }
443 for (DocletTag p : javaMethod.getTagsByName("param")) {
444 if (p.getValue().contains(annotationName)) {
445 String description = "";
446 if (p.getValue().split(" ", 2).length >= 2) {
447 description = p.getValue().split(" ", 2)[1].trim();
448 if (description.contains("optional")) {
449 required = false;
450 }
451 } else {
452 throw new RuntimeException(String.format("No description for parameter \"%s\" in " +
453 "method \"%s\" in %s (line %d)",
454 p.getValue(), javaMethod.getName(),
455 javaMethod.getDeclaringClass().getName(),
456 javaMethod.getLineNumber()));
457 }
458 individualParameterNode.put("description", description);
459 }
460 }
461 individualParameterNode.put("required", required);
462 parameters.add(individualParameterNode);
463 }
464 }
465
466 // Returns the Swagger specified strings for the type of a parameter
467 private String getType(JavaType javaType) {
468 String type = javaType.getFullyQualifiedName();
469 String value;
470 if (type.equals(String.class.getName())) {
471 value = "string";
472 } else if (type.equals("int")) {
473 value = "integer";
474 } else if (type.equals(boolean.class.getName())) {
475 value = "boolean";
476 } else if (type.equals(long.class.getName())) {
477 value = "number";
478 } else {
479 value = "";
480 }
481 return value;
482 }
483
484 // Writes the swagger.json file using the supplied JSON root.
485 private void genCatalog(File dstDirectory, ObjectNode root) {
486 File swaggerCfg = new File(dstDirectory, JSON_FILE);
487 if (dstDirectory.exists() || dstDirectory.mkdirs()) {
488 try (FileWriter fw = new FileWriter(swaggerCfg);
489 PrintWriter pw = new PrintWriter(fw)) {
490 pw.println(root.toString());
491 } catch (IOException e) {
492 throw new RuntimeException("Unable to write " + JSON_FILE, e);
493 }
494 } else {
495 throw new RuntimeException("Unable to create " + dstDirectory);
496 }
497 }
498
499 // Generates the registrator Java component.
500 private void genRegistrator(File dstDirectory, String webContext,
501 String apiTitle, String apiVersion,
502 String apiPackage, String apiDescription) {
503 File dir = new File(dstDirectory, resourceDirectory != null ? GEN_SRC : ".");
504 File reg = new File(dir, apiRegistratorPath(apiPackage));
505 File pkg = reg.getParentFile();
506 if (pkg.exists() || pkg.mkdirs()) {
507 try {
508 String src = new String(ByteStreams.toByteArray(getClass().getResourceAsStream(REG_SRC)));
509 src = src.replace("${api.package}", apiPackage)
510 .replace("${web.context}", webContext)
511 .replace("${api.title}", apiTitle)
Yuta HIGUCHIbcc2ce92018-03-07 16:42:11 -0800512 .replace("${api.description}", apiDescription)
513 .replace("${year}", Year.now().toString());
514
Brian O'Connore8468b52016-07-25 13:42:36 -0700515 Files.write(src.getBytes(), reg);
516 } catch (IOException e) {
517 throw new RuntimeException("Unable to write " + reg, e);
518 }
519 } else {
520 throw new RuntimeException("Unable to create " + reg);
521 }
522 }
523
524 private String shortText(String comment) {
525 int i = comment.indexOf('.');
526 return i > 0 ? comment.substring(0, i) : comment;
527 }
528
529 public static String apiRegistratorPath(String apiPackage) {
530 return apiPackage.replaceAll("\\.", "/") + "/ApiDocRegistrator.java";
531 }
Ray Milkey275af2c2018-06-15 13:05:08 -0700532
533 private static List<File> getFiles(String commaSeparatedList) {
534 String[] fileNames = commaSeparatedList.split(",");
535 ImmutableList.Builder<File> files = ImmutableList.builder();
536 Arrays.stream(fileNames).forEach(filename -> files.add(new File(filename)));
537 return files.build();
538 }
539
540 public static void main(String args[]) {
541 List<File> srcs = getFiles(args[0]);
542 List<File> resources = getFiles(args[1]);
543 File srcDirectory = null;//new File(args[2]);
544 File resourceDirectory = new File(args[3]);
545 File genSrcOutputDirectory = new File(args[4]);
546 File genResourcesOutputDirectory = new File(args[5]);
547 String webContext = args[6];
548 String apiTitle = args[7];
549 String apiVersion = args[8];
550 String apiPackage = args[9];
551 String apiDescription = args[10];
552
553 SwaggerGenerator generator = new SwaggerGenerator(
554 srcs,
555 resources,
556 srcDirectory, resourceDirectory,
557 genSrcOutputDirectory,
558 genResourcesOutputDirectory,
559 webContext,
560 apiTitle,
561 apiVersion,
562 apiPackage,
563 apiDescription);
564 generator.execute();
565 }
Brian O'Connore8468b52016-07-25 13:42:36 -0700566}