2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
20 package org.onap.aai.util.swagger;
22 import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml;
23 import com.fasterxml.jackson.dataformat.yaml.snakeyaml.constructor.SafeConstructor;
24 import freemarker.template.Configuration;
25 import freemarker.template.Template;
26 import freemarker.template.TemplateException;
27 import org.onap.aai.introspection.Version;
31 import java.util.stream.Collectors;
33 public class GenerateSwagger {
35 public static final String LINE_SEPARATOR = System.getProperty("line.separator");
36 public static final String DEFAULT_WIKI = "";
38 public static final String DEFAULT_SCHEMA_DIR = "../aai-schema";
39 public static final String CURRENT_VERSION = Version. getLatest().toString();
40 //if the program is run from aai-common, use this directory as default"
41 public static final String ALT_SCHEMA_DIR = "aai-schema";
42 //used to check to see if program is run from aai-core
43 public static final String DEFAULT_RUN_DIR = "aai-core";
45 public static void main(String[] args) throws IOException, TemplateException {
47 String schemaDir = System.getProperty("aai.schema.dir");
48 String versionToGenerate = System.getProperty("aai.generate.version");
49 String wikiLink = System.getProperty("aai.wiki.link");
51 if(schemaDir == null){
52 if(System.getProperty("user.dir") != null && !System.getProperty("user.dir").contains(DEFAULT_RUN_DIR)) {
53 System.out.println("Warning: Schema directory is not set so using default schema dir: " + ALT_SCHEMA_DIR);
54 schemaDir = ALT_SCHEMA_DIR;
57 System.out.println("Warning: Schema directory is not set so using default schema dir: " + DEFAULT_SCHEMA_DIR);
58 schemaDir = DEFAULT_SCHEMA_DIR;
62 if(versionToGenerate == null){
63 System.out.println("Warning: Version to generate is not set so using default version: " + CURRENT_VERSION);
64 versionToGenerate = CURRENT_VERSION;
68 System.out.println("Warning: aai.wiki.link property is not set so using default");
69 wikiLink = DEFAULT_WIKI;
72 String yamlFile = schemaDir + "/src/main/resources/aai_swagger_yaml/aai_swagger_" + versionToGenerate + ".yaml";
73 File swaggerYamlFile = new File(yamlFile);
75 if(!swaggerYamlFile.exists()){
76 System.err.println("Unable to find the swagger yaml file: " + swaggerYamlFile);
80 Yaml yaml = new Yaml(new SafeConstructor());
81 Map<String, Object> swaggerMap = null;
83 try (BufferedReader reader = new BufferedReader(new FileReader(swaggerYamlFile))){
84 swaggerMap = (Map<String, Object>) yaml.load(reader);
85 } catch(IOException ex){
89 if(null == swaggerMap) {
90 throw new IOException();
93 Map<String, Object> map = (Map<String, Object>) swaggerMap.get("paths");
94 Map<String, Object> schemaDefinitionmap = (Map<String, Object>) swaggerMap.get("definitions");
95 Map<String, Object> infoMap = (Map<String, Object>) swaggerMap.get("info");
96 Map<String, List<Api>> tagMap = new LinkedHashMap<>();
98 List<Api> apis = convertToApi(map);
99 apis.forEach((api) -> {
100 if(!tagMap.containsKey(api.getTag())){
101 List<Api> newApis = new ArrayList<>();
103 tagMap.put(api.getTag(), newApis);
105 tagMap.get(api.getTag()).add(api);
109 Map<String, List<Api>> sortedTagMap = new TreeMap<>(tagMap);
110 sortedTagMap.forEach((key, value) -> {
111 value.sort(Comparator.comparing(Api::getPath));
114 Map<String, Object> resultMap = new HashMap<>();
116 List<Definition> definitionList = convertToDefinition(schemaDefinitionmap);
118 definitionList = definitionList
119 .stream().sorted(Comparator.comparing(Definition::getDefinitionName)).collect(Collectors.toList());
121 resultMap.put("aaiApis", tagMap);
122 resultMap.put("sortedAaiApis", sortedTagMap);
123 resultMap.put("wikiLink", wikiLink);
124 resultMap.put("definitions", definitionList);
125 if (infoMap.containsKey("description")) {
126 String infoDescription = infoMap.get("description").toString();
128 infoDescription = Arrays.stream(infoDescription.split("\n"))
131 String hyperLink = "";
132 if(line.trim().contains("https://")){
133 int startIndex = line.indexOf("https://");
134 int endIndex = line.lastIndexOf("/");
135 hyperLink = line.substring(startIndex, endIndex);
136 return String.format("<a href=\"%s\">%s</a><br/>", hyperLink, line);
138 return String.format("%s<br/>", line);
141 .collect(Collectors.joining(LINE_SEPARATOR));
143 resultMap.put("description", infoDescription);
146 Configuration configuration = new Configuration();
147 configuration.setClassForTemplateLoading(Api.class, "/");
148 String resourcePath = "src/main/resources";
149 if(System.getProperty("user.dir") != null && !System.getProperty("user.dir").contains(DEFAULT_RUN_DIR)) {
150 configuration.setDirectoryForTemplateLoading(new File(DEFAULT_RUN_DIR + "/" + resourcePath));
153 configuration.setDirectoryForTemplateLoading(new File(resourcePath));
155 Template template = configuration.getTemplate("swagger.html.ftl");
157 String outputDirStr = schemaDir + "/src/main/resources/aai_swagger_html";
159 File outputDir = new File(outputDirStr);
161 if(!outputDir.exists()){
162 boolean resp = outputDir.mkdir();
164 System.err.println("Unable to create the directory: " + outputDirStr);
167 } else if(outputDir.isFile()){
168 System.err.println("Unable to create the directory: " + outputDirStr + " since a filename with that string exists");
172 Writer file = new FileWriter(new File(outputDirStr + "/aai_swagger_" + versionToGenerate + ".html"));
173 template.process(resultMap, file);
176 public static List<Api> convertToApi(Map<String, Object> pathMap){
179 throw new IllegalArgumentException();
181 List<Api> apis = new ArrayList<>();
183 pathMap.forEach( (pathKey, pathValue) -> {
186 Map<String, Object> httpVerbMap = (Map<String, Object>) pathValue;
187 List<Api.HttpVerb> httpVerbs = new ArrayList<>();
189 api.setPath(pathKey);
191 httpVerbMap.forEach((httpVerbKey, httpVerbValue) -> {
193 Api.HttpVerb httpVerb = new Api.HttpVerb();
195 Map<String, Object> httpVerbValueMap = (Map<String,Object>)httpVerbValue;
197 httpVerb.setType(httpVerbKey);
199 if(httpVerbValueMap.containsKey("tags")){
200 httpVerb.setTags((List<String>)httpVerbValueMap.get("tags"));
203 if(httpVerbValueMap.containsKey("summary")){
204 httpVerb.setSummary((String)httpVerbValueMap.get("summary"));
207 if(httpVerbValueMap.containsKey("operationId")){
208 httpVerb.setOperationId((String)httpVerbValueMap.get("operationId"));
211 if(httpVerbValueMap.containsKey("consumes")){
212 httpVerb.setConsumes((List<String>)httpVerbValueMap.get("consumes"));
213 if(httpVerb.getConsumes() != null){
214 httpVerb.setConsumerEnabled(true);
218 if(httpVerbValueMap.containsKey("produces")){
219 httpVerb.setProduces((List<String>)httpVerbValueMap.get("produces"));
222 if(httpVerbValueMap.containsKey("parameters")){
223 List<Map<String, Object>> parameters = (List<Map<String, Object>>) httpVerbValueMap.get("parameters");
224 List<Map<String, Object>> requestParameters = parameters
226 .filter((parameter) -> !parameter.get("name").equals("body"))
227 .collect(Collectors.toList());
228 httpVerb.setParameters(requestParameters);
229 if(httpVerb.getParameters() != null){
230 httpVerb.setParametersEnabled(true);
233 List<Map<String, Object>> requestBodyList = parameters
235 .filter((parameter) -> parameter.get("name").equals("body"))
236 .collect(Collectors.toList());
238 Map<String, Object> requestBody = null;
240 if(requestBodyList != null && requestBodyList.size() == 1){
241 requestBody = requestBodyList.get(0);
242 httpVerb.setBodyParametersEnabled(true);
243 httpVerb.setBodyParameters(requestBody);
245 if(requestBody != null && requestBody.containsKey("schema")){
246 Map<String, Object> schemaMap = (Map<String, Object>)requestBody.get("schema");
247 if(schemaMap != null && schemaMap.containsKey("$ref")){
248 String schemaLink = schemaMap.get("$ref").toString();
249 httpVerb.setSchemaLink(schemaLink);
250 int retCode = schemaLink.lastIndexOf('/');
251 if(retCode != -1 && retCode != schemaLink.length()){
252 httpVerb.setSchemaType(schemaLink.substring(retCode));
259 if(httpVerbValueMap.containsKey("responses")){
261 List<Api.HttpVerb.Response> responses = new ArrayList<Api.HttpVerb.Response>();
263 Map<String, Object> responsesMap = (Map<String, Object>) httpVerbValueMap.get("responses");
268 .filter((res) -> !"default".equalsIgnoreCase(res.getKey()))
269 .forEach((responseMap) -> {
271 Map<String, Object> responseValueMap = (Map<String, Object>)responseMap.getValue();
273 Api.HttpVerb.Response response = new Api.HttpVerb.Response();
275 response.setResponseCode(responseMap.getKey());
276 response.setDescription((String) responseValueMap.get("description"));
278 if(responseValueMap != null && responseValueMap.containsKey("schema")){
279 Map<String, Object> schemaMap = (Map<String, Object>)responseValueMap.get("schema");
280 if(schemaMap != null && schemaMap.containsKey("$ref")){
281 String schemaLink = schemaMap.get("$ref").toString();
282 httpVerb.setHasReturnSchema(true);
283 httpVerb.setReturnSchemaLink(schemaLink);
284 int retCode = schemaLink.lastIndexOf('/');
285 if(retCode != -1 && retCode != schemaLink.length()){
286 httpVerb.setReturnSchemaObject(schemaLink.substring(retCode));
291 responses.add(response);
295 httpVerb.setResponses(responses);
298 httpVerbs.add(httpVerb);
301 api.setHttpMethods(httpVerbs);
308 public static List<Definition> convertToDefinition(Map<String, Object> definitionMap) {
310 if(definitionMap == null)
311 throw new IllegalArgumentException();
313 List<Definition> defintionsList = new ArrayList<>();
317 .forEach((entry) -> {
319 Definition definition = new Definition();
320 String key = entry.getKey();
321 Map<String, Object> valueMap = (Map<String, Object>) entry.getValue();
323 definition.setDefinitionName(key);
325 if(valueMap.containsKey("description")){
326 String description = valueMap.get("description").toString();
327 description = formatDescription(description);
328 definition.setDefinitionDescription(description);
329 definition.setHasDescription(true);
332 List<Definition.Property> definitionProperties = new ArrayList<>();
334 List<String> requiredProperties = (valueMap.get("required") == null) ? new ArrayList<>() : (List<String>) valueMap.get("required");
336 Set<String> requiredPropsSet = requiredProperties.stream().collect(Collectors.toSet());
341 .filter( (e) -> "properties".equals(e.getKey()))
342 .forEach((propertyEntries) -> {
343 Map<String, Object> propertyRealEntries = (Map<String, Object>) propertyEntries.getValue();
346 .forEach((propertyEntry) -> {
347 Definition.Property definitionProperty = new Definition.Property();
348 String propertyKey = propertyEntry.getKey();
349 if(requiredPropsSet.contains(propertyKey)){
350 definitionProperty.setRequired(true);
352 definitionProperty.setPropertyName(propertyKey);
353 Map<String, Object> definitionPropertyMap = (Map<String, Object>) propertyEntry.getValue();
355 if(definitionPropertyMap.containsKey("description")){
356 definitionProperty.setPropertyDescription(definitionPropertyMap.get("description").toString());
357 definitionProperty.setHasPropertyDescription(true);
359 if(definitionPropertyMap.containsKey("type")){
360 String type = definitionPropertyMap.get("type").toString();
361 definitionProperty.setPropertyType(type);
362 definitionProperty.setHasType(true);
363 if ("array".equals(type)) {
364 definitionProperty.setPropertyType("object[]");
365 if(!definitionPropertyMap.containsKey("items")){
366 throw new RuntimeException("Unable to find the property items even though the type is array for " + propertyEntry.getKey());
368 Map<String, Object> itemMap = (Map<String, Object>) definitionPropertyMap.get("items");
369 if(itemMap.containsKey("$ref")){
370 definitionProperty.setHasPropertyReference(true);
371 String refItem = itemMap.get("$ref").toString();
372 int retCode = refItem.lastIndexOf('/');
373 if(retCode != -1 && retCode != refItem.length()){
374 definitionProperty.setPropertyReferenceObjectName(refItem.substring(retCode + 1));
376 definitionProperty.setPropertyReference(refItem);
380 if(definitionPropertyMap.containsKey("$ref")){
381 definitionProperty.setHasPropertyReference(true);
382 String refItem = definitionPropertyMap.get("$ref").toString();
383 int retCode = refItem.lastIndexOf('/');
384 if(retCode != -1 && retCode != refItem.length()){
385 definitionProperty.setPropertyReferenceObjectName(refItem.substring(retCode + 1));
387 definitionProperty.setPropertyReference(refItem);
391 definitionProperties.add(definitionProperty);
395 definition.setPropertyList(definitionProperties);
397 List<Definition.Property> schemaProperties = definitionProperties.
399 .filter((o) -> o.isHasPropertyReference())
400 .collect(Collectors.toList());
402 List<Definition.Property> regularProperties = definitionProperties.
404 .filter((o) -> !o.isHasPropertyReference())
405 .collect(Collectors.toList());
407 definition.setRegularPropertyList(regularProperties);
408 definition.setSchemaPropertyList(schemaProperties);
410 defintionsList.add(definition);
412 return defintionsList;
415 public static String formatDescription(String description){
417 description = Arrays.stream(description.split("\n"))
420 if(line.contains("######")){
421 line = line.replaceAll("#", "");
423 String headerId = line.toLowerCase().replaceAll("\\s", "-");
425 if(line.contains("Related Nodes")){
426 return String.format("<h6 id=\"%s\">%s</h6>%s<ul>", headerId, line, LINE_SEPARATOR);
428 return String.format("<h6 id=\"%s\">%s</h6>", headerId, line);
430 } else if(line.startsWith("-")){
431 line = line.replaceFirst("-", "");
433 return String.format("<li>%s</li>", line);
435 return String.format("<p>%s</p>", line);
438 .collect(Collectors.joining(LINE_SEPARATOR));
440 if(description.contains("<ul>")){
441 description = description + "</ul>";