Add instructions to invoke the linter and code formatter plugins to the README and...
[aai/schema-service.git] / aai-schema-gen / src / main / java / org / onap / aai / schemagen / GenerateXsd.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
21 package org.onap.aai.schemagen;
22
23 import java.io.BufferedWriter;
24 import java.io.File;
25 import java.io.IOException;
26 import java.nio.charset.Charset;
27 import java.nio.charset.StandardCharsets;
28 import java.nio.file.Files;
29 import java.nio.file.Path;
30 import java.nio.file.Paths;
31 import java.util.*;
32
33 import org.onap.aai.schemagen.genxsd.HTMLfromOXM;
34 import org.onap.aai.schemagen.genxsd.NodesYAMLfromOXM;
35 import org.onap.aai.schemagen.genxsd.YAMLfromOXM;
36 import org.onap.aai.setup.SchemaVersion;
37 import org.onap.aai.setup.SchemaVersions;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
41 import org.w3c.dom.NodeList;
42
43 public class GenerateXsd {
44
45     private static final Logger logger = LoggerFactory.getLogger("GenerateXsd.class");
46     protected static String apiVersion = null;
47     public static AnnotationConfigApplicationContext ctx = null;
48     static String apiVersionFmt = null;
49     static boolean useAnnotationsInXsd = false;
50     static String responsesUrl = null;
51     static String responsesLabel = null;
52     static String jsonEdges = null;
53     static Map<String, String> generatedJavaType;
54     static Map<String, String> appliedPaths;
55     static String RELEASE = System.getProperty("aai.release", "onap");
56
57     static NodeList javaTypeNodes;
58     static Map<String, String> javaTypeDefinitions = createJavaTypeDefinitions();
59
60     private static Map<String, String> createJavaTypeDefinitions() {
61         StringBuilder aaiInternal = new StringBuilder();
62         Map<String, String> javaTypeDefinitions = new HashMap<String, String>();
63         aaiInternal.append("  aai-internal:\n");
64         aaiInternal.append("    properties:\n");
65         aaiInternal.append("      property-name:\n");
66         aaiInternal.append("        type: string\n");
67         aaiInternal.append("      property-value:\n");
68         aaiInternal.append("        type: string\n");
69         // javaTypeDefinitions.put("aai-internal", aaiInternal.toString());
70         return javaTypeDefinitions;
71     }
72
73     public static final int VALUE_NONE = 0;
74     public static final int VALUE_DESCRIPTION = 1;
75     public static final int VALUE_INDEXED_PROPS = 2;
76     public static final int VALUE_CONTAINER = 3;
77
78     private static final String GENERATE_TYPE_XSD = "xsd";
79     private static final String GENERATE_TYPE_YAML = "yaml";
80
81     private final static String NODE_DIR = System.getProperty("nodes.configuration.location");
82     private final static String EDGE_DIR = System.getProperty("edges.configuration.location");
83     private static final String BASE_ROOT = "aai-schema/";
84     private static final String BASE_AUTO_GEN_ROOT = "aai-schema/";
85
86     private static final String ROOT = BASE_ROOT + "src/main/resources";
87     private static final String AUTO_GEN_ROOT = BASE_AUTO_GEN_ROOT + "src/main/resources";
88
89     private static final String NORMAL_START_DIR = "aai-schema-gen";
90     private static final String XSD_DIR = ROOT + "/" + RELEASE + "/aai_schema";
91
92     private static final String YAML_DIR = (((System.getProperty("user.dir") != null)
93         && (!System.getProperty("user.dir").contains(NORMAL_START_DIR))) ? AUTO_GEN_ROOT : ROOT)
94         + "/" + RELEASE + "/aai_swagger_yaml";
95
96     /* These three strings are for yaml auto-generation from aai-common class */
97
98     private static final int SWAGGER_SUPPORT_STARTS_VERSION = 1; // minimum version to support
99                                                                  // swagger documentation
100
101     private static boolean validVersion(String versionToGen) {
102
103         if ("ALL".equalsIgnoreCase(versionToGen)) {
104             return true;
105         }
106
107         SchemaVersions schemaVersions = SpringContextAware.getBean(SchemaVersions.class);
108         if (schemaVersions == null) {
109             return false;
110         }
111         for (SchemaVersion v : schemaVersions.getVersions()) {
112             if (v.toString().equals(versionToGen)) {
113                 return true;
114             }
115         }
116
117         return false;
118     }
119
120     private static boolean versionSupportsSwagger(String version) {
121         return Integer.parseInt(version.substring(1)) >= SWAGGER_SUPPORT_STARTS_VERSION;
122     }
123
124     public static String getAPIVersion() {
125         return apiVersion;
126     }
127
128     public static String getYamlDir() {
129         return YAML_DIR;
130     }
131
132     public static String getResponsesUrl() {
133         return responsesUrl;
134     }
135
136     public static void main(String[] args) throws IOException {
137         String versionToGen = System.getProperty("gen_version");
138         if (versionToGen == null) {
139             System.err.println("Version is required, ie v<n> or ALL.");
140             System.exit(1);
141         } else {
142             versionToGen = versionToGen.toLowerCase();
143         }
144
145         String fileTypeToGen = System.getProperty("gen_type");
146         if (fileTypeToGen == null) {
147             fileTypeToGen = GENERATE_TYPE_XSD;
148         } else {
149             fileTypeToGen = fileTypeToGen.toLowerCase();
150         }
151
152         AnnotationConfigApplicationContext ctx =
153             new AnnotationConfigApplicationContext("org.onap.aai.setup", "org.onap.aai.schemagen");
154
155         SchemaVersions schemaVersions = ctx.getBean(SchemaVersions.class);
156
157         if (!fileTypeToGen.equals(GENERATE_TYPE_XSD) && !fileTypeToGen.equals(GENERATE_TYPE_YAML)) {
158             System.err.println("Invalid gen_type passed. " + fileTypeToGen);
159             System.exit(1);
160         }
161
162         String responsesLabel = System.getProperty("yamlresponses_url");
163         responsesUrl = responsesLabel;
164
165         List<SchemaVersion> versionsToGen = new ArrayList<>();
166         if (!"ALL".equalsIgnoreCase(versionToGen) && !versionToGen.matches("v\\d+")
167             && !validVersion(versionToGen)) {
168             System.err.println("Invalid version passed. " + versionToGen);
169             System.exit(1);
170         } else if ("ALL".equalsIgnoreCase(versionToGen)) {
171             versionsToGen = schemaVersions.getVersions();
172             Collections.sort(versionsToGen);
173             Collections.reverse(versionsToGen);
174         } else {
175             versionsToGen.add(new SchemaVersion(versionToGen));
176         }
177
178         // process file type System property
179         if (fileTypeToGen.equals(GENERATE_TYPE_YAML)) {
180             if (responsesUrl == null || responsesUrl.length() < 1 || responsesLabel == null
181                 || responsesLabel.length() < 1) {
182                 System.err.println(
183                     "generating swagger yaml file requires yamlresponses_url and yamlresponses_label properties");
184                 System.exit(1);
185             } else {
186                 responsesUrl = "description: " + "Response codes found in [response codes]("
187                     + responsesLabel + ").\n";
188             }
189         }
190         /*
191          * TODO: Oxm Path is config driveb
192          */
193         String oxmPath;
194         if (System.getProperty("user.dir") != null
195             && !System.getProperty("user.dir").contains(NORMAL_START_DIR)) {
196             oxmPath = BASE_AUTO_GEN_ROOT + NODE_DIR;
197         } else {
198             oxmPath = BASE_ROOT + NODE_DIR;
199         }
200
201         String outfileName = null;
202         File outfile;
203         String nodesfileName = null;
204         File nodesfile;
205         String fileContent = null;
206         String nodesContent = null;
207
208         for (SchemaVersion v : versionsToGen) {
209             apiVersion = v.toString();
210             logger.debug("YAMLdir = " + YAML_DIR);
211             logger.debug("Generating " + apiVersion + " " + fileTypeToGen);
212             apiVersionFmt = "." + apiVersion + ".";
213             generatedJavaType = new HashMap<String, String>();
214             appliedPaths = new HashMap<String, String>();
215             File edgeRuleFile = null;
216             String fileName = EDGE_DIR + "DbEdgeRules_" + apiVersion + ".json";
217             logger.debug("user.dir = " + System.getProperty("user.dir"));
218             if (System.getProperty("user.dir") != null
219                 && !System.getProperty("user.dir").contains(NORMAL_START_DIR)) {
220                 fileName = BASE_AUTO_GEN_ROOT + fileName;
221
222             } else {
223                 fileName = BASE_ROOT + fileName;
224
225             }
226             edgeRuleFile = new File(fileName);
227             // Document doc = ni.getSchema(translateVersion(v));
228
229             if (fileTypeToGen.equals(GENERATE_TYPE_XSD)) {
230                 outfileName = XSD_DIR + "/aai_schema_" + apiVersion + "." + GENERATE_TYPE_XSD;
231                 try {
232                     HTMLfromOXM swagger = ctx.getBean(HTMLfromOXM.class);
233                     swagger.setVersion(v);
234                     fileContent = swagger.process();
235                     if (fileContent.startsWith("Schema format issue")) {
236                         throw new Exception(fileContent);
237                     }
238                 } catch (Exception e) {
239                     logger.error("Exception creating output file " + outfileName);
240                     logger.error(e.getMessage());
241                     System.exit(-1);
242                 }
243             } else if (versionSupportsSwagger(apiVersion)) {
244                 outfileName = YAML_DIR + "/aai_swagger_" + apiVersion + "." + GENERATE_TYPE_YAML;
245                 nodesfileName = YAML_DIR + "/aai_swagger_" + apiVersion + "." + "nodes" + "."
246                     + GENERATE_TYPE_YAML;
247                 try {
248                     YAMLfromOXM swagger = (YAMLfromOXM) ctx.getBean(YAMLfromOXM.class);
249                     swagger.setVersion(v);
250                     fileContent = swagger.process();
251                     Map combinedJavaTypes = swagger.getCombinedJavaTypes();
252                     NodesYAMLfromOXM nodesSwagger = ctx.getBean(NodesYAMLfromOXM.class);
253                     nodesSwagger.setVersion(v);
254                     nodesSwagger.setCombinedJavaTypes(combinedJavaTypes);
255                     nodesContent = nodesSwagger.process();
256                 } catch (Exception e) {
257                     logger.error("Exception creating output file " + outfileName, e);
258                 }
259             } else {
260                 continue;
261             }
262             outfile = new File(outfileName);
263             File parentDir = outfile.getParentFile();
264             if (!parentDir.exists()) {
265                 parentDir.mkdirs();
266             }
267             if (nodesfileName != null) {
268                 BufferedWriter nodesBW = null;
269                 nodesfile = new File(nodesfileName);
270                 parentDir = nodesfile.getParentFile();
271                 if (!parentDir.exists()) {
272                     parentDir.mkdirs();
273                 }
274                 try {
275                     if (!nodesfile.createNewFile()) {
276                         logger.error("File {} already exist", nodesfileName);
277                     }
278                 } catch (IOException e) {
279                     logger.error("Exception creating output file " + nodesfileName, e);
280                 }
281                 try {
282                     Charset charset = StandardCharsets.UTF_8;
283                     Path path = Paths.get(nodesfileName);
284                     nodesBW = Files.newBufferedWriter(path, charset);
285                     nodesBW.write(nodesContent);
286                 } catch (IOException e) {
287                     logger.error("Exception writing output file " + outfileName, e);
288                 } finally {
289                     if (nodesBW != null) {
290                         nodesBW.close();
291                     }
292                 }
293             }
294
295             try {
296                 if (!outfile.createNewFile()) {
297                     logger.error("File {} already exist", outfileName);
298                 }
299             } catch (IOException e) {
300                 logger.error("Exception creating output file " + outfileName, e);
301             }
302             BufferedWriter bw = null;
303             try {
304                 Charset charset = StandardCharsets.UTF_8;
305                 Path path = Paths.get(outfileName);
306                 bw = Files.newBufferedWriter(path, charset);
307                 bw.write(fileContent);
308             } catch (IOException e) {
309                 logger.error("Exception writing output file " + outfileName, e);
310             } finally {
311                 if (bw != null) {
312                     bw.close();
313                 }
314             }
315             logger.debug("GeneratedXSD successful, saved in " + outfileName);
316         }
317
318     }
319
320 }