Update the license for 2017-2018 license
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / util / swagger / GenerateSwagger.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
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
10  *
11  *    http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20 package org.onap.aai.util.swagger;
21
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;
28
29 import java.io.*;
30 import java.util.*;
31 import java.util.stream.Collectors;
32
33 public class GenerateSwagger {
34
35     public static final String LINE_SEPARATOR = System.getProperty("line.separator");
36     public static final String DEFAULT_WIKI = "";
37
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";
44
45     public static void main(String[] args) throws IOException, TemplateException {
46
47         String schemaDir         = System.getProperty("aai.schema.dir");
48         String versionToGenerate = System.getProperty("aai.generate.version");
49         String wikiLink = System.getProperty("aai.wiki.link");
50
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;
55                 }
56                 else {
57                         System.out.println("Warning: Schema directory is not set so using default schema dir: " + DEFAULT_SCHEMA_DIR);
58                         schemaDir = DEFAULT_SCHEMA_DIR;
59                 }
60         }
61
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;
65         }
66
67         if(wikiLink == null){
68             System.out.println("Warning: aai.wiki.link property is not set so using default");
69             wikiLink = DEFAULT_WIKI;
70         }
71
72         String yamlFile = schemaDir + "/src/main/resources/aai_swagger_yaml/aai_swagger_" + versionToGenerate + ".yaml";
73         File swaggerYamlFile = new File(yamlFile);
74
75         if(!swaggerYamlFile.exists()){
76             System.err.println("Unable to find the swagger yaml file: " + swaggerYamlFile);
77             System.exit(1);
78         }
79
80         Yaml yaml = new Yaml(new SafeConstructor());
81         Map<String, Object> swaggerMap = null;
82
83         try (BufferedReader reader = new BufferedReader(new FileReader(swaggerYamlFile))){
84             swaggerMap = (Map<String, Object>) yaml.load(reader);
85         } catch(IOException ex){
86             ex.printStackTrace();
87         }
88
89         if(null == swaggerMap) {
90             throw new IOException();
91         }
92
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<>();
97
98         List<Api> apis = convertToApi(map);
99         apis.forEach((api) -> {
100             if(!tagMap.containsKey(api.getTag())){
101                 List<Api> newApis = new ArrayList<>();
102                 newApis.add(api);
103                 tagMap.put(api.getTag(), newApis);
104             } else {
105                 tagMap.get(api.getTag()).add(api);
106             }
107         });
108
109         Map<String, List<Api>> sortedTagMap = new TreeMap<>(tagMap);
110         sortedTagMap.forEach((key, value) -> {
111             value.sort(Comparator.comparing(Api::getPath));
112         });
113
114         Map<String, Object> resultMap = new HashMap<>();
115
116         List<Definition> definitionList = convertToDefinition(schemaDefinitionmap);
117
118         definitionList = definitionList
119             .stream().sorted(Comparator.comparing(Definition::getDefinitionName)).collect(Collectors.toList());
120
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();
127
128             infoDescription = Arrays.stream(infoDescription.split("\n"))
129                     .map(line -> {
130                         line = line.trim();
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);
137                         }
138                         return String.format("%s<br/>", line);
139                     })
140
141                     .collect(Collectors.joining(LINE_SEPARATOR));
142
143             resultMap.put("description", infoDescription);
144         }
145
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));
151         }
152         else {
153                 configuration.setDirectoryForTemplateLoading(new File(resourcePath));
154         }
155         Template template = configuration.getTemplate("swagger.html.ftl");
156
157         String outputDirStr = schemaDir + "/src/main/resources/aai_swagger_html";
158
159         File outputDir = new File(outputDirStr);
160
161         if(!outputDir.exists()){
162             boolean resp = outputDir.mkdir();
163             if(!resp){
164                 System.err.println("Unable to create the directory: " + outputDirStr);
165                 System.exit(1);
166             }
167         } else if(outputDir.isFile()){
168             System.err.println("Unable to create the directory: " + outputDirStr + " since a filename with that string exists");
169             System.exit(1);
170         }
171
172         Writer file = new FileWriter(new File(outputDirStr +  "/aai_swagger_" + versionToGenerate + ".html"));
173         template.process(resultMap, file);
174     }
175
176     public static List<Api> convertToApi(Map<String, Object> pathMap){
177
178         if(pathMap == null)
179             throw new IllegalArgumentException();
180
181         List<Api> apis = new ArrayList<>();
182
183         pathMap.forEach( (pathKey, pathValue) -> {
184
185             Api api = new Api();
186             Map<String, Object> httpVerbMap = (Map<String, Object>) pathValue;
187             List<Api.HttpVerb> httpVerbs = new ArrayList<>();
188
189             api.setPath(pathKey);
190
191             httpVerbMap.forEach((httpVerbKey, httpVerbValue) -> {
192
193                 Api.HttpVerb httpVerb = new Api.HttpVerb();
194
195                 Map<String, Object> httpVerbValueMap = (Map<String,Object>)httpVerbValue;
196
197                 httpVerb.setType(httpVerbKey);
198
199                 if(httpVerbValueMap.containsKey("tags")){
200                     httpVerb.setTags((List<String>)httpVerbValueMap.get("tags"));
201                 }
202
203                 if(httpVerbValueMap.containsKey("summary")){
204                     httpVerb.setSummary((String)httpVerbValueMap.get("summary"));
205                 }
206
207                 if(httpVerbValueMap.containsKey("operationId")){
208                     httpVerb.setOperationId((String)httpVerbValueMap.get("operationId"));
209                 }
210
211                 if(httpVerbValueMap.containsKey("consumes")){
212                     httpVerb.setConsumes((List<String>)httpVerbValueMap.get("consumes"));
213                     if(httpVerb.getConsumes() != null){
214                         httpVerb.setConsumerEnabled(true);
215                     }
216                 }
217
218                 if(httpVerbValueMap.containsKey("produces")){
219                     httpVerb.setProduces((List<String>)httpVerbValueMap.get("produces"));
220                 }
221
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
225                             .stream()
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);
231                     }
232
233                     List<Map<String, Object>> requestBodyList = parameters
234                             .stream()
235                             .filter((parameter) -> parameter.get("name").equals("body"))
236                             .collect(Collectors.toList());
237
238                     Map<String, Object> requestBody = null;
239
240                     if(requestBodyList != null && requestBodyList.size() == 1){
241                         requestBody = requestBodyList.get(0);
242                         httpVerb.setBodyParametersEnabled(true);
243                         httpVerb.setBodyParameters(requestBody);
244
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));
253                                 }
254                             }
255                         }
256                     }
257                 }
258
259                 if(httpVerbValueMap.containsKey("responses")){
260
261                     List<Api.HttpVerb.Response> responses = new ArrayList<Api.HttpVerb.Response>();
262
263                     Map<String, Object> responsesMap = (Map<String, Object>) httpVerbValueMap.get("responses");
264
265                     responsesMap
266                         .entrySet()
267                         .stream()
268                         .filter((res) -> !"default".equalsIgnoreCase(res.getKey()))
269                         .forEach((responseMap) -> {
270
271                             Map<String, Object> responseValueMap = (Map<String, Object>)responseMap.getValue();
272
273                             Api.HttpVerb.Response response = new Api.HttpVerb.Response();
274
275                             response.setResponseCode(responseMap.getKey());
276                             response.setDescription((String) responseValueMap.get("description"));
277
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));
287                                     }
288                                 }
289                             }
290
291                             responses.add(response);
292                         }
293                     );
294
295                     httpVerb.setResponses(responses);
296                 }
297
298                 httpVerbs.add(httpVerb);
299             });
300
301             api.setHttpMethods(httpVerbs);
302             apis.add(api);
303         });
304
305         return apis;
306     }
307
308     public static List<Definition> convertToDefinition(Map<String, Object> definitionMap) {
309
310         if(definitionMap == null)
311             throw new IllegalArgumentException();
312
313         List<Definition> defintionsList = new ArrayList<>();
314
315         definitionMap
316             .entrySet()
317             .forEach((entry) -> {
318
319                 Definition definition = new Definition();
320                 String key = entry.getKey();
321                 Map<String, Object> valueMap = (Map<String, Object>) entry.getValue();
322
323                 definition.setDefinitionName(key);
324
325                 if(valueMap.containsKey("description")){
326                     String description = valueMap.get("description").toString();
327                     description = formatDescription(description);
328                     definition.setDefinitionDescription(description);
329                     definition.setHasDescription(true);
330                 }
331
332                 List<Definition.Property> definitionProperties = new ArrayList<>();
333
334                 List<String> requiredProperties = (valueMap.get("required") == null) ? new ArrayList<>() : (List<String>) valueMap.get("required");
335
336                 Set<String> requiredPropsSet = requiredProperties.stream().collect(Collectors.toSet());
337
338                 valueMap
339                     .entrySet()
340                     .stream()
341                     .filter( (e) -> "properties".equals(e.getKey()))
342                     .forEach((propertyEntries) -> {
343                         Map<String, Object> propertyRealEntries = (Map<String, Object>) propertyEntries.getValue();
344                         propertyRealEntries
345                             .entrySet()
346                             .forEach((propertyEntry) -> {
347                                 Definition.Property definitionProperty = new Definition.Property();
348                                 String propertyKey = propertyEntry.getKey();
349                                 if(requiredPropsSet.contains(propertyKey)){
350                                     definitionProperty.setRequired(true);
351                                 }
352                                 definitionProperty.setPropertyName(propertyKey);
353                                 Map<String, Object> definitionPropertyMap = (Map<String, Object>) propertyEntry.getValue();
354
355                                 if(definitionPropertyMap.containsKey("description")){
356                                     definitionProperty.setPropertyDescription(definitionPropertyMap.get("description").toString());
357                                     definitionProperty.setHasPropertyDescription(true);
358                                 }
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());
367                                         } else {
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));
375                                                 }
376                                                 definitionProperty.setPropertyReference(refItem);
377                                             }
378                                         }
379                                     } else {
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));
386                                             }
387                                             definitionProperty.setPropertyReference(refItem);
388                                         }
389                                     }
390                                 }
391                                 definitionProperties.add(definitionProperty);
392                             });
393                     });
394
395                 definition.setPropertyList(definitionProperties);
396
397                 List<Definition.Property> schemaProperties = definitionProperties.
398                         stream()
399                         .filter((o) -> o.isHasPropertyReference())
400                         .collect(Collectors.toList());
401
402                 List<Definition.Property> regularProperties = definitionProperties.
403                         stream()
404                         .filter((o) -> !o.isHasPropertyReference())
405                         .collect(Collectors.toList());
406
407                 definition.setRegularPropertyList(regularProperties);
408                 definition.setSchemaPropertyList(schemaProperties);
409
410                 defintionsList.add(definition);
411             });
412         return defintionsList;
413     }
414
415     public static String formatDescription(String description){
416
417         description = Arrays.stream(description.split("\n"))
418             .map((line) -> {
419                 line = line.trim();
420                 if(line.contains("######")){
421                     line = line.replaceAll("#", "");
422                     line = line.trim();
423                     String headerId = line.toLowerCase().replaceAll("\\s", "-");
424
425                     if(line.contains("Related Nodes")){
426                         return String.format("<h6 id=\"%s\">%s</h6>%s<ul>", headerId, line, LINE_SEPARATOR);
427                     } else {
428                         return String.format("<h6 id=\"%s\">%s</h6>", headerId, line);
429                     }
430                 } else if(line.startsWith("-")){
431                     line = line.replaceFirst("-", "");
432                     line = line.trim();
433                     return String.format("<li>%s</li>", line);
434                 } else {
435                     return String.format("<p>%s</p>", line);
436                 }
437             })
438             .collect(Collectors.joining(LINE_SEPARATOR));
439
440         if(description.contains("<ul>")){
441             description = description + "</ul>";
442         }
443
444         return description;
445     }
446
447 }