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