blob: 0d44913840cc52ecf87ceabd08f1fe65be701aaf [file] [log] [blame]
Sahil Lele372d1f32015-07-31 15:01:41 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
Sahil Lele372d1f32015-07-31 15:01:41 -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 */
16package org.onosproject.maven;
17
18import com.fasterxml.jackson.databind.ObjectMapper;
19import com.fasterxml.jackson.databind.node.ArrayNode;
20import com.fasterxml.jackson.databind.node.ObjectNode;
HIGUCHI Yuta547c2052016-02-23 00:08:13 -080021import com.google.common.base.Throwables;
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -070022import com.google.common.io.ByteStreams;
23import com.google.common.io.Files;
Andrea Campanella82baf6b2015-12-14 10:23:37 -080024import com.google.gson.JsonParser;
Sahil Lele372d1f32015-07-31 15:01:41 -070025import 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;
32import org.apache.maven.plugin.AbstractMojo;
33import org.apache.maven.plugin.MojoExecutionException;
34import org.apache.maven.plugins.annotations.LifecyclePhase;
35import org.apache.maven.plugins.annotations.Mojo;
36import org.apache.maven.plugins.annotations.Parameter;
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -070037import org.apache.maven.project.MavenProject;
Sahil Lele372d1f32015-07-31 15:01:41 -070038
39import java.io.File;
Andrea Campanella82baf6b2015-12-14 10:23:37 -080040import java.io.FileReader;
Sahil Lele372d1f32015-07-31 15:01:41 -070041import java.io.FileWriter;
42import java.io.IOException;
43import java.io.PrintWriter;
Yuta HIGUCHIbcc2ce92018-03-07 16:42:11 -080044import java.time.Year;
Sahil Lele372d1f32015-07-31 15:01:41 -070045import java.util.HashMap;
46import java.util.Map;
47import java.util.Optional;
48
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -070049import static com.google.common.base.Strings.isNullOrEmpty;
50
Sahil Lele372d1f32015-07-31 15:01:41 -070051/**
52 * Produces ONOS Swagger api-doc.
53 */
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -070054@Mojo(name = "swagger", defaultPhase = LifecyclePhase.GENERATE_SOURCES)
Sahil Lele372d1f32015-07-31 15:01:41 -070055public class OnosSwaggerMojo extends AbstractMojo {
56 private final ObjectMapper mapper = new ObjectMapper();
Andrea Campanella82baf6b2015-12-14 10:23:37 -080057 private final JsonParser jsonParser = new JsonParser();
Sahil Lele372d1f32015-07-31 15:01:41 -070058
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -070059 private static final String JSON_FILE = "swagger.json";
60 private static final String GEN_SRC = "generated-sources";
61 private static final String REG_SRC = "registrator.javat";
62
Sahil Lele372d1f32015-07-31 15:01:41 -070063 private static final String PATH = "javax.ws.rs.Path";
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -070064 private static final String PATH_PARAM = "javax.ws.rs.PathParam";
65 private static final String QUERY_PARAM = "javax.ws.rs.QueryParam";
Sahil Lele372d1f32015-07-31 15:01:41 -070066 private static final String POST = "javax.ws.rs.POST";
67 private static final String GET = "javax.ws.rs.GET";
68 private static final String PUT = "javax.ws.rs.PUT";
69 private static final String DELETE = "javax.ws.rs.DELETE";
70 private static final String PRODUCES = "javax.ws.rs.Produces";
71 private static final String CONSUMES = "javax.ws.rs.Consumes";
72 private static final String JSON = "MediaType.APPLICATION_JSON";
andrea863201a2015-11-24 13:18:30 -080073 private static final String OCTET_STREAM = "MediaType.APPLICATION_OCTET_STREAM";
Sahil Lele372d1f32015-07-31 15:01:41 -070074
75 /**
76 * The directory where the generated catalogue file will be put.
77 */
78 @Parameter(defaultValue = "${basedir}")
79 protected File srcDirectory;
80
81 /**
82 * The directory where the generated catalogue file will be put.
83 */
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -070084 @Parameter(defaultValue = "${project.build.directory}")
Sahil Lele372d1f32015-07-31 15:01:41 -070085 protected File dstDirectory;
86
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -070087 /**
88 * REST API web-context
89 */
90 @Parameter(defaultValue = "${web.context}")
91 protected String webContext;
92
93 /**
94 * REST API version
95 */
96 @Parameter(defaultValue = "${api.version}")
97 protected String apiVersion;
98
99 /**
100 * REST API description
101 */
102 @Parameter(defaultValue = "${api.description}")
103 protected String apiDescription;
104
105 /**
106 * REST API title
107 */
108 @Parameter(defaultValue = "${api.title}")
109 protected String apiTitle;
110
111 /**
112 * REST API title
113 */
114 @Parameter(defaultValue = "${api.package}")
115 protected String apiPackage;
116
117 /**
118 * Maven project
119 */
120 @Parameter(defaultValue = "${project}")
121 protected MavenProject project;
122
123
Sahil Lele372d1f32015-07-31 15:01:41 -0700124 @Override
125 public void execute() throws MojoExecutionException {
Sahil Lele372d1f32015-07-31 15:01:41 -0700126 try {
127 JavaProjectBuilder builder = new JavaProjectBuilder();
128 builder.addSourceTree(new File(srcDirectory, "src/main/java"));
129
130 ObjectNode root = initializeRoot();
Sahil Lele372d1f32015-07-31 15:01:41 -0700131 ArrayNode tags = mapper.createArrayNode();
Sahil Lele372d1f32015-07-31 15:01:41 -0700132 ObjectNode paths = mapper.createObjectNode();
andreafaa2c4b2015-11-16 13:48:39 -0800133 ObjectNode definitions = mapper.createObjectNode();
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700134
135 root.set("tags", tags);
Sahil Lele372d1f32015-07-31 15:01:41 -0700136 root.set("paths", paths);
andreafaa2c4b2015-11-16 13:48:39 -0800137 root.set("definitions", definitions);
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700138
andreafaa2c4b2015-11-16 13:48:39 -0800139 builder.getClasses().forEach(jc -> processClass(jc, paths, tags, definitions));
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700140
141 if (paths.size() > 0) {
142 getLog().info("Generating ONOS REST API documentation...");
143 genCatalog(root);
144
145 if (!isNullOrEmpty(apiPackage)) {
146 genRegistrator();
147 }
148 }
149
150 project.addCompileSourceRoot(new File(dstDirectory, GEN_SRC).getPath());
151
Sahil Lele372d1f32015-07-31 15:01:41 -0700152 } catch (Exception e) {
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700153 getLog().warn("Unable to generate ONOS REST API documentation", e);
Sahil Lele372d1f32015-07-31 15:01:41 -0700154 throw e;
155 }
156 }
157
158 // initializes top level root with Swagger required specifications
159 private ObjectNode initializeRoot() {
160 ObjectNode root = mapper.createObjectNode();
161 root.put("swagger", "2.0");
162 ObjectNode info = mapper.createObjectNode();
163 root.set("info", info);
Sahil Lele372d1f32015-07-31 15:01:41 -0700164
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700165 root.put("basePath", webContext);
166 info.put("version", apiVersion);
167 info.put("title", apiTitle);
168 info.put("description", apiDescription);
Sahil Lele372d1f32015-07-31 15:01:41 -0700169
170 ArrayNode produces = mapper.createArrayNode();
171 produces.add("application/json");
172 root.set("produces", produces);
173
174 ArrayNode consumes = mapper.createArrayNode();
175 consumes.add("application/json");
176 root.set("consumes", consumes);
177
178 return root;
179 }
180
181 // Checks whether javaClass has a path tag associated with it and if it does
182 // processes its methods and creates a tag for the class on the root
andreafaa2c4b2015-11-16 13:48:39 -0800183 void processClass(JavaClass javaClass, ObjectNode paths, ArrayNode tags, ObjectNode definitions) {
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700184 // If the class does not have a Path tag then ignore it
185 JavaAnnotation annotation = getPathAnnotation(javaClass);
Sahil Lele372d1f32015-07-31 15:01:41 -0700186 if (annotation == null) {
187 return;
188 }
189
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700190 String path = getPath(annotation);
191 if (path == null) {
192 return;
Sahil Lele372d1f32015-07-31 15:01:41 -0700193 }
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700194
195 String resourcePath = "/" + path;
196 String tagPath = path.isEmpty() ? "/" : path;
197
198 // Create tag node for this class.
199 ObjectNode tagObject = mapper.createObjectNode();
200 tagObject.put("name", tagPath);
Sahil Lele372d1f32015-07-31 15:01:41 -0700201 if (javaClass.getComment() != null) {
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700202 tagObject.put("description", shortText(javaClass.getComment()));
Sahil Lele372d1f32015-07-31 15:01:41 -0700203 }
204 tags.add(tagObject);
205
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700206 // Create an array node add to all methods from this class.
Sahil Lele372d1f32015-07-31 15:01:41 -0700207 ArrayNode tagArray = mapper.createArrayNode();
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700208 tagArray.add(tagPath);
Sahil Lele372d1f32015-07-31 15:01:41 -0700209
andreafaa2c4b2015-11-16 13:48:39 -0800210 processAllMethods(javaClass, resourcePath, paths, tagArray, definitions);
Sahil Lele372d1f32015-07-31 15:01:41 -0700211 }
212
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700213 private JavaAnnotation getPathAnnotation(JavaClass javaClass) {
214 Optional<JavaAnnotation> optional = javaClass.getAnnotations()
215 .stream().filter(a -> a.getType().getName().equals(PATH)).findAny();
Sho SHIMIZUef7e2902016-02-12 18:38:29 -0800216 return optional.orElse(null);
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700217 }
218
Sahil Lele372d1f32015-07-31 15:01:41 -0700219 // Checks whether a class's methods are REST methods and then places all the
220 // methods under a specific path into the paths node
221 private void processAllMethods(JavaClass javaClass, String resourcePath,
andreafaa2c4b2015-11-16 13:48:39 -0800222 ObjectNode paths, ArrayNode tagArray, ObjectNode definitions) {
Sahil Lele372d1f32015-07-31 15:01:41 -0700223 // map of the path to its methods represented by an ObjectNode
224 Map<String, ObjectNode> pathMap = new HashMap<>();
225
226 javaClass.getMethods().forEach(javaMethod -> {
227 javaMethod.getAnnotations().forEach(annotation -> {
228 String name = annotation.getType().getName();
229 if (name.equals(POST) || name.equals(GET) || name.equals(DELETE) || name.equals(PUT)) {
230 // substring(12) removes "javax.ws.rs."
231 String method = annotation.getType().toString().substring(12).toLowerCase();
andreafaa2c4b2015-11-16 13:48:39 -0800232 processRestMethod(javaMethod, method, pathMap, resourcePath, tagArray, definitions);
Sahil Lele372d1f32015-07-31 15:01:41 -0700233 }
234 });
235 });
236
237 // for each path add its methods to the path node
238 for (Map.Entry<String, ObjectNode> entry : pathMap.entrySet()) {
239 paths.set(entry.getKey(), entry.getValue());
240 }
241
242
243 }
244
245 private void processRestMethod(JavaMethod javaMethod, String method,
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700246 Map<String, ObjectNode> pathMap,
andreafaa2c4b2015-11-16 13:48:39 -0800247 String resourcePath, ArrayNode tagArray, ObjectNode definitions) {
Sahil Lele372d1f32015-07-31 15:01:41 -0700248 String fullPath = resourcePath, consumes = "", produces = "",
249 comment = javaMethod.getComment();
Andrea Campanella10c4adc2015-12-03 15:27:54 -0800250 DocletTag tag = javaMethod.getTagByName("onos.rsModel");
Sahil Lele372d1f32015-07-31 15:01:41 -0700251 for (JavaAnnotation annotation : javaMethod.getAnnotations()) {
252 String name = annotation.getType().getName();
253 if (name.equals(PATH)) {
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700254 fullPath = resourcePath + "/" + getPath(annotation);
255 fullPath = fullPath.replaceFirst("^//", "/");
Sahil Lele372d1f32015-07-31 15:01:41 -0700256 }
257 if (name.equals(CONSUMES)) {
258 consumes = getIOType(annotation);
259 }
260 if (name.equals(PRODUCES)) {
261 produces = getIOType(annotation);
262 }
263 }
264 ObjectNode methodNode = mapper.createObjectNode();
265 methodNode.set("tags", tagArray);
266
267 addSummaryDescriptions(methodNode, comment);
andreafaa2c4b2015-11-16 13:48:39 -0800268 addJsonSchemaDefinition(definitions, tag);
andreafaa2c4b2015-11-16 13:48:39 -0800269
270 processParameters(javaMethod, methodNode, method, tag);
Sahil Lele372d1f32015-07-31 15:01:41 -0700271
272 processConsumesProduces(methodNode, "consumes", consumes);
273 processConsumesProduces(methodNode, "produces", produces);
andreafaa2c4b2015-11-16 13:48:39 -0800274 if (tag == null || ((method.toLowerCase().equals("post") || method.toLowerCase().equals("put"))
275 && !(tag.getParameters().size() > 1))) {
276 addResponses(methodNode, tag, false);
277 } else {
278 addResponses(methodNode, tag, true);
279 }
Sahil Lele372d1f32015-07-31 15:01:41 -0700280
281 ObjectNode operations = pathMap.get(fullPath);
282 if (operations == null) {
283 operations = mapper.createObjectNode();
284 operations.set(method, methodNode);
285 pathMap.put(fullPath, operations);
286 } else {
287 operations.set(method, methodNode);
288 }
289 }
290
andreafaa2c4b2015-11-16 13:48:39 -0800291 private void addJsonSchemaDefinition(ObjectNode definitions, DocletTag tag) {
292 File definitionsDirectory = new File(srcDirectory + "/src/main/resources/definitions");
293 if (tag != null) {
Sho SHIMIZUa09e1bb2016-08-01 14:25:25 -0700294 tag.getParameters().forEach(param -> {
andreafaa2c4b2015-11-16 13:48:39 -0800295 try {
296 File config = new File(definitionsDirectory.getAbsolutePath() + "/"
297 + param + ".json");
Andrea Campanella82baf6b2015-12-14 10:23:37 -0800298 definitions.putPOJO(param, jsonParser.parse(new FileReader(config)));
andreafaa2c4b2015-11-16 13:48:39 -0800299 } catch (IOException e) {
HIGUCHI Yuta547c2052016-02-23 00:08:13 -0800300 getLog().error(String.format("Could not process %s in %s@%s: %s",
301 tag.getName(), tag.getContext(), tag.getLineNumber(),
302 e.getMessage()));
303 throw Throwables.propagate(e);
andreafaa2c4b2015-11-16 13:48:39 -0800304 }
305 });
306
307 }
308 }
309
Sahil Lele372d1f32015-07-31 15:01:41 -0700310 private void processConsumesProduces(ObjectNode methodNode, String type, String io) {
311 if (!io.equals("")) {
312 ArrayNode array = mapper.createArrayNode();
313 methodNode.set(type, array);
314 array.add(io);
315 }
316 }
317
318 private void addSummaryDescriptions(ObjectNode methodNode, String comment) {
319 String summary = "", description;
320 if (comment != null) {
321 if (comment.contains(".")) {
322 int periodIndex = comment.indexOf(".");
323 summary = comment.substring(0, periodIndex);
324 description = comment.length() > periodIndex + 1 ?
325 comment.substring(periodIndex + 1).trim() : "";
326 } else {
327 description = comment;
328 }
329 methodNode.put("summary", summary);
330 methodNode.put("description", description);
331 }
332 }
333
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700334 // Temporary solution to add responses to a method
andreafaa2c4b2015-11-16 13:48:39 -0800335 private void addResponses(ObjectNode methodNode, DocletTag tag, boolean responseJson) {
Sahil Lele372d1f32015-07-31 15:01:41 -0700336 ObjectNode responses = mapper.createObjectNode();
337 methodNode.set("responses", responses);
338
339 ObjectNode success = mapper.createObjectNode();
340 success.put("description", "successful operation");
341 responses.set("200", success);
andreafaa2c4b2015-11-16 13:48:39 -0800342 if (tag != null && responseJson) {
343 ObjectNode schema = mapper.createObjectNode();
Sho SHIMIZUa09e1bb2016-08-01 14:25:25 -0700344 tag.getParameters().forEach(
andreafaa2c4b2015-11-16 13:48:39 -0800345 param -> schema.put("$ref", "#/definitions/" + param));
346 success.set("schema", schema);
347 }
Sahil Lele372d1f32015-07-31 15:01:41 -0700348
349 ObjectNode defaultObj = mapper.createObjectNode();
350 defaultObj.put("description", "Unexpected error");
351 responses.set("default", defaultObj);
352 }
353
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700354 // Checks if the annotations has a value of JSON and returns the string
355 // that Swagger requires
Sahil Lele372d1f32015-07-31 15:01:41 -0700356 private String getIOType(JavaAnnotation annotation) {
357 if (annotation.getNamedParameter("value").toString().equals(JSON)) {
358 return "application/json";
Andrea Campanella260645b2015-12-06 10:24:18 -0800359 } else if (annotation.getNamedParameter("value").toString().equals(OCTET_STREAM)) {
andrea863201a2015-11-24 13:18:30 -0800360 return "application/octet_stream";
Sahil Lele372d1f32015-07-31 15:01:41 -0700361 }
362 return "";
363 }
364
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700365 // If the annotation has a Path tag, returns the value with leading and
366 // trailing double quotes and slash removed.
Sahil Lele372d1f32015-07-31 15:01:41 -0700367 private String getPath(JavaAnnotation annotation) {
368 String path = annotation.getNamedParameter("value").toString();
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700369 return path == null ? null : path.replaceAll("(^[\\\"/]*|[/\\\"]*$)", "");
Sahil Lele372d1f32015-07-31 15:01:41 -0700370 }
371
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700372 // Processes parameters of javaMethod and enters the proper key-values into the methodNode
andreafaa2c4b2015-11-16 13:48:39 -0800373 private void processParameters(JavaMethod javaMethod, ObjectNode methodNode, String method, DocletTag tag) {
Sahil Lele372d1f32015-07-31 15:01:41 -0700374 ArrayNode parameters = mapper.createArrayNode();
375 methodNode.set("parameters", parameters);
376 boolean required = true;
377
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700378 for (JavaParameter javaParameter : javaMethod.getParameters()) {
Sahil Lele372d1f32015-07-31 15:01:41 -0700379 ObjectNode individualParameterNode = mapper.createObjectNode();
380 Optional<JavaAnnotation> optional = javaParameter.getAnnotations().stream().filter(
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700381 annotation -> annotation.getType().getName().equals(PATH_PARAM) ||
382 annotation.getType().getName().equals(QUERY_PARAM)).findAny();
Sho SHIMIZUef7e2902016-02-12 18:38:29 -0800383 JavaAnnotation pathType = optional.orElse(null);
Sahil Lele372d1f32015-07-31 15:01:41 -0700384
385 String annotationName = javaParameter.getName();
386
387
388 if (pathType != null) { //the parameter is a path or query parameter
389 individualParameterNode.put("name",
andreafaa2c4b2015-11-16 13:48:39 -0800390 pathType.getNamedParameter("value")
391 .toString().replace("\"", ""));
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700392 if (pathType.getType().getName().equals(PATH_PARAM)) {
Sahil Lele372d1f32015-07-31 15:01:41 -0700393 individualParameterNode.put("in", "path");
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700394 } else if (pathType.getType().getName().equals(QUERY_PARAM)) {
Sahil Lele372d1f32015-07-31 15:01:41 -0700395 individualParameterNode.put("in", "query");
396 }
397 individualParameterNode.put("type", getType(javaParameter.getType()));
398 } else { // the parameter is a body parameter
399 individualParameterNode.put("name", annotationName);
400 individualParameterNode.put("in", "body");
401
andreafaa2c4b2015-11-16 13:48:39 -0800402 // Adds the reference to the Json model for the input
403 // that goes in the post or put operation
404 if (tag != null && (method.toLowerCase().equals("post") ||
405 method.toLowerCase().equals("put"))) {
406 ObjectNode schema = mapper.createObjectNode();
Sho SHIMIZUa09e1bb2016-08-01 14:25:25 -0700407 tag.getParameters().forEach(param -> {
andreafaa2c4b2015-11-16 13:48:39 -0800408 schema.put("$ref", "#/definitions/" + param);
409 });
410 individualParameterNode.set("schema", schema);
411 }
Sahil Lele372d1f32015-07-31 15:01:41 -0700412 }
413 for (DocletTag p : javaMethod.getTagsByName("param")) {
414 if (p.getValue().contains(annotationName)) {
Andrea Campanella260645b2015-12-06 10:24:18 -0800415 String description = "";
416 if (p.getValue().split(" ", 2).length >= 2) {
417 description = p.getValue().split(" ", 2)[1].trim();
Sahil Lele372d1f32015-07-31 15:01:41 -0700418 if (description.contains("optional")) {
419 required = false;
420 }
Andrea Campanella260645b2015-12-06 10:24:18 -0800421 } else {
422 getLog().warn(String.format(
423 "No description for parameter \"%s\" in " +
424 "method \"%s\" in %s (line %d)",
425 p.getValue(), javaMethod.getName(),
426 javaMethod.getDeclaringClass().getName(),
427 javaMethod.getLineNumber()));
Sahil Lele372d1f32015-07-31 15:01:41 -0700428 }
Andrea Campanella260645b2015-12-06 10:24:18 -0800429 individualParameterNode.put("description", description);
Sahil Lele372d1f32015-07-31 15:01:41 -0700430 }
431 }
432 individualParameterNode.put("required", required);
433 parameters.add(individualParameterNode);
434 }
435 }
436
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700437 // Returns the Swagger specified strings for the type of a parameter
Sahil Lele372d1f32015-07-31 15:01:41 -0700438 private String getType(JavaType javaType) {
439 String type = javaType.getFullyQualifiedName();
440 String value;
441 if (type.equals(String.class.getName())) {
442 value = "string";
443 } else if (type.equals("int")) {
444 value = "integer";
445 } else if (type.equals(boolean.class.getName())) {
446 value = "boolean";
447 } else if (type.equals(long.class.getName())) {
448 value = "number";
449 } else {
450 value = "";
451 }
452 return value;
453 }
454
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700455 // Writes the swagger.json file using the supplied JSON root.
456 private void genCatalog(ObjectNode root) {
457 File swaggerCfg = new File(dstDirectory, JSON_FILE);
458 if (dstDirectory.exists() || dstDirectory.mkdirs()) {
459 try (FileWriter fw = new FileWriter(swaggerCfg);
460 PrintWriter pw = new PrintWriter(fw)) {
461 pw.println(root.toString());
462 } catch (IOException e) {
463 getLog().warn("Unable to write " + JSON_FILE);
464 }
465 } else {
466 getLog().warn("Unable to create " + dstDirectory);
Sahil Lele372d1f32015-07-31 15:01:41 -0700467 }
468 }
469
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700470 // Generates the registrator Java component.
471 private void genRegistrator() {
472 File dir = new File(dstDirectory, GEN_SRC);
473 File reg = new File(dir, apiPackage.replaceAll("\\.", "/") + "/ApiDocRegistrator.java");
474 File pkg = reg.getParentFile();
475 if (pkg.exists() || pkg.mkdirs()) {
476 try {
477 String src = new String(ByteStreams.toByteArray(getClass().getResourceAsStream(REG_SRC)));
478 src = src.replace("${api.package}", apiPackage)
479 .replace("${web.context}", webContext)
480 .replace("${api.title}", apiTitle)
Yuta HIGUCHIbcc2ce92018-03-07 16:42:11 -0800481 .replace("${api.description}", apiTitle)
482 .replace("${year}", Year.now().toString());
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700483 Files.write(src.getBytes(), reg);
484 } catch (IOException e) {
485 getLog().warn("Unable to write " + reg);
486 }
487 } else {
488 getLog().warn("Unable to create " + reg);
489 }
490 }
491
492 // Returns "nickname" based on method and path for a REST method
Sahil Lele372d1f32015-07-31 15:01:41 -0700493 private String setNickname(String method, String path) {
494 if (!path.equals("")) {
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700495 return (method + path.replace('/', '_').replace("{", "").replace("}", "")).toLowerCase();
Sahil Lele372d1f32015-07-31 15:01:41 -0700496 } else {
497 return method.toLowerCase();
498 }
499 }
Thomas Vachuska0fa2aa12015-08-18 12:53:04 -0700500
501 private String shortText(String comment) {
502 int i = comment.indexOf('.');
503 return i > 0 ? comment.substring(0, i) : comment;
504 }
505
Sahil Lele372d1f32015-07-31 15:01:41 -0700506}