Update schema service to fail to start
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / util / 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.util;
21
22
23 import org.onap.aai.config.SpringContextAware;
24 import org.onap.aai.setup.SchemaVersion;
25 import org.onap.aai.setup.SchemaVersions;
26 import org.onap.aai.util.genxsd.HTMLfromOXM;
27 import org.onap.aai.util.genxsd.NodesYAMLfromOXM;
28
29 import org.onap.aai.util.genxsd.YAMLfromOXM;
30 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
31 import org.w3c.dom.*;
32
33
34 import java.io.*;
35 import java.nio.charset.Charset;
36 import java.nio.file.Files;
37 import java.nio.file.Path;
38 import java.nio.file.Paths;
39 import java.util.*;
40
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 public class GenerateXsd {
45
46         private static final Logger logger = LoggerFactory.getLogger("GenerateXsd.class");
47         protected static String apiVersion = null;
48         public static AnnotationConfigApplicationContext ctx = null;
49         static String apiVersionFmt = null;
50         static boolean useAnnotationsInXsd = false;
51         static String responsesUrl = null;
52         static String responsesLabel = null;
53         static String jsonEdges = null;
54         static Map<String, String> generatedJavaType;
55         static Map<String, String> appliedPaths;
56         static String RELEASE = System.getProperty("aai.release", "onap");
57
58
59         static NodeList javaTypeNodes;
60         static Map<String,String> javaTypeDefinitions = createJavaTypeDefinitions();
61     private static Map<String, String> createJavaTypeDefinitions()
62     {
63         StringBuffer aaiInternal = new StringBuffer();
64         Map<String,String> javaTypeDefinitions = new HashMap<String, String>();
65         aaiInternal.append("  aai-internal:\n");
66         aaiInternal.append("    properties:\n");
67         aaiInternal.append("      property-name:\n");
68         aaiInternal.append("        type: string\n");
69         aaiInternal.append("      property-value:\n");
70         aaiInternal.append("        type: string\n");
71 //      javaTypeDefinitions.put("aai-internal", aaiInternal.toString());
72         return javaTypeDefinitions;
73     }
74
75         public static final int VALUE_NONE = 0;
76         public static final int VALUE_DESCRIPTION = 1;
77         public static final int VALUE_INDEXED_PROPS = 2;
78         public static final int VALUE_CONTAINER = 3;
79
80         private static final String generateTypeXSD = "xsd";
81         private static final String generateTypeYAML = "yaml";
82
83         private final static String nodeDir = System.getProperty("nodes.configuration.location");
84         private final static String edgeDir = System.getProperty("edges.configuration.location");
85         private static final String baseRoot = "aai-schema/";
86         private static final String baseAutoGenRoot = "aai-schema/";
87
88         private static final String root = baseRoot + "src/main/resources";
89         private static final String autoGenRoot = baseAutoGenRoot + "src/main/resources";
90
91         private static final String normalStartDir = "aai-core";
92         private static final String xsd_dir = root + "/" + RELEASE +"/aai_schema";
93
94         private static final String yaml_dir = (((System.getProperty("user.dir") != null) && (!System.getProperty("user.dir").contains(normalStartDir))) ? autoGenRoot : root) + "/" + RELEASE + "/aai_swagger_yaml";
95
96         /* These three strings are for yaml auto-generation from aai-common class*/
97
98         private static int swaggerSupportStartsVersion = 1; // minimum version to support swagger documentation
99
100
101         private static boolean validVersion(String versionToGen) {
102
103                 if ("ALL".equalsIgnoreCase(versionToGen)) {
104                         return true;
105                 }
106
107                 SchemaVersions schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
108                 for (SchemaVersion v : schemaVersions.getVersions()) {
109                 if (v.equals(versionToGen)) {
110                     return true;
111                 }
112             }
113
114             return false;
115         }
116
117         private static boolean versionSupportsSwagger( String version) {
118                 if (new Integer(version.substring(1)).intValue() >= swaggerSupportStartsVersion ) {
119                         return true;
120                 }
121                 return false;
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         public static void main(String[] args) throws IOException {
136                 String versionToGen = System.getProperty("gen_version").toLowerCase();
137                 String fileTypeToGen = System.getProperty("gen_type").toLowerCase();
138
139                 AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
140                                 "org.onap.aai.config",
141                                 "org.onap.aai.setup"
142                 );
143
144                 SchemaVersions schemaVersions = ctx.getBean(SchemaVersions.class);
145
146                 if ( fileTypeToGen == null ) {
147                         fileTypeToGen = generateTypeXSD;
148                 }
149
150                 if ( !fileTypeToGen.equals( generateTypeXSD ) && !fileTypeToGen.equals( generateTypeYAML )) {
151                         System.err.println("Invalid gen_type passed. " + fileTypeToGen);
152                         System.exit(1);
153                 }
154
155                 String responsesLabel = System.getProperty("yamlresponses_url");
156                 responsesUrl = responsesLabel;
157
158                 List<SchemaVersion> versionsToGen = new ArrayList<>();
159                 if ( versionToGen == null ) {
160                         System.err.println("Version is required, ie v<n> or ALL.");
161                         System.exit(1);
162                 }
163                 else if (!"ALL".equalsIgnoreCase(versionToGen) && !versionToGen.matches("v\\d+") && !validVersion(versionToGen)) {
164                         System.err.println("Invalid version passed. " + versionToGen);
165                         System.exit(1);
166                 }
167                 else if ("ALL".equalsIgnoreCase(versionToGen)) {
168                         versionsToGen = schemaVersions.getVersions();
169                         Collections.sort(versionsToGen);
170                         Collections.reverse(versionsToGen);
171                 } else {
172                         versionsToGen.add(new SchemaVersion(versionToGen));
173                 }
174
175                 //process file type System property
176                 fileTypeToGen = (fileTypeToGen == null ? generateTypeXSD : fileTypeToGen.toLowerCase());
177                 if ( !fileTypeToGen.equals( generateTypeXSD ) && !fileTypeToGen.equals( generateTypeYAML )) {
178                         System.err.println("Invalid gen_type passed. " + fileTypeToGen);
179                         System.exit(1);
180                 } else if ( fileTypeToGen.equals(generateTypeYAML) ) {
181                         if ( responsesUrl == null || responsesUrl.length() < 1
182                                         || responsesLabel == null || responsesLabel.length() < 1 ) {
183                                 System.err.println("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]("+responsesLabel+ ").\n";
187                         }
188                 }
189                 /*
190                  * TODO: Oxm Path is config driveb
191                  */
192                 String oxmPath;
193                 if(System.getProperty("user.dir") != null && !System.getProperty("user.dir").contains(normalStartDir)) {
194                         oxmPath = baseAutoGenRoot + nodeDir;
195                 }
196                 else {
197                         oxmPath = baseRoot + nodeDir;
198                 }
199
200                 String outfileName = null;
201                 File outfile;
202                 String nodesfileName = null;
203                 File nodesfile;
204                 String fileContent = null;
205                 String nodesContent = null;
206
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 = edgeDir + "DbEdgeRules_" + apiVersion + ".json";
217                         logger.debug("user.dir = "+System.getProperty("user.dir"));
218                         if(System.getProperty("user.dir") != null && !System.getProperty("user.dir").contains(normalStartDir)) {
219                                 fileName = baseAutoGenRoot + fileName;
220
221                         }
222                         else {
223                                 fileName = baseRoot + fileName;
224
225                         }
226                         edgeRuleFile = new File( fileName);
227 //                      Document doc = ni.getSchema(translateVersion(v));
228
229                         if ( fileTypeToGen.equals(generateTypeXSD) ) {
230                                 outfileName = xsd_dir + "/aai_schema_" + apiVersion + "." + generateTypeXSD;
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                                 e.printStackTrace();
242                                 System.exit(-1);
243                                 }
244                         } else if ( versionSupportsSwagger(apiVersion )) {
245                                 outfileName = yaml_dir + "/aai_swagger_" + apiVersion + "." + generateTypeYAML;
246                                 nodesfileName = yaml_dir + "/aai_swagger_" + apiVersion + "." + "nodes"+"."+generateTypeYAML;
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);
258                                 e.printStackTrace();
259                                 }
260                         } else {
261                                 continue;
262                         }
263                         outfile = new File(outfileName);
264                         File parentDir = outfile.getParentFile();
265                         if(! parentDir.exists())
266                               parentDir.mkdirs();
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                             try {
274                                 nodesfile.createNewFile();
275                             } catch (IOException e) {
276                                 logger.error( "Exception creating output file " + nodesfileName);
277                                 e.printStackTrace();
278                             }
279                         try {
280                                 Charset charset = Charset.forName("UTF-8");
281                                 Path path = Paths.get(nodesfileName);
282                                 nodesBW = Files.newBufferedWriter(path, charset);
283                                 nodesBW.write(nodesContent);
284                         } catch ( IOException e) {
285                                 logger.error( "Exception writing output file " + outfileName);
286                                 e.printStackTrace();
287                         } finally {
288                                 if ( nodesBW != null ) {
289                                         nodesBW.close();
290                                 }
291                         }
292                         }
293
294                     try {
295                         outfile.createNewFile();
296                     } catch (IOException e) {
297                         logger.error( "Exception creating output file " + outfileName);
298                         e.printStackTrace();
299                     }
300                     BufferedWriter bw = null;
301                 try {
302                         Charset charset = Charset.forName("UTF-8");
303                         Path path = Paths.get(outfileName);
304                         bw = Files.newBufferedWriter(path, charset);
305                         bw.write(fileContent);
306                 } catch ( IOException e) {
307                         logger.error( "Exception writing output file " + outfileName);
308                         e.printStackTrace();
309                 } finally {
310                         if ( bw != null ) {
311                                 bw.close();
312                         }
313                 }
314                         logger.debug( "GeneratedXSD successful, saved in " + outfileName);
315                 }
316
317         }
318
319 }
320