84f06064dda9668c2112aac35b23f329de8f6f8d
[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 = SpringContextAware.getBean(SchemaVersions.class);
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                                 } catch(Exception e) {
236                                 logger.error( "Exception creating output file " + outfileName);
237                                 logger.error( e.getMessage());
238                                 e.printStackTrace();
239                                 System.exit(-1);
240                                 }
241                         } else if ( versionSupportsSwagger(apiVersion )) {
242                                 outfileName = yaml_dir + "/aai_swagger_" + apiVersion + "." + generateTypeYAML;
243                                 nodesfileName = yaml_dir + "/aai_swagger_" + apiVersion + "." + "nodes"+"."+generateTypeYAML;
244                                 try {                                   
245                                         YAMLfromOXM swagger = (YAMLfromOXM) ctx.getBean(YAMLfromOXM.class);
246                                         swagger.setVersion(v);
247                                         fileContent = swagger.process();
248                                         Map combinedJavaTypes = swagger.getCombinedJavaTypes();
249                                         NodesYAMLfromOXM nodesSwagger = ctx.getBean(NodesYAMLfromOXM.class);
250                                         nodesSwagger.setVersion(v);
251                                         nodesSwagger.setCombinedJavaTypes(combinedJavaTypes);
252                                         nodesContent = nodesSwagger.process();
253                                 } catch(Exception e) {
254                                 logger.error( "Exception creating output file " + outfileName);
255                                 e.printStackTrace();
256                                 }
257                         } else {
258                                 continue;
259                         }
260                         outfile = new File(outfileName);
261                         File parentDir = outfile.getParentFile();
262                         if(! parentDir.exists()) 
263                               parentDir.mkdirs();
264                         if(nodesfileName != null) {
265                                 BufferedWriter nodesBW = null;
266                                 nodesfile = new File(nodesfileName);
267                                 parentDir = nodesfile.getParentFile();
268                                 if(! parentDir.exists()) 
269                                       parentDir.mkdirs();
270                             try {
271                                 nodesfile.createNewFile();
272                             } catch (IOException e) {
273                                 logger.error( "Exception creating output file " + nodesfileName);
274                                 e.printStackTrace();
275                             }
276                         try {
277                                 Charset charset = Charset.forName("UTF-8");
278                                 Path path = Paths.get(nodesfileName);
279                                 nodesBW = Files.newBufferedWriter(path, charset);
280                                 nodesBW.write(nodesContent);
281                         } catch ( IOException e) {
282                                 logger.error( "Exception writing output file " + outfileName);
283                                 e.printStackTrace();
284                         } finally {
285                                 if ( nodesBW != null ) {
286                                         nodesBW.close();
287                                 }
288                         }
289                         }
290                                         
291                     try {
292                         outfile.createNewFile();
293                     } catch (IOException e) {
294                         logger.error( "Exception creating output file " + outfileName);
295                         e.printStackTrace();
296                     }
297                     BufferedWriter bw = null;
298                 try {
299                         Charset charset = Charset.forName("UTF-8");
300                         Path path = Paths.get(outfileName);
301                         bw = Files.newBufferedWriter(path, charset);
302                         bw.write(fileContent);
303                 } catch ( IOException e) {
304                         logger.error( "Exception writing output file " + outfileName);
305                         e.printStackTrace();
306                 } finally {
307                         if ( bw != null ) {
308                                 bw.close();
309                         }
310                 }
311                         logger.debug( "GeneratedXSD successful, saved in " + outfileName);
312                 }
313                 
314         }
315
316 }
317
318