blob: 217316102adf321b330d1c147cf7e6fc3b4f31a8 [file] [log] [blame]
Brian O'Connore8468b52016-07-25 13:42:36 -07001/*
Brian O'Connor0a4e6742016-09-15 23:03:10 -07002 * Copyright 2016-present Open Networking Laboratory
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";
65
66 private final List<File> srcs;
67 private final List<File> resources;
68 private final File srcDirectory;
69 private final File resourceDirectory;
70 private final File genSrcOutputDirectory;
71 private final File genResourcesOutputDirectory;
72 private final String webContext;
73 private final String apiTitle;
74 private final String apiVersion;
75 private final String apiPackage;
76 private final String apiDescription;
77
78 public SwaggerGenerator(List<File> srcs, List<File> resources,
79 File srcDirectory, File resourceDirectory,
80 File genSrcOutputDirectory, File genResourcesOutputDirectory,
81 String webContext, String apiTitle, String apiVersion,
82 String apiPackage, String apiDescription) {
83 this.srcs = srcs;
84 this.resources = resources;
85 this.srcDirectory = srcDirectory;
86 this.resourceDirectory = resourceDirectory;
87 this.genSrcOutputDirectory = genSrcOutputDirectory;
88 this.genResourcesOutputDirectory = genResourcesOutputDirectory;
89 this.webContext = webContext;
90
91 this.apiTitle = apiTitle;
92 this.apiVersion = apiVersion;
93 this.apiPackage = apiPackage;
94 this.apiDescription = apiDescription;
95 }
96
97 public void execute() {
98 try {
99 JavaProjectBuilder builder = new JavaProjectBuilder();
100 if (srcDirectory != null) {
101 builder.addSourceTree(new File(srcDirectory, "src/main/java"));
102 }
103 if (srcs != null) {
104 srcs.forEach(src -> {
Brian O'Connoree674952016-09-13 16:31:45 -0700105 if (src.toString().endsWith(".java")) {
106 try {
107 builder.addSource(src);
108 } catch (IOException e) {
109 throw new RuntimeException(e);
110 }
Brian O'Connore8468b52016-07-25 13:42:36 -0700111 }
112 });
113 }
114
115 ObjectNode root = initializeRoot(webContext, apiTitle, apiVersion, apiDescription);
116 ArrayNode tags = mapper.createArrayNode();
117 ObjectNode paths = mapper.createObjectNode();
118 ObjectNode definitions = mapper.createObjectNode();
119
120 root.set("tags", tags);
121 root.set("paths", paths);
122 root.set("definitions", definitions);
123
124 // TODO: Process resources to allow lookup of files by name
125
126 builder.getClasses().forEach(jc -> processClass(jc, paths, tags, definitions, srcDirectory));
127
128 if (paths.size() > 0) {
129 genCatalog(genResourcesOutputDirectory, root);
130 if (!isNullOrEmpty(apiPackage)) {
131 genRegistrator(genSrcOutputDirectory, webContext, apiTitle, apiVersion,
132 apiPackage, apiDescription);
133 }
134 }
135 } catch (Exception e) {
136 e.printStackTrace();
137 throw new RuntimeException("Unable to generate ONOS REST API documentation", e);
138 }
139 }
140
141 // initializes top level root with Swagger required specifications
142 private ObjectNode initializeRoot(String webContext, String apiTitle,
143 String apiVersion, String apiDescription) {
144 ObjectNode root = mapper.createObjectNode();
145 root.put("swagger", "2.0");
146 ObjectNode info = mapper.createObjectNode();
147 root.set("info", info);
148
149 root.put("basePath", webContext);
150 info.put("version", apiVersion);
151 info.put("title", apiTitle);
152 info.put("description", apiDescription);
153
154 ArrayNode produces = mapper.createArrayNode();
155 produces.add("application/json");
156 root.set("produces", produces);
157
158 ArrayNode consumes = mapper.createArrayNode();
159 consumes.add("application/json");
160 root.set("consumes", consumes);
161
162 return root;
163 }
164
165 // Checks whether javaClass has a path tag associated with it and if it does
166 // processes its methods and creates a tag for the class on the root
167 void processClass(JavaClass javaClass, ObjectNode paths, ArrayNode tags,
168 ObjectNode definitions, File srcDirectory) {
169 // If the class does not have a Path tag then ignore it
170 JavaAnnotation annotation = getPathAnnotation(javaClass);
171 if (annotation == null) {
172 return;
173 }
174
175 String path = getPath(annotation);
176 if (path == null) {
177 return;
178 }
179
180 String resourcePath = "/" + path;
181 String tagPath = path.isEmpty() ? "/" : path;
182
183 // Create tag node for this class.
184 ObjectNode tagObject = mapper.createObjectNode();
185 tagObject.put("name", tagPath);
186 if (javaClass.getComment() != null) {
187 tagObject.put("description", shortText(javaClass.getComment()));
188 }
189 tags.add(tagObject);
190
191 // Create an array node add to all methods from this class.
192 ArrayNode tagArray = mapper.createArrayNode();
193 tagArray.add(tagPath);
194
195 processAllMethods(javaClass, resourcePath, paths, tagArray, definitions, srcDirectory);
196 }
197
198 private JavaAnnotation getPathAnnotation(JavaClass javaClass) {
199 Optional<JavaAnnotation> optional = javaClass.getAnnotations()
200 .stream().filter(a -> a.getType().getName().equals(PATH)).findAny();
201 return optional.orElse(null);
202 }
203
204 // Checks whether a class's methods are REST methods and then places all the
205 // methods under a specific path into the paths node
206 private void processAllMethods(JavaClass javaClass, String resourcePath,
207 ObjectNode paths, ArrayNode tagArray, ObjectNode definitions,
208 File srcDirectory) {
209 // map of the path to its methods represented by an ObjectNode
210 Map<String, ObjectNode> pathMap = new HashMap<>();
211
212 javaClass.getMethods().forEach(javaMethod -> {
213 javaMethod.getAnnotations().forEach(annotation -> {
214 String name = annotation.getType().getName();
215 if (name.equals(POST) || name.equals(GET) || name.equals(DELETE) || name.equals(PUT)) {
216 // substring(12) removes "javax.ws.rs."
217 String method = annotation.getType().toString().substring(12).toLowerCase();
218 processRestMethod(javaMethod, method, pathMap, resourcePath, tagArray, definitions, srcDirectory);
219 }
220 });
221 });
222
223 // for each path add its methods to the path node
224 for (Map.Entry<String, ObjectNode> entry : pathMap.entrySet()) {
225 paths.set(entry.getKey(), entry.getValue());
226 }
227
228
229 }
230
231 private void processRestMethod(JavaMethod javaMethod, String method,
232 Map<String, ObjectNode> pathMap,
233 String resourcePath, ArrayNode tagArray,
234 ObjectNode definitions, File srcDirectory) {
235 String fullPath = resourcePath, consumes = "", produces = "",
236 comment = javaMethod.getComment();
237 DocletTag tag = javaMethod.getTagByName("onos.rsModel");
238 for (JavaAnnotation annotation : javaMethod.getAnnotations()) {
239 String name = annotation.getType().getName();
240 if (name.equals(PATH)) {
241 fullPath = resourcePath + "/" + getPath(annotation);
242 fullPath = fullPath.replaceFirst("^//", "/");
243 }
244 if (name.equals(CONSUMES)) {
245 consumes = getIOType(annotation);
246 }
247 if (name.equals(PRODUCES)) {
248 produces = getIOType(annotation);
249 }
250 }
251 ObjectNode methodNode = mapper.createObjectNode();
252 methodNode.set("tags", tagArray);
253
254 addSummaryDescriptions(methodNode, comment);
255 addJsonSchemaDefinition(srcDirectory, definitions, tag);
256
257 processParameters(javaMethod, methodNode, method, tag);
258
259 processConsumesProduces(methodNode, "consumes", consumes);
260 processConsumesProduces(methodNode, "produces", produces);
261 if (tag == null || ((method.toLowerCase().equals("post") || method.toLowerCase().equals("put"))
262 && !(tag.getParameters().size() > 1))) {
263 addResponses(methodNode, tag, false);
264 } else {
265 addResponses(methodNode, tag, true);
266 }
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
330 // Temporary solution to add responses to a method
331 private void addResponses(ObjectNode methodNode, DocletTag tag, boolean responseJson) {
332 ObjectNode responses = mapper.createObjectNode();
333 methodNode.set("responses", responses);
334
335 ObjectNode success = mapper.createObjectNode();
336 success.put("description", "successful operation");
337 responses.set("200", success);
338 if (tag != null && responseJson) {
339 ObjectNode schema = mapper.createObjectNode();
340 tag.getParameters().stream().forEach(
341 param -> schema.put("$ref", "#/definitions/" + param));
342 success.set("schema", schema);
343 }
344
345 ObjectNode defaultObj = mapper.createObjectNode();
346 defaultObj.put("description", "Unexpected error");
347 responses.set("default", defaultObj);
348 }
349
350 // Checks if the annotations has a value of JSON and returns the string
351 // that Swagger requires
352 private String getIOType(JavaAnnotation annotation) {
353 if (annotation.getNamedParameter("value").toString().equals(JSON)) {
354 return "application/json";
355 } else if (annotation.getNamedParameter("value").toString().equals(OCTET_STREAM)) {
356 return "application/octet_stream";
357 }
358 return "";
359 }
360
361 // If the annotation has a Path tag, returns the value with leading and
362 // trailing double quotes and slash removed.
363 private String getPath(JavaAnnotation annotation) {
364 String path = annotation.getNamedParameter("value").toString();
365 return path == null ? null : path.replaceAll("(^[\\\"/]*|[/\\\"]*$)", "");
366 }
367
368 // Processes parameters of javaMethod and enters the proper key-values into the methodNode
369 private void processParameters(JavaMethod javaMethod, ObjectNode methodNode, String method, DocletTag tag) {
370 ArrayNode parameters = mapper.createArrayNode();
371 methodNode.set("parameters", parameters);
372 boolean required = true;
373
374 for (JavaParameter javaParameter : javaMethod.getParameters()) {
375 ObjectNode individualParameterNode = mapper.createObjectNode();
376 Optional<JavaAnnotation> optional = javaParameter.getAnnotations().stream().filter(
377 annotation -> annotation.getType().getName().equals(PATH_PARAM) ||
378 annotation.getType().getName().equals(QUERY_PARAM)).findAny();
379 JavaAnnotation pathType = optional.orElse(null);
380
381 String annotationName = javaParameter.getName();
382
383
384 if (pathType != null) { //the parameter is a path or query parameter
385 individualParameterNode.put("name",
386 pathType.getNamedParameter("value")
387 .toString().replace("\"", ""));
388 if (pathType.getType().getName().equals(PATH_PARAM)) {
389 individualParameterNode.put("in", "path");
390 } else if (pathType.getType().getName().equals(QUERY_PARAM)) {
391 individualParameterNode.put("in", "query");
392 }
393 individualParameterNode.put("type", getType(javaParameter.getType()));
394 } else { // the parameter is a body parameter
395 individualParameterNode.put("name", annotationName);
396 individualParameterNode.put("in", "body");
397
398 // Adds the reference to the Json model for the input
399 // that goes in the post or put operation
400 if (tag != null && (method.toLowerCase().equals("post") ||
401 method.toLowerCase().equals("put"))) {
402 ObjectNode schema = mapper.createObjectNode();
403 tag.getParameters().stream().forEach(param -> {
404 schema.put("$ref", "#/definitions/" + param);
405 });
406 individualParameterNode.set("schema", schema);
407 }
408 }
409 for (DocletTag p : javaMethod.getTagsByName("param")) {
410 if (p.getValue().contains(annotationName)) {
411 String description = "";
412 if (p.getValue().split(" ", 2).length >= 2) {
413 description = p.getValue().split(" ", 2)[1].trim();
414 if (description.contains("optional")) {
415 required = false;
416 }
417 } else {
418 throw new RuntimeException(String.format("No description for parameter \"%s\" in " +
419 "method \"%s\" in %s (line %d)",
420 p.getValue(), javaMethod.getName(),
421 javaMethod.getDeclaringClass().getName(),
422 javaMethod.getLineNumber()));
423 }
424 individualParameterNode.put("description", description);
425 }
426 }
427 individualParameterNode.put("required", required);
428 parameters.add(individualParameterNode);
429 }
430 }
431
432 // Returns the Swagger specified strings for the type of a parameter
433 private String getType(JavaType javaType) {
434 String type = javaType.getFullyQualifiedName();
435 String value;
436 if (type.equals(String.class.getName())) {
437 value = "string";
438 } else if (type.equals("int")) {
439 value = "integer";
440 } else if (type.equals(boolean.class.getName())) {
441 value = "boolean";
442 } else if (type.equals(long.class.getName())) {
443 value = "number";
444 } else {
445 value = "";
446 }
447 return value;
448 }
449
450 // Writes the swagger.json file using the supplied JSON root.
451 private void genCatalog(File dstDirectory, ObjectNode root) {
452 File swaggerCfg = new File(dstDirectory, JSON_FILE);
453 if (dstDirectory.exists() || dstDirectory.mkdirs()) {
454 try (FileWriter fw = new FileWriter(swaggerCfg);
455 PrintWriter pw = new PrintWriter(fw)) {
456 pw.println(root.toString());
457 } catch (IOException e) {
458 throw new RuntimeException("Unable to write " + JSON_FILE, e);
459 }
460 } else {
461 throw new RuntimeException("Unable to create " + dstDirectory);
462 }
463 }
464
465 // Generates the registrator Java component.
466 private void genRegistrator(File dstDirectory, String webContext,
467 String apiTitle, String apiVersion,
468 String apiPackage, String apiDescription) {
469 File dir = new File(dstDirectory, resourceDirectory != null ? GEN_SRC : ".");
470 File reg = new File(dir, apiRegistratorPath(apiPackage));
471 File pkg = reg.getParentFile();
472 if (pkg.exists() || pkg.mkdirs()) {
473 try {
474 String src = new String(ByteStreams.toByteArray(getClass().getResourceAsStream(REG_SRC)));
475 src = src.replace("${api.package}", apiPackage)
476 .replace("${web.context}", webContext)
477 .replace("${api.title}", apiTitle)
478 .replace("${api.description}", apiDescription);
479 Files.write(src.getBytes(), reg);
480 } catch (IOException e) {
481 throw new RuntimeException("Unable to write " + reg, e);
482 }
483 } else {
484 throw new RuntimeException("Unable to create " + reg);
485 }
486 }
487
488 private String shortText(String comment) {
489 int i = comment.indexOf('.');
490 return i > 0 ? comment.substring(0, i) : comment;
491 }
492
493 public static String apiRegistratorPath(String apiPackage) {
494 return apiPackage.replaceAll("\\.", "/") + "/ApiDocRegistrator.java";
495 }
496}