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