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 = "v11";
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 if(null == swaggerMap) {
80 throw new IOException();
83 Map<String, Object> map = (Map<String, Object>) swaggerMap.get("paths");
84 Map<String, Object> schemaDefinitionmap = (Map<String, Object>) swaggerMap.get("definitions");
85 Map<String, Object> infoMap = (Map<String, Object>) swaggerMap.get("info");
86 Map<String, List<Api>> tagMap = new LinkedHashMap<>();
88 List<Api> apis = convertToApi(map);
89 apis.forEach((api) -> {
90 if(!tagMap.containsKey(api.getTag())){
91 List<Api> newApis = new ArrayList<>();
93 tagMap.put(api.getTag(), newApis);
95 tagMap.get(api.getTag()).add(api);
99 Map<String, List<Api>> sortedTagMap = new TreeMap<>(tagMap);
100 sortedTagMap.forEach((key, value) -> {
101 value.sort(Comparator.comparing(Api::getPath));
104 Map<String, Object> resultMap = new HashMap<>();
106 List<Definition> definitionList = convertToDefinition(schemaDefinitionmap);
108 definitionList = definitionList
109 .stream().sorted(Comparator.comparing(Definition::getDefinitionName)).collect(Collectors.toList());
111 resultMap.put("aaiApis", tagMap);
112 resultMap.put("sortedAaiApis", sortedTagMap);
113 resultMap.put("wikiLink", wikiLink);
114 resultMap.put("definitions", definitionList);
115 if (infoMap.containsKey("description")) {
116 String infoDescription = infoMap.get("description").toString();
118 infoDescription = Arrays.stream(infoDescription.split("\n"))
121 String hyperLink = "";
122 if(line.trim().contains("https://")){
123 int startIndex = line.indexOf("https://");
124 int endIndex = line.lastIndexOf("/");
125 hyperLink = line.substring(startIndex, endIndex);
126 return String.format("<a href=\"%s\">%s</a><br/>", hyperLink, line);
128 return String.format("%s<br/>", line);
131 .collect(Collectors.joining(LINE_SEPARATOR));
133 resultMap.put("description", infoDescription);
136 Configuration configuration = new Configuration();
137 configuration.setClassForTemplateLoading(Api.class, "/");
138 configuration.setDirectoryForTemplateLoading(new File("src/main/resources/"));
140 Template template = configuration.getTemplate("swagger.html.ftl");
142 String outputDirStr = schemaDir + "/src/main/resources/aai_swagger_html";
144 File outputDir = new File(outputDirStr);
146 if(!outputDir.exists()){
147 boolean resp = outputDir.mkdir();
149 System.err.println("Unable to create the directory: " + outputDirStr);
152 } else if(outputDir.isFile()){
153 System.err.println("Unable to create the directory: " + outputDirStr + " since a filename with that string exists");
157 Writer file = new FileWriter(new File(outputDirStr + "/aai_swagger_" + versionToGenerate + ".html"));
158 template.process(resultMap, file);
161 public static List<Api> convertToApi(Map<String, Object> pathMap){
164 throw new IllegalArgumentException();
166 List<Api> apis = new ArrayList<>();
168 pathMap.forEach( (pathKey, pathValue) -> {
171 Map<String, Object> httpVerbMap = (Map<String, Object>) pathValue;
172 List<Api.HttpVerb> httpVerbs = new ArrayList<>();
174 api.setPath(pathKey);
176 httpVerbMap.forEach((httpVerbKey, httpVerbValue) -> {
178 Api.HttpVerb httpVerb = new Api.HttpVerb();
180 Map<String, Object> httpVerbValueMap = (Map<String,Object>)httpVerbValue;
182 httpVerb.setType(httpVerbKey);
184 if(httpVerbValueMap.containsKey("tags")){
185 httpVerb.setTags((List<String>)httpVerbValueMap.get("tags"));
188 if(httpVerbValueMap.containsKey("summary")){
189 httpVerb.setSummary((String)httpVerbValueMap.get("summary"));
192 if(httpVerbValueMap.containsKey("operationId")){
193 httpVerb.setOperationId((String)httpVerbValueMap.get("operationId"));
196 if(httpVerbValueMap.containsKey("consumes")){
197 httpVerb.setConsumes((List<String>)httpVerbValueMap.get("consumes"));
198 if(httpVerb.getConsumes() != null){
199 httpVerb.setConsumerEnabled(true);
203 if(httpVerbValueMap.containsKey("produces")){
204 httpVerb.setProduces((List<String>)httpVerbValueMap.get("produces"));
207 if(httpVerbValueMap.containsKey("parameters")){
208 List<Map<String, Object>> parameters = (List<Map<String, Object>>) httpVerbValueMap.get("parameters");
209 List<Map<String, Object>> requestParameters = parameters
211 .filter((parameter) -> !parameter.get("name").equals("body"))
212 .collect(Collectors.toList());
213 httpVerb.setParameters(requestParameters);
214 if(httpVerb.getParameters() != null){
215 httpVerb.setParametersEnabled(true);
218 List<Map<String, Object>> requestBodyList = parameters
220 .filter((parameter) -> parameter.get("name").equals("body"))
221 .collect(Collectors.toList());
223 Map<String, Object> requestBody = null;
225 if(requestBodyList != null && requestBodyList.size() == 1){
226 requestBody = requestBodyList.get(0);
227 httpVerb.setBodyParametersEnabled(true);
228 httpVerb.setBodyParameters(requestBody);
230 if(requestBody != null && requestBody.containsKey("schema")){
231 Map<String, Object> schemaMap = (Map<String, Object>)requestBody.get("schema");
232 if(schemaMap != null && schemaMap.containsKey("$ref")){
233 String schemaLink = schemaMap.get("$ref").toString();
234 httpVerb.setSchemaLink(schemaLink);
235 int retCode = schemaLink.lastIndexOf('/');
236 if(retCode != -1 && retCode != schemaLink.length()){
237 httpVerb.setSchemaType(schemaLink.substring(retCode));
244 if(httpVerbValueMap.containsKey("responses")){
246 List<Api.HttpVerb.Response> responses = new ArrayList<Api.HttpVerb.Response>();
248 Map<String, Object> responsesMap = (Map<String, Object>) httpVerbValueMap.get("responses");
253 .filter((res) -> !"default".equalsIgnoreCase(res.getKey()))
254 .forEach((responseMap) -> {
256 Map<String, Object> responseValueMap = (Map<String, Object>)responseMap.getValue();
258 Api.HttpVerb.Response response = new Api.HttpVerb.Response();
260 response.setResponseCode(responseMap.getKey());
261 response.setDescription((String) responseValueMap.get("description"));
263 if(responseValueMap != null && responseValueMap.containsKey("schema")){
264 Map<String, Object> schemaMap = (Map<String, Object>)responseValueMap.get("schema");
265 if(schemaMap != null && schemaMap.containsKey("$ref")){
266 String schemaLink = schemaMap.get("$ref").toString();
267 httpVerb.setHasReturnSchema(true);
268 httpVerb.setReturnSchemaLink(schemaLink);
269 int retCode = schemaLink.lastIndexOf('/');
270 if(retCode != -1 && retCode != schemaLink.length()){
271 httpVerb.setReturnSchemaObject(schemaLink.substring(retCode));
276 responses.add(response);
280 httpVerb.setResponses(responses);
283 httpVerbs.add(httpVerb);
286 api.setHttpMethods(httpVerbs);
293 public static List<Definition> convertToDefinition(Map<String, Object> definitionMap) {
295 if(definitionMap == null)
296 throw new IllegalArgumentException();
298 List<Definition> defintionsList = new ArrayList<>();
302 .forEach((entry) -> {
304 Definition definition = new Definition();
305 String key = entry.getKey();
306 Map<String, Object> valueMap = (Map<String, Object>) entry.getValue();
308 definition.setDefinitionName(key);
310 if(valueMap.containsKey("description")){
311 String description = valueMap.get("description").toString();
312 description = formatDescription(description);
313 definition.setDefinitionDescription(description);
314 definition.setHasDescription(true);
317 List<Definition.Property> definitionProperties = new ArrayList<>();
319 List<String> requiredProperties = (valueMap.get("required") == null) ? new ArrayList<>() : (List<String>) valueMap.get("required");
321 Set<String> requiredPropsSet = requiredProperties.stream().collect(Collectors.toSet());
326 .filter( (e) -> "properties".equals(e.getKey()))
327 .forEach((propertyEntries) -> {
328 Map<String, Object> propertyRealEntries = (Map<String, Object>) propertyEntries.getValue();
331 .forEach((propertyEntry) -> {
332 Definition.Property definitionProperty = new Definition.Property();
333 String propertyKey = propertyEntry.getKey();
334 if(requiredPropsSet.contains(propertyKey)){
335 definitionProperty.setRequired(true);
337 definitionProperty.setPropertyName(propertyKey);
338 Map<String, Object> definitionPropertyMap = (Map<String, Object>) propertyEntry.getValue();
340 if(definitionPropertyMap.containsKey("description")){
341 definitionProperty.setPropertyDescription(definitionPropertyMap.get("description").toString());
342 definitionProperty.setHasPropertyDescription(true);
344 if(definitionPropertyMap.containsKey("type")){
345 String type = definitionPropertyMap.get("type").toString();
346 definitionProperty.setPropertyType(type);
347 definitionProperty.setHasType(true);
348 if ("array".equals(type)) {
349 definitionProperty.setPropertyType("object[]");
350 if(!definitionPropertyMap.containsKey("items")){
351 throw new RuntimeException("Unable to find the property items even though the type is array for " + propertyEntry.getKey());
353 Map<String, Object> itemMap = (Map<String, Object>) definitionPropertyMap.get("items");
354 if(itemMap.containsKey("$ref")){
355 definitionProperty.setHasPropertyReference(true);
356 String refItem = itemMap.get("$ref").toString();
357 int retCode = refItem.lastIndexOf('/');
358 if(retCode != -1 && retCode != refItem.length()){
359 definitionProperty.setPropertyReferenceObjectName(refItem.substring(retCode + 1));
361 definitionProperty.setPropertyReference(refItem);
365 if(definitionPropertyMap.containsKey("$ref")){
366 definitionProperty.setHasPropertyReference(true);
367 String refItem = definitionPropertyMap.get("$ref").toString();
368 int retCode = refItem.lastIndexOf('/');
369 if(retCode != -1 && retCode != refItem.length()){
370 definitionProperty.setPropertyReferenceObjectName(refItem.substring(retCode + 1));
372 definitionProperty.setPropertyReference(refItem);
376 definitionProperties.add(definitionProperty);
380 definition.setPropertyList(definitionProperties);
382 List<Definition.Property> schemaProperties = definitionProperties.
384 .filter((o) -> o.isHasPropertyReference())
385 .collect(Collectors.toList());
387 List<Definition.Property> regularProperties = definitionProperties.
389 .filter((o) -> !o.isHasPropertyReference())
390 .collect(Collectors.toList());
392 definition.setRegularPropertyList(regularProperties);
393 definition.setSchemaPropertyList(schemaProperties);
395 defintionsList.add(definition);
397 return defintionsList;
400 public static String formatDescription(String description){
402 description = Arrays.stream(description.split("\n"))
405 if(line.contains("######")){
406 line = line.replaceAll("#", "");
408 String headerId = line.toLowerCase().replaceAll("\\s", "-");
410 if(line.contains("Related Nodes")){
411 return String.format("<h6 id=\"%s\">%s</h6>%s<ul>", headerId, line, LINE_SEPARATOR);
413 return String.format("<h6 id=\"%s\">%s</h6>", headerId, line);
415 } else if(line.startsWith("-")){
416 line = line.replaceFirst("-", "");
418 return String.format("<li>%s</li>", line);
420 return String.format("<p>%s</p>", line);
423 .collect(Collectors.joining(LINE_SEPARATOR));
425 if(description.contains("<ul>")){
426 description = description + "</ul>";