2 * ============LICENSE_START=======================================================
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
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=========================================================
21 package org.openecomp.aai.util.swagger;
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;
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 = "v10";
41 public static void main(String[] args) throws IOException, TemplateException {
43 String schemaDir = System.getProperty("aai.schema.dir");
44 String versionToGenerate = System.getProperty("aai.generate.version");
45 String wikiLink = System.getProperty("aai.wiki.link");
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;
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;
58 System.out.println("Warning: aai.wiki.link property is not set so using default");
59 wikiLink = DEFAULT_WIKI;
62 String yamlFile = schemaDir + "/src/main/resources/aai_swagger_yaml/aai_swagger_" + versionToGenerate + ".yaml";
63 File swaggerYamlFile = new File(yamlFile);
65 if(!swaggerYamlFile.exists()){
66 System.err.println("Unable to find the swagger yaml file: " + swaggerYamlFile);
70 Yaml yaml = new Yaml(new SafeConstructor());
71 Map<String, Object> swaggerMap = null;
73 try (BufferedReader reader = new BufferedReader(new FileReader(swaggerYamlFile))){
74 swaggerMap = (Map<String, Object>) yaml.load(reader);
75 } catch(IOException ex){
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<>();
84 List<Api> apis = convertToApi(map);
85 apis.forEach((api) -> {
86 if(!tagMap.containsKey(api.getTag())){
87 List<Api> newApis = new ArrayList<>();
89 tagMap.put(api.getTag(), newApis);
91 tagMap.get(api.getTag()).add(api);
95 Map<String, List<Api>> sortedTagMap = new TreeMap<>(tagMap);
96 sortedTagMap.forEach((key, value) -> {
97 value.sort(Comparator.comparing(Api::getPath));
100 Map<String, Object> resultMap = new HashMap<>();
102 List<Definition> definitionList = convertToDefinition(schemaDefinitionmap);
104 definitionList = definitionList
105 .stream().sorted(Comparator.comparing(Definition::getDefinitionName)).collect(Collectors.toList());
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();
114 infoDescription = Arrays.stream(infoDescription.split("\n"))
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);
124 return String.format("%s<br/>", line);
127 .collect(Collectors.joining(LINE_SEPARATOR));
129 resultMap.put("description", infoDescription);
132 Configuration configuration = new Configuration();
133 configuration.setClassForTemplateLoading(Api.class, "/");
134 configuration.setDirectoryForTemplateLoading(new File("src/main/resources/"));
136 Template template = configuration.getTemplate("swagger.html.ftl");
138 String outputDirStr = schemaDir + "/src/main/resources/aai_swagger_html";
140 File outputDir = new File(outputDirStr);
142 if(!outputDir.exists()){
143 boolean resp = outputDir.mkdir();
145 System.err.println("Unable to create the directory: " + outputDirStr);
148 } else if(outputDir.isFile()){
149 System.err.println("Unable to create the directory: " + outputDirStr + " since a filename with that string exists");
153 Writer file = new FileWriter(new File(outputDirStr + "/aai_swagger_" + versionToGenerate + ".html"));
154 template.process(resultMap, file);
157 public static List<Api> convertToApi(Map<String, Object> pathMap){
160 throw new IllegalArgumentException();
162 List<Api> apis = new ArrayList<>();
164 pathMap.forEach( (pathKey, pathValue) -> {
167 Map<String, Object> httpVerbMap = (Map<String, Object>) pathValue;
168 List<Api.HttpVerb> httpVerbs = new ArrayList<>();
170 api.setPath(pathKey);
172 httpVerbMap.forEach((httpVerbKey, httpVerbValue) -> {
174 Api.HttpVerb httpVerb = new Api.HttpVerb();
176 Map<String, Object> httpVerbValueMap = (Map<String,Object>)httpVerbValue;
178 httpVerb.setType(httpVerbKey);
180 if(httpVerbValueMap.containsKey("tags")){
181 httpVerb.setTags((List<String>)httpVerbValueMap.get("tags"));
184 if(httpVerbValueMap.containsKey("summary")){
185 httpVerb.setSummary((String)httpVerbValueMap.get("summary"));
188 if(httpVerbValueMap.containsKey("operationId")){
189 httpVerb.setOperationId((String)httpVerbValueMap.get("operationId"));
192 if(httpVerbValueMap.containsKey("consumes")){
193 httpVerb.setConsumes((List<String>)httpVerbValueMap.get("consumes"));
194 if(httpVerb.getConsumes() != null){
195 httpVerb.setConsumerEnabled(true);
199 if(httpVerbValueMap.containsKey("produces")){
200 httpVerb.setProduces((List<String>)httpVerbValueMap.get("produces"));
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
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);
214 List<Map<String, Object>> requestBodyList = parameters
216 .filter((parameter) -> parameter.get("name").equals("body"))
217 .collect(Collectors.toList());
219 Map<String, Object> requestBody = null;
221 if(requestBodyList != null && requestBodyList.size() == 1){
222 requestBody = requestBodyList.get(0);
223 httpVerb.setBodyParametersEnabled(true);
224 httpVerb.setBodyParameters(requestBody);
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));
240 if(httpVerbValueMap.containsKey("responses")){
242 List<Api.HttpVerb.Response> responses = new ArrayList<Api.HttpVerb.Response>();
244 Map<String, Object> responsesMap = (Map<String, Object>) httpVerbValueMap.get("responses");
249 .filter((res) -> !"default".equalsIgnoreCase(res.getKey()))
250 .forEach((responseMap) -> {
252 Map<String, Object> responseValueMap = (Map<String, Object>)responseMap.getValue();
254 Api.HttpVerb.Response response = new Api.HttpVerb.Response();
256 response.setResponseCode(responseMap.getKey());
257 response.setDescription((String) responseValueMap.get("description"));
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));
272 responses.add(response);
276 httpVerb.setResponses(responses);
279 httpVerbs.add(httpVerb);
282 api.setHttpMethods(httpVerbs);
289 public static List<Definition> convertToDefinition(Map<String, Object> definitionMap) {
291 if(definitionMap == null)
292 throw new IllegalArgumentException();
294 List<Definition> defintionsList = new ArrayList<>();
298 .forEach((entry) -> {
300 Definition definition = new Definition();
301 String key = entry.getKey();
302 Map<String, Object> valueMap = (Map<String, Object>) entry.getValue();
304 definition.setDefinitionName(key);
306 if(valueMap.containsKey("description")){
307 String description = valueMap.get("description").toString();
308 description = formatDescription(description);
309 definition.setDefinitionDescription(description);
310 definition.setHasDescription(true);
313 List<Definition.Property> definitionProperties = new ArrayList<>();
315 List<String> requiredProperties = (valueMap.get("required") == null) ? new ArrayList<>() : (List<String>) valueMap.get("required");
317 Set<String> requiredPropsSet = requiredProperties.stream().collect(Collectors.toSet());
322 .filter( (e) -> "properties".equals(e.getKey()))
323 .forEach((propertyEntries) -> {
324 Map<String, Object> propertyRealEntries = (Map<String, Object>) propertyEntries.getValue();
327 .forEach((propertyEntry) -> {
328 Definition.Property definitionProperty = new Definition.Property();
329 String propertyKey = propertyEntry.getKey();
330 if(requiredPropsSet.contains(propertyKey)){
331 definitionProperty.setRequired(true);
333 definitionProperty.setPropertyName(propertyKey);
334 Map<String, Object> definitionPropertyMap = (Map<String, Object>) propertyEntry.getValue();
336 if(definitionPropertyMap.containsKey("description")){
337 definitionProperty.setPropertyDescription(definitionPropertyMap.get("description").toString());
338 definitionProperty.setHasPropertyDescription(true);
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());
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));
357 definitionProperty.setPropertyReference(refItem);
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));
368 definitionProperty.setPropertyReference(refItem);
372 definitionProperties.add(definitionProperty);
376 definition.setPropertyList(definitionProperties);
378 List<Definition.Property> schemaProperties = definitionProperties.
380 .filter((o) -> o.isHasPropertyReference())
381 .collect(Collectors.toList());
383 List<Definition.Property> regularProperties = definitionProperties.
385 .filter((o) -> !o.isHasPropertyReference())
386 .collect(Collectors.toList());
388 definition.setRegularPropertyList(regularProperties);
389 definition.setSchemaPropertyList(schemaProperties);
391 defintionsList.add(definition);
393 return defintionsList;
396 public static String formatDescription(String description){
398 description = Arrays.stream(description.split("\n"))
401 if(line.contains("######")){
402 line = line.replaceAll("#", "");
404 String headerId = line.toLowerCase().replaceAll("\\s", "-");
406 if(line.contains("Related Nodes")){
407 return String.format("<h6 id=\"%s\">%s</h6>%s<ul>", headerId, line, LINE_SEPARATOR);
409 return String.format("<h6 id=\"%s\">%s</h6>", headerId, line);
411 } else if(line.startsWith("-")){
412 line = line.replaceFirst("-", "");
414 return String.format("<li>%s</li>", line);
416 return String.format("<p>%s</p>", line);
419 .collect(Collectors.joining(LINE_SEPARATOR));
421 if(description.contains("<ul>")){
422 description = description + "</ul>";