Changes for checkstyle 8.32
[policy/apex-pdp.git] / model / basic-model / src / main / java / org / onap / policy / apex / model / basicmodel / handling / ApexSchemaGenerator.java
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  * 
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  * 
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * 
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.model.basicmodel.handling;
22
23 import java.io.File;
24 import java.io.IOException;
25 import java.io.PrintStream;
26 import java.io.StringWriter;
27 import javax.xml.bind.JAXBContext;
28 import javax.xml.bind.JAXBException;
29 import javax.xml.bind.SchemaOutputResolver;
30 import javax.xml.transform.Result;
31 import javax.xml.transform.stream.StreamResult;
32 import org.slf4j.ext.XLogger;
33 import org.slf4j.ext.XLoggerFactory;
34
35 /**
36  * This class generates the XML model schema from the given Apex concept classes.
37  *
38  * @author Liam Fallon (liam.fallon@ericsson.com)
39  */
40 public class ApexSchemaGenerator {
41     // Get a reference to the logger
42     private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexSchemaGenerator.class);
43
44     /**
45      * A Main method to allow schema generation from the command line or from maven or scripts.
46      *
47      * @param args the command line arguments, usage is {@code ApexSchemaGenerator apex-root-class [schema-file-name]}
48      */
49     public static void main(final String[] args) {
50         PrintStream printStream = null;
51
52         if (args.length == 1) {
53             printStream = System.out;
54         } else if (args.length == 2) {
55             final File schemaFile = new File(args[1]);
56
57             try {
58                 schemaFile.getParentFile().mkdirs();
59                 printStream = new PrintStream(schemaFile);
60             } catch (final Exception e) {
61                 LOGGER.error("error on Apex schema output", e);
62                 return;
63             }
64         } else {
65             LOGGER.error("usage: ApexSchemaGenerator apex-root-class [schema-file-name]");
66             return;
67         }
68
69         // Get the schema
70         final String schema = new ApexSchemaGenerator().generate(args[0]);
71
72         // Output the schema
73         printStream.println(schema);
74
75         printStream.close();
76     }
77
78     /**
79      * Generates the XML schema (XSD) for the Apex model described using JAXB annotations.
80      *
81      * @param rootClassName the name of the root class for schema generation
82      * @return The schema
83      */
84     public String generate(final String rootClassName) {
85         JAXBContext jaxbContext;
86         try {
87             jaxbContext = JAXBContext.newInstance(Class.forName(rootClassName));
88         } catch (final ClassNotFoundException e) {
89             LOGGER.error("could not create JAXB context, root class " + rootClassName + " not found", e);
90             return null;
91         } catch (final JAXBException e) {
92             LOGGER.error("could not create JAXB context", e);
93             return null;
94         }
95
96         final ApexSchemaOutputResolver sor = new ApexSchemaOutputResolver();
97         try {
98             jaxbContext.generateSchema(sor);
99         } catch (final IOException e) {
100             LOGGER.error("error generating the Apex schema (XSD) file", e);
101             return null;
102         }
103
104         String schemaString = sor.getSchema();
105         schemaString = fixForUnqualifiedBug(schemaString);
106
107         return schemaString;
108     }
109
110     /**
111      * There is a bug in schema generation that does not specify the elements from Java Maps as being unqualified. This
112      * method "hacks" those elements in the schema to fix this, the elements being {@code entry}, {@code key}, and
113      * {@code value}
114      *
115      * @param schemaString The schema in which elements should be fixed
116      * @return the string
117      */
118     private String fixForUnqualifiedBug(final String schemaString) {
119         // Fix the "entry" element
120         String newSchemaString = schemaString.replaceAll(
121                         "<xs:element name=\"entry\" minOccurs=\"0\" maxOccurs=\"unbounded\">",
122                         "<xs:element name=\"entry\" minOccurs=\"0\" maxOccurs=\"unbounded\" form=\"unqualified\">");
123
124         // Fix the "key" element
125         newSchemaString = newSchemaString.replaceAll("<xs:element name=\"key\"",
126                         "<xs:element name=\"key\" form=\"unqualified\"");
127
128         // Fix the "value" element
129         newSchemaString = newSchemaString.replaceAll("<xs:element name=\"value\"",
130                         "<xs:element name=\"value\" form=\"unqualified\"");
131
132         return newSchemaString;
133     }
134
135     /**
136      * This inner class is used to receive the output of schema generation from the JAXB schema generator.
137      */
138     private class ApexSchemaOutputResolver extends SchemaOutputResolver {
139         private final StringWriter stringWriter = new StringWriter();
140
141         /**
142          * {@inheritDoc}.
143          */
144         @Override
145         public Result createOutput(final String namespaceUri, final String suggestedFileName) throws IOException {
146             final StreamResult result = new StreamResult(stringWriter);
147             result.setSystemId(suggestedFileName);
148             return result;
149         }
150
151         /**
152          * Get the schema from the string writer.
153          *
154          * @return the schema generated by JAXB
155          */
156         public String getSchema() {
157             return stringWriter.toString();
158         }
159     }
160 }