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