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