63318da329de9132de86e73bc7b09efb4fa57b63
[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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  */
22
23 package org.onap.aai.util;
24
25 import org.onap.aai.introspection.Version;
26 import org.onap.aai.util.genxsd.EdgeRuleSet;
27 import org.onap.aai.util.genxsd.HTMLfromOXM;
28 import org.onap.aai.util.genxsd.YAMLfromOXM;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 import java.io.BufferedWriter;
33 import java.io.File;
34 import java.io.IOException;
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 public class GenerateXsd {
42         
43         private static final Logger logger = LoggerFactory.getLogger("GenerateXsd.class");
44         protected static String apiVersion = null;
45         static String apiVersionFmt = null;
46         static boolean useAnnotationsInXsd = false;
47         static String responsesUrl = null;
48         static String responsesLabel = null;
49         static String jsonEdges = null;
50         static EdgeRuleSet edgeRuleSet = null;
51
52         static Map<String, String> generatedJavaType;
53         static Map<String, String> appliedPaths;
54
55         public static final int VALUE_NONE = 0;
56         public static final int VALUE_DESCRIPTION = 1;
57         public static final int VALUE_INDEXED_PROPS = 2;
58         public static final int VALUE_CONTAINER = 3;
59         
60         private static final String generateTypeXSD = "xsd";
61         private static final String generateTypeYAML = "yaml";
62         
63         private static final String root = "../aai-schema/src/main/resources";
64         private static final String autoGenRoot = "aai-schema/src/main/resources";
65         private static final String normalStartDir = "aai-core";
66         private static final String xsd_dir = root + "/aai_schema";
67         private static final String yaml_dir = (((System.getProperty("user.dir") != null) && (!System.getProperty("user.dir").contains(normalStartDir))) ? autoGenRoot : root) + "/aai_swagger_yaml";
68         
69         /* These three strings are for yaml auto-generation from aai-common class*/
70 //      private static final String alt_yaml_dir = autoGenRoot + "/aai_swagger_yaml";
71
72         private static int annotationsStartVersion = 9; // minimum version to support annotations in xsd
73         private static int swaggerSupportStartsVersion = 7; // minimum version to support swagger documentation
74         
75         private static boolean validVersion(String versionToGen) {
76                 
77                 if ("ALL".equalsIgnoreCase(versionToGen)) {
78                         return true;
79                 }
80                 
81                 for (Version v : Version.values()) {
82                 if (v.name().equals(versionToGen)) {
83                     return true;
84                 }
85             }
86
87             return false;
88         }
89         
90         private static boolean versionUsesAnnotations( String version) {
91                 if (new Integer(version.substring(1)).intValue() >= annotationsStartVersion ) {
92                         return true;
93                 }
94                 return false;
95         }
96         
97         private static boolean versionSupportsSwagger( String version) {
98                 if (new Integer(version.substring(1)).intValue() >= swaggerSupportStartsVersion ) {
99                         return true;
100                 }
101                 return false;
102         }
103         
104         public static String getAPIVersion() {
105                 return apiVersion;
106         }
107
108         public static String getYamlDir() {
109                 return yaml_dir;
110         }
111
112         public static String getResponsesUrl() {
113                 return responsesUrl;
114         }
115
116         public static void main(String[] args) throws IOException {
117                 String versionToGen = System.getProperty("gen_version").toLowerCase();
118                 String fileTypeToGen = System.getProperty("gen_type").toLowerCase();
119                 if ( fileTypeToGen == null ) {
120                         fileTypeToGen = generateTypeXSD;
121                 }
122                 
123                 if ( !fileTypeToGen.equals( generateTypeXSD ) && !fileTypeToGen.equals( generateTypeYAML )) {
124                         System.err.println("Invalid gen_type passed. " + fileTypeToGen);
125                         System.exit(1);
126                 }
127                 
128                 
129                 String responsesLabel = System.getProperty("yamlresponses_url");
130                 responsesUrl = responsesLabel;
131                 
132                 List<Version> versionsToGen = new ArrayList<>();
133                 if ( versionToGen == null ) {
134                         System.err.println("Version is required, ie v<n> or ALL.");
135                         System.exit(1);                 
136                 }
137                 else if (!"ALL".equalsIgnoreCase(versionToGen) && !versionToGen.matches("v\\d+") && !validVersion(versionToGen)) {
138                         System.err.println("Invalid version passed. " + versionToGen);
139                         System.exit(1);
140                 }
141                 else if ("ALL".equalsIgnoreCase(versionToGen)) {
142                         versionsToGen = Arrays.asList(Version.values());
143                         Collections.sort(versionsToGen);
144                         Collections.reverse(versionsToGen);
145                 } else {
146                         versionsToGen.add(Version.getVersion(versionToGen));
147                 }
148                 
149                 //process file type System property
150                 fileTypeToGen = (fileTypeToGen == null ? generateTypeXSD : fileTypeToGen.toLowerCase());
151                 if ( !fileTypeToGen.equals( generateTypeXSD ) && !fileTypeToGen.equals( generateTypeYAML )) {
152                         System.err.println("Invalid gen_type passed. " + fileTypeToGen);
153                         System.exit(1);
154                 } else if ( fileTypeToGen.equals(generateTypeYAML) ) {
155                         if ( responsesUrl == null || responsesUrl.length() < 1 
156                                         || responsesLabel == null || responsesLabel.length() < 1 ) {
157                                 System.err.println("generating swagger yaml file requires yamlresponses_url and yamlresponses_label properties" );
158                                 System.exit(1);
159                         } else {
160                                 responsesUrl = "description: "+ "Response codes found in [response codes]("+responsesLabel+ ").\n";
161                         }
162                 }
163                 String oxmPath;
164                 if(System.getProperty("user.dir") != null && !System.getProperty("user.dir").contains(normalStartDir)) {
165                         oxmPath = autoGenRoot + "/oxm/";
166                 }
167                 else {
168                         oxmPath = root + "/oxm/";
169                 }
170
171                 String outfileName;
172                 File outfile;
173                 String fileContent = null;
174                 
175                 for (Version v : versionsToGen) {
176                         apiVersion = v.toString();
177                         logger.debug("YAMLdir = "+yaml_dir);
178                         logger.debug("Generating " + apiVersion + " " + fileTypeToGen);
179                         File oxm_file = new File(oxmPath + "aai_oxm_" + apiVersion + ".xml");
180                         apiVersionFmt = "." + apiVersion + ".";
181                         generatedJavaType = new HashMap<String, String>();
182                         appliedPaths = new HashMap<String, String>();
183                         File edgeRuleFile = null;
184                         logger.debug("user.dir = "+System.getProperty("user.dir"));
185                         if(System.getProperty("user.dir") != null && !System.getProperty("user.dir").contains(normalStartDir)) {
186                                 edgeRuleFile = new File(normalStartDir + "/src/main/resources/dbedgerules/DbEdgeRules_" + apiVersion + ".json");
187                         }
188                         else {
189                                 edgeRuleFile = new File("src/main/resources/dbedgerules/DbEdgeRules_" + apiVersion + ".json");
190                         }
191                         
192                         if ( fileTypeToGen.equals(generateTypeXSD) ) {
193                                 useAnnotationsInXsd = versionUsesAnnotations(apiVersion);
194                                 outfileName = xsd_dir + "/aai_schema_" + apiVersion + "." + generateTypeXSD;
195                                 try {
196                                         HTMLfromOXM swagger = new HTMLfromOXM(oxm_file, v);
197                                         fileContent = swagger.process();
198                                 } catch(Exception e) {
199                                 logger.error( "Exception creating output file " + outfileName);
200                                 logger.error( e.getMessage());
201                                 e.printStackTrace();
202                                 }
203                         } else if ( versionSupportsSwagger(apiVersion )) {
204                                 outfileName = yaml_dir + "/aai_swagger_" + apiVersion + "." + generateTypeYAML;
205                                 try {
206                                         YAMLfromOXM swagger = new YAMLfromOXM(oxm_file, v, edgeRuleFile);
207                                         fileContent = swagger.process();
208                                 } catch(Exception e) {
209                                 logger.error( "Exception creating output file " + outfileName);
210                                 logger.error( e.getMessage());
211                                 e.printStackTrace();
212                                 }
213                         } else {
214                                 continue;
215                         }
216                         outfile = new File(outfileName);
217                         File parentDir = outfile.getParentFile();
218                         if(! parentDir.exists()) 
219                               parentDir.mkdirs();
220                 
221                     try {
222                         outfile.createNewFile();
223                     } catch (IOException e) {
224                         logger.error( "Exception creating output file " + outfileName);
225                         e.printStackTrace();
226                     }
227                     BufferedWriter bw = null;
228                 try {
229                         Charset charset = Charset.forName("UTF-8");
230                         Path path = Paths.get(outfileName);
231                         bw = Files.newBufferedWriter(path, charset);
232                         bw.write(fileContent);
233                 } catch ( IOException e) {
234                         logger.error( "Exception writing output file " + outfileName);
235                         e.printStackTrace();
236                 } finally {
237                         if ( bw != null ) {
238                                 bw.close();
239                         }
240                 }
241                         logger.debug( "GeneratedXSD successful, saved in " + outfileName);
242                 }
243                 
244         }
245 }