Merge "Optimize the areas where its creating extra memory"
[aai/aai-common.git] / aai-schema-ingest / src / main / java / org / onap / aai / nodes / NodeIngestor.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright © 2018 IBM.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *    http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.aai.nodes;
24
25 import com.att.eelf.configuration.EELFLogger;
26 import com.att.eelf.configuration.EELFManager;
27 import com.google.common.base.CaseFormat;
28 import org.eclipse.persistence.jaxb.JAXBContextProperties;
29 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
30 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory;
31 import org.onap.aai.setup.ConfigTranslator;
32 import org.onap.aai.setup.SchemaVersion;
33 import org.onap.aai.setup.SchemaVersions;
34 import org.onap.aai.setup.Translator;
35 import org.springframework.beans.factory.annotation.Autowired;
36 import org.springframework.context.annotation.PropertySource;
37 import org.springframework.stereotype.Component;
38 import org.w3c.dom.Document;
39 import org.w3c.dom.Node;
40 import org.w3c.dom.NodeList;
41 import org.xml.sax.SAXException;
42
43 import javax.annotation.PostConstruct;
44 import javax.xml.XMLConstants;
45 import javax.xml.bind.JAXBException;
46 import javax.xml.parsers.DocumentBuilder;
47 import javax.xml.parsers.DocumentBuilderFactory;
48 import javax.xml.parsers.ParserConfigurationException;
49 import java.io.*;
50 import java.nio.charset.StandardCharsets;
51 import java.util.*;
52 import java.util.regex.Matcher;
53 import java.util.regex.Pattern;
54
55 @Component
56 /*
57   NodeIngestor - ingests A&AI OXM files per given config, serves DynamicJAXBContext per version
58  */
59 @PropertySource(value = "classpath:schema-ingest.properties", ignoreResourceNotFound=true)
60 @PropertySource(value = "file:${schema.ingest.file}", ignoreResourceNotFound=true)
61 public class NodeIngestor {
62
63     private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(NodeIngestor.class);
64     private static final Pattern classNamePattern = Pattern.compile("\\.(v\\d+)\\.");
65     private Map<SchemaVersion, DynamicJAXBContext> versionContextMap = new HashMap<>();
66     private Map<SchemaVersion, Set<String>> typesPerVersion = new HashMap<>();
67     private Map<SchemaVersion, Document> schemaPerVersion = new HashMap<>();
68     private String localSchema;
69     private SchemaVersions schemaVersions;
70     private Set<Translator> translators;
71
72     private CaseFormatStore caseFormatStore;
73     //TODO : See if you can get rid of InputStream resets
74
75     /**
76      * Instantiates the NodeIngestor bean.
77      * @param translatorSet
78      */
79
80      @Autowired
81     public NodeIngestor(Set<Translator> translatorSet) {
82         this.translators = translatorSet;
83         this.caseFormatStore = new CaseFormatStore();
84     }
85
86     @PostConstruct
87     public void initialize() {
88
89         for (Translator translator : translators) {
90             try {
91                 LOGGER.debug("Processing the translator");
92                 translateAll(translator);
93
94             } catch (Exception e) {
95                 LOGGER.error("Error while Processing the translator" + e.getMessage());
96                 throw new ExceptionInInitializerError("NodeIngestor could not ingest schema");
97             }
98         }
99         if (versionContextMap.isEmpty() || schemaPerVersion.isEmpty() || typesPerVersion.isEmpty()) {
100             throw new ExceptionInInitializerError("NodeIngestor could not ingest schema");
101         }
102     }
103
104     private void translateAll(Translator translator) throws ExceptionInInitializerError {
105         if (translator instanceof ConfigTranslator) {
106             this.localSchema = "true";
107         }
108
109             Boolean retrieveLocalSchema = Boolean.parseBoolean(this.localSchema);
110         /*
111          * Set this to default schemaVersion
112          */
113         this.schemaVersions = translator.getSchemaVersions();
114         List<SchemaVersion> schemaVersionList = translator.getSchemaVersions().getVersions();
115
116         try {
117             for (SchemaVersion version : schemaVersionList) {
118                 LOGGER.debug("Version being processed" + version);
119                 List<InputStream> inputStreams = retrieveOXM(version, translator);
120                 LOGGER.debug("Retrieved OXMs from SchemaService");
121                 /*
122                 IOUtils.copy and copy the inputstream
123                 */
124                 if (inputStreams.isEmpty()) {
125                     continue;
126                 }
127
128                 final DynamicJAXBContext ctx = ingest(inputStreams);
129                 versionContextMap.put(version, ctx);
130                 setAllTypesAndProperties(version, inputStreams);
131                 schemaPerVersion.put(version, createCombinedSchema(inputStreams, version, retrieveLocalSchema));
132             }
133         } catch (JAXBException | ParserConfigurationException | SAXException | IOException e) {
134             throw new ExceptionInInitializerError(e);
135         }
136     }
137
138     /**
139      * Ingests the given OXM files into DynamicJAXBContext
140      *
141      * @param inputStreams - inputStrean of oxms from SchemaService to be ingested
142      *
143      * @return DynamicJAXBContext including schema information from all given files
144      *
145      * @throws JAXBException if there's an error creating the DynamicJAXBContext
146      */
147     private DynamicJAXBContext ingest(List<InputStream> inputStreams) throws JAXBException {
148         Map<String, Object> properties = new HashMap<>();
149         properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, inputStreams);
150         LOGGER.debug("Ingested the InputStream");
151         return DynamicJAXBContextFactory.createContextFromOXM(this.getClass().getClassLoader(), properties);
152     }
153
154     private void setAllTypesAndProperties(SchemaVersion version, List<InputStream> inputStreams) throws ParserConfigurationException, IOException, SAXException {
155         Set<String> types = new HashSet<>();
156         final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
157         docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
158         final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
159
160         for (InputStream inputStream : inputStreams) {
161             //TODO Change this
162             inputStream.reset();
163             final Document doc = docBuilder.parse(inputStream);
164             final NodeList list = doc.getElementsByTagName("java-type");
165             getAllNodeTypes(list, types);
166             caseFormatStore.parse(doc);
167         }
168
169         LOGGER.debug("Types size {}", types.size());
170         typesPerVersion.put(version, types);
171     }
172
173     private void getAllNodeTypes(NodeList list, Set<String> types){
174
175         for (int i = 0; i < list.getLength(); i++) {
176             String type = list.item(i).getAttributes().getNamedItem("name").getNodeValue();
177             types.add(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, type));
178         }
179     }
180
181     private Document createCombinedSchema(List<InputStream> inputStreams, SchemaVersion version, boolean localSchema) throws ParserConfigurationException, SAXException, IOException {
182         if (localSchema) {
183             return createCombinedSchema(inputStreams, version);
184         }
185
186         InputStream inputStream = inputStreams.get(0);
187         inputStream.reset();
188         final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
189         docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
190         DocumentBuilder masterDocBuilder = docFactory.newDocumentBuilder();
191         return masterDocBuilder.parse(inputStream);
192     }
193
194     private Document createCombinedSchema(List<InputStream> inputStreams, SchemaVersion version) throws ParserConfigurationException, SAXException, IOException {
195         final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
196         docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
197         final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
198         DocumentBuilder masterDocBuilder = docFactory.newDocumentBuilder();
199         Document combinedDoc = masterDocBuilder.parse(getShell(version));
200         NodeList masterList = combinedDoc.getElementsByTagName("java-types");
201         Node javaTypesContainer = masterList.getLength() == 0 ? combinedDoc.getDocumentElement() : masterList.item(0);
202
203         for (InputStream inputStream : inputStreams) {
204             inputStream.reset();
205             final Document doc = docBuilder.parse(inputStream);
206             final NodeList list = doc.getElementsByTagName("java-type");
207             for (int i = 0; i < list.getLength(); i++) {
208                 Node copy = combinedDoc.importNode(list.item(i), true);
209                 javaTypesContainer.appendChild(copy);
210             }
211         }
212         return combinedDoc;
213     }
214
215     /**
216      * Gets the DynamicJAXBContext for the given version
217      *
218      * @param v - schema version to retrieve the context
219      * @return DynamicJAXBContext
220      */
221     public DynamicJAXBContext getContextForVersion(SchemaVersion v) {
222         return versionContextMap.get(v);
223     }
224
225     /**
226      * Determines if the given version contains the given node type
227      *
228      * @param nodeType - node type to check, must be in lower hyphen form (ie "type-name")
229      * @param v - schema version to check against
230      * @return boolean
231      */
232     public boolean hasNodeType(String nodeType, SchemaVersion v) {
233         return typesPerVersion.get(v).contains(nodeType);
234     }
235
236     public Set<String> getObjectsInVersion(SchemaVersion v) {
237         return typesPerVersion.get(v);
238     }
239
240     /**
241      * Determines if the given version contains the given node type
242      *
243      * @param v - Schemaversion to retrieve the schema
244      * @return Document
245      */
246     public Document getSchema(SchemaVersion v) {
247         return schemaPerVersion.get(v);
248     }
249
250
251     public SchemaVersion getVersionFromClassName(String classname) {
252         Matcher m = classNamePattern.matcher(classname);
253         if (m.find()) {
254             String version = m.group(1);
255             return new SchemaVersion(version);
256         } else {
257             return this.schemaVersions.getDefaultVersion();
258         }
259     }
260
261     private List<InputStream> retrieveOXM(SchemaVersion version, Translator translator) throws IOException {
262             /*
263             Call Schema MS to get versions using RestTemplate or Local
264              */
265         return translator.getVersionNodeStream(version);
266
267     }
268
269     private InputStream getShell(SchemaVersion v) {
270         String source = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
271             "<xml-bindings xmlns=\"http://www.eclipse.org/eclipselink/xsds/persistence/oxm\" package-name=\"inventory.aai.onap.org." + v.toString().toLowerCase() + "\" xml-mapping-metadata-complete=\"true\">\n" +
272             "   <xml-schema element-form-default=\"QUALIFIED\">\n" +
273             "           <xml-ns namespace-uri=\"http://org.onap.aai.inventory/" + v.toString().toLowerCase() + "\" />\n" +
274             "   </xml-schema>\n" +
275             "   <java-types>\n" +
276             "   </java-types>\n" +
277             "</xml-bindings>";
278         return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
279     }
280
281     public CaseFormatStore getCaseFormatStore(){
282         return caseFormatStore;
283     }
284 }