[AAI-50] Add support for v11 version APIs
[aai/aai-common.git] / aai-core / src / main / java / org / openecomp / aai / util / swagger / GenerateSwagger.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.openecomp.aai
4  * ================================================================================
5  * Copyright (C) 2017 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
21 package org.openecomp.aai.util.swagger;
22
23 import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml;
24 import com.fasterxml.jackson.dataformat.yaml.snakeyaml.constructor.SafeConstructor;
25 import freemarker.template.Configuration;
26 import freemarker.template.Template;
27 import freemarker.template.TemplateException;
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 = "v11";
40
41     public static void main(String[] args) throws IOException, TemplateException {
42
43         String schemaDir         = System.getProperty("aai.schema.dir");
44         String versionToGenerate = System.getProperty("aai.generate.version");
45         String wikiLink = System.getProperty("aai.wiki.link");
46
47         if(schemaDir == null){
48             System.out.println("Warning: Schema directory is not set so using default schema dir: " + DEFAULT_SCHEMA_DIR);
49             schemaDir = DEFAULT_SCHEMA_DIR;
50         }
51
52         if(versionToGenerate == null){
53             System.out.println("Warning: Version to generate is not set so using default version: " + CURRENT_VERSION);
54             versionToGenerate = CURRENT_VERSION;
55         }
56
57         if(wikiLink == null){
58             System.out.println("Warning: aai.wiki.link property is not set so using default");
59             wikiLink = DEFAULT_WIKI;
60         }
61
62         String yamlFile = schemaDir + "/src/main/resources/aai_swagger_yaml/aai_swagger_" + versionToGenerate + ".yaml";
63         File swaggerYamlFile = new File(yamlFile);
64
65         if(!swaggerYamlFile.exists()){
66             System.err.println("Unable to find the swagger yaml file: " + swaggerYamlFile);
67             System.exit(1);
68         }
69
70         Yaml yaml = new Yaml(new SafeConstructor());
71         Map<String, Object> swaggerMap = null;
72
73         try (BufferedReader reader = new BufferedReader(new FileReader(swaggerYamlFile))){
74             swaggerMap = (Map<String, Object>) yaml.load(reader);
75         } catch(IOException ex){
76             ex.printStackTrace();
77         }
78
79         Map<String, Object> map = (Map<String, Object>) swaggerMap.get("paths");
80         Map<String, Object> schemaDefinitionmap = (Map<String, Object>) swaggerMap.get("definitions");
81         Map<String, Object> infoMap = (Map<String, Object>) swaggerMap.get("info");
82         Map<String, List<Api>> tagMap = new LinkedHashMap<>();
83
84         List<Api> apis = convertToApi(map);
85         apis.forEach((api) -> {
86             if(!tagMap.containsKey(api.getTag())){
87                 List<Api> newApis = new ArrayList<>();
88                 newApis.add(api);
89                 tagMap.put(api.getTag(), newApis);
90             } else {
91                 tagMap.get(api.getTag()).add(api);
92             }
93         });
94
95         Map<String, List<Api>> sortedTagMap = new TreeMap<>(tagMap);
96         sortedTagMap.forEach((key, value) -> {
97             value.sort(Comparator.comparing(Api::getPath));
98         });
99
100         Map<String, Object> resultMap = new HashMap<>();
101
102         List<Definition> definitionList = convertToDefinition(schemaDefinitionmap);
103
104         definitionList = definitionList
105             .stream().sorted(Comparator.comparing(Definition::getDefinitionName)).collect(Collectors.toList());
106
107         resultMap.put("aaiApis", tagMap);
108         resultMap.put("sortedAaiApis", sortedTagMap);
109         resultMap.put("wikiLink", wikiLink);
110         resultMap.put("definitions", definitionList);
111         if (infoMap.containsKey("description")) {
112             String infoDescription = infoMap.get("description").toString();
113
114             infoDescription = Arrays.stream(infoDescription.split("\n"))
115                     .map(line -> {
116                         line = line.trim();
117                         String hyperLink = "";
118                         if(line.trim().contains("https://")){
119                             int startIndex = line.indexOf("https://");
120                             int endIndex = line.lastIndexOf("/");
121                             hyperLink = line.substring(startIndex, endIndex);
122                             return String.format("<a href=\"%s\">%s</a><br/>", hyperLink, line);
123                         }
124                         return String.format("%s<br/>", line);
125                     })
126
127                     .collect(Collectors.joining(LINE_SEPARATOR));
128
129             resultMap.put("description", infoDescription);
130         }
131
132         Configuration configuration = new Configuration();
133         configuration.setClassForTemplateLoading(Api.class, "/");
134         configuration.setDirectoryForTemplateLoading(new File("src/main/resources/"));
135
136         Template template = configuration.getTemplate("swagger.html.ftl");
137
138         String outputDirStr = schemaDir + "/src/main/resources/aai_swagger_html";
139
140         File outputDir = new File(outputDirStr);
141
142         if(!outputDir.exists()){
143             boolean resp = outputDir.mkdir();
144             if(!resp){
145                 System.err.println("Unable to create the directory: " + outputDirStr);
146                 System.exit(1);
147             }
148         } else if(outputDir.isFile()){
149             System.err.println("Unable to create the directory: " + outputDirStr + " since a filename with that string exists");
150             System.exit(1);
151         }
152
153         Writer file = new FileWriter(new File(outputDirStr +  "/aai_swagger_" + versionToGenerate + ".html"));
154         template.process(resultMap, file);
155     }
156
157     public static List<Api> convertToApi(Map<String, Object> pathMap){
158
159         if(pathMap == null)
160             throw new IllegalArgumentException();
161
162         List<Api> apis = new ArrayList<>();
163
164         pathMap.forEach( (pathKey, pathValue) -> {
165
166             Api api = new Api();
167             Map<String, Object> httpVerbMap = (Map<String, Object>) pathValue;
168             List<Api.HttpVerb> httpVerbs = new ArrayList<>();
169
170             api.setPath(pathKey);
171
172             httpVerbMap.forEach((httpVerbKey, httpVerbValue) -> {
173
174                 Api.HttpVerb httpVerb = new Api.HttpVerb();
175
176                 Map<String, Object> httpVerbValueMap = (Map<String,Object>)httpVerbValue;
177
178                 httpVerb.setType(httpVerbKey);
179
180                 if(httpVerbValueMap.containsKey("tags")){
181                     httpVerb.setTags((List<String>)httpVerbValueMap.get("tags"));
182                 }
183
184                 if(httpVerbValueMap.containsKey("summary")){
185                     httpVerb.setSummary((String)httpVerbValueMap.get("summary"));
186                 }
187
188                 if(httpVerbValueMap.containsKey("operationId")){
189                     httpVerb.setOperationId((String)httpVerbValueMap.get("operationId"));
190                 }
191
192                 if(httpVerbValueMap.containsKey("consumes")){
193                     httpVerb.setConsumes((List<String>)httpVerbValueMap.get("consumes"));
194                     if(httpVerb.getConsumes() != null){
195                         httpVerb.setConsumerEnabled(true);
196                     }
197                 }
198
199                 if(httpVerbValueMap.containsKey("produces")){
200                     httpVerb.setProduces((List<String>)httpVerbValueMap.get("produces"));
201                 }
202
203                 if(httpVerbValueMap.containsKey("parameters")){
204                     List<Map<String, Object>> parameters = (List<Map<String, Object>>) httpVerbValueMap.get("parameters");
205                     List<Map<String, Object>> requestParameters = parameters
206                             .stream()
207                             .filter((parameter) -> !parameter.get("name").equals("body"))
208                             .collect(Collectors.toList());
209                     httpVerb.setParameters(requestParameters);
210                     if(httpVerb.getParameters() != null){
211                         httpVerb.setParametersEnabled(true);
212                     }
213
214                     List<Map<String, Object>> requestBodyList = parameters
215                             .stream()
216                             .filter((parameter) -> parameter.get("name").equals("body"))
217                             .collect(Collectors.toList());
218
219                     Map<String, Object> requestBody = null;
220
221                     if(requestBodyList != null && requestBodyList.size() == 1){
222                         requestBody = requestBodyList.get(0);
223                         httpVerb.setBodyParametersEnabled(true);
224                         httpVerb.setBodyParameters(requestBody);
225
226                         if(requestBody != null && requestBody.containsKey("schema")){
227                             Map<String, Object> schemaMap = (Map<String, Object>)requestBody.get("schema");
228                             if(schemaMap != null && schemaMap.containsKey("$ref")){
229                                 String schemaLink = schemaMap.get("$ref").toString();
230                                 httpVerb.setSchemaLink(schemaLink);
231                                 int retCode = schemaLink.lastIndexOf('/');
232                                 if(retCode != -1 && retCode != schemaLink.length()){
233                                     httpVerb.setSchemaType(schemaLink.substring(retCode));
234                                 }
235                             }
236                         }
237                     }
238                 }
239
240                 if(httpVerbValueMap.containsKey("responses")){
241
242                     List<Api.HttpVerb.Response> responses = new ArrayList<Api.HttpVerb.Response>();
243
244                     Map<String, Object> responsesMap = (Map<String, Object>) httpVerbValueMap.get("responses");
245
246                     responsesMap
247                         .entrySet()
248                         .stream()
249                         .filter((res) -> !"default".equalsIgnoreCase(res.getKey()))
250                         .forEach((responseMap) -> {
251
252                             Map<String, Object> responseValueMap = (Map<String, Object>)responseMap.getValue();
253
254                             Api.HttpVerb.Response response = new Api.HttpVerb.Response();
255
256                             response.setResponseCode(responseMap.getKey());
257                             response.setDescription((String) responseValueMap.get("description"));
258
259                             if(responseValueMap != null && responseValueMap.containsKey("schema")){
260                                 Map<String, Object> schemaMap = (Map<String, Object>)responseValueMap.get("schema");
261                                 if(schemaMap != null && schemaMap.containsKey("$ref")){
262                                     String schemaLink = schemaMap.get("$ref").toString();
263                                     httpVerb.setHasReturnSchema(true);
264                                     httpVerb.setReturnSchemaLink(schemaLink);
265                                     int retCode = schemaLink.lastIndexOf('/');
266                                     if(retCode != -1 && retCode != schemaLink.length()){
267                                         httpVerb.setReturnSchemaObject(schemaLink.substring(retCode));
268                                     }
269                                 }
270                             }
271
272                             responses.add(response);
273                         }
274                     );
275
276                     httpVerb.setResponses(responses);
277                 }
278
279                 httpVerbs.add(httpVerb);
280             });
281
282             api.setHttpMethods(httpVerbs);
283             apis.add(api);
284         });
285
286         return apis;
287     }
288
289     public static List<Definition> convertToDefinition(Map<String, Object> definitionMap) {
290
291         if(definitionMap == null)
292             throw new IllegalArgumentException();
293
294         List<Definition> defintionsList = new ArrayList<>();
295
296         definitionMap
297             .entrySet()
298             .forEach((entry) -> {
299
300                 Definition definition = new Definition();
301                 String key = entry.getKey();
302                 Map<String, Object> valueMap = (Map<String, Object>) entry.getValue();
303
304                 definition.setDefinitionName(key);
305
306                 if(valueMap.containsKey("description")){
307                     String description = valueMap.get("description").toString();
308                     description = formatDescription(description);
309                     definition.setDefinitionDescription(description);
310                     definition.setHasDescription(true);
311                 }
312
313                 List<Definition.Property> definitionProperties = new ArrayList<>();
314
315                 List<String> requiredProperties = (valueMap.get("required") == null) ? new ArrayList<>() : (List<String>) valueMap.get("required");
316
317                 Set<String> requiredPropsSet = requiredProperties.stream().collect(Collectors.toSet());
318
319                 valueMap
320                     .entrySet()
321                     .stream()
322                     .filter( (e) -> "properties".equals(e.getKey()))
323                     .forEach((propertyEntries) -> {
324                         Map<String, Object> propertyRealEntries = (Map<String, Object>) propertyEntries.getValue();
325                         propertyRealEntries
326                             .entrySet()
327                             .forEach((propertyEntry) -> {
328                                 Definition.Property definitionProperty = new Definition.Property();
329                                 String propertyKey = propertyEntry.getKey();
330                                 if(requiredPropsSet.contains(propertyKey)){
331                                     definitionProperty.setRequired(true);
332                                 }
333                                 definitionProperty.setPropertyName(propertyKey);
334                                 Map<String, Object> definitionPropertyMap = (Map<String, Object>) propertyEntry.getValue();
335
336                                 if(definitionPropertyMap.containsKey("description")){
337                                     definitionProperty.setPropertyDescription(definitionPropertyMap.get("description").toString());
338                                     definitionProperty.setHasPropertyDescription(true);
339                                 }
340                                 if(definitionPropertyMap.containsKey("type")){
341                                     String type = definitionPropertyMap.get("type").toString();
342                                     definitionProperty.setPropertyType(type);
343                                     definitionProperty.setHasType(true);
344                                     if ("array".equals(type)) {
345                                         definitionProperty.setPropertyType("object[]");
346                                         if(!definitionPropertyMap.containsKey("items")){
347                                             throw new RuntimeException("Unable to find the property items even though the type is array for " + propertyEntry.getKey());
348                                         } else {
349                                             Map<String, Object> itemMap = (Map<String, Object>) definitionPropertyMap.get("items");
350                                             if(itemMap.containsKey("$ref")){
351                                                 definitionProperty.setHasPropertyReference(true);
352                                                 String refItem = itemMap.get("$ref").toString();
353                                                 int retCode = refItem.lastIndexOf('/');
354                                                 if(retCode != -1 && retCode != refItem.length()){
355                                                     definitionProperty.setPropertyReferenceObjectName(refItem.substring(retCode + 1));
356                                                 }
357                                                 definitionProperty.setPropertyReference(refItem);
358                                             }
359                                         }
360                                     } else {
361                                         if(definitionPropertyMap.containsKey("$ref")){
362                                             definitionProperty.setHasPropertyReference(true);
363                                             String refItem = definitionPropertyMap.get("$ref").toString();
364                                             int retCode = refItem.lastIndexOf('/');
365                                             if(retCode != -1 && retCode != refItem.length()){
366                                                 definitionProperty.setPropertyReferenceObjectName(refItem.substring(retCode + 1));
367                                             }
368                                             definitionProperty.setPropertyReference(refItem);
369                                         }
370                                     }
371                                 }
372                                 definitionProperties.add(definitionProperty);
373                             });
374                     });
375
376                 definition.setPropertyList(definitionProperties);
377
378                 List<Definition.Property> schemaProperties = definitionProperties.
379                         stream()
380                         .filter((o) -> o.isHasPropertyReference())
381                         .collect(Collectors.toList());
382
383                 List<Definition.Property> regularProperties = definitionProperties.
384                         stream()
385                         .filter((o) -> !o.isHasPropertyReference())
386                         .collect(Collectors.toList());
387
388                 definition.setRegularPropertyList(regularProperties);
389                 definition.setSchemaPropertyList(schemaProperties);
390
391                 defintionsList.add(definition);
392             });
393         return defintionsList;
394     }
395
396     public static String formatDescription(String description){
397
398         description = Arrays.stream(description.split("\n"))
399             .map((line) -> {
400                 line = line.trim();
401                 if(line.contains("######")){
402                     line = line.replaceAll("#", "");
403                     line = line.trim();
404                     String headerId = line.toLowerCase().replaceAll("\\s", "-");
405
406                     if(line.contains("Related Nodes")){
407                         return String.format("<h6 id=\"%s\">%s</h6>%s<ul>", headerId, line, LINE_SEPARATOR);
408                     } else {
409                         return String.format("<h6 id=\"%s\">%s</h6>", headerId, line);
410                     }
411                 } else if(line.startsWith("-")){
412                     line = line.replaceFirst("-", "");
413                     line = line.trim();
414                     return String.format("<li>%s</li>", line);
415                 } else {
416                     return String.format("<p>%s</p>", line);
417                 }
418             })
419             .collect(Collectors.joining(LINE_SEPARATOR));
420
421         if(description.contains("<ul>")){
422             description = description + "</ul>";
423         }
424
425         return description;
426     }
427
428 }