Update schema service to fail to start
[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     Map<SchemaVersion, List<String>> filesToIngest;
66     private Map<SchemaVersion, DynamicJAXBContext> versionContextMap = new TreeMap<>();
67     private Map<SchemaVersion, Set<String>> typesPerVersion = new TreeMap<>();
68     private Map<SchemaVersion, Document> schemaPerVersion = new TreeMap<>();
69     private String localSchema;
70     private SchemaVersions schemaVersions;
71     private Set<Translator> translators;
72     
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     }
84
85     @PostConstruct
86     public void initialize() {
87
88         for (Translator translator : translators) {
89             try {
90                 LOGGER.debug("Processing the translator");
91                 translateAll(translator);
92
93             } catch (Exception e) {
94                 LOGGER.error("Error while Processing the translator" + e.getMessage());
95                 throw new ExceptionInInitializerError("NodeIngestor could not ingest schema");
96             }
97         }
98         if (versionContextMap.isEmpty() || schemaPerVersion.isEmpty() || typesPerVersion.isEmpty()) {
99             throw new ExceptionInInitializerError("NodeIngestor could not ingest schema");
100         }
101     }
102
103     private void translateAll(Translator translator) throws ExceptionInInitializerError {
104         if (translator instanceof ConfigTranslator) {
105             this.localSchema = "true";
106         }
107
108             Boolean retrieveLocalSchema = Boolean.parseBoolean(this.localSchema);
109         /*
110          * Set this to default schemaVersion
111          */
112         this.schemaVersions = translator.getSchemaVersions();
113         List<SchemaVersion> schemaVersionList = translator.getSchemaVersions().getVersions();
114
115         try {
116             for (SchemaVersion version : schemaVersionList) {
117                 LOGGER.debug("Version being processed" + version);
118                 List<InputStream> inputStreams = retrieveOXM(version, translator);
119                 LOGGER.debug("Retrieved OXMs from SchemaService");
120                 /*
121                 IOUtils.copy and copy the inputstream
122                 */
123                 if (inputStreams.isEmpty()) {
124                     continue;
125                 }
126
127                 final DynamicJAXBContext ctx = ingest(inputStreams);
128                 versionContextMap.put(version, ctx);
129                 typesPerVersion.put(version, getAllNodeTypes(inputStreams));
130                 schemaPerVersion.put(version, createCombinedSchema(inputStreams, version, retrieveLocalSchema));
131             }
132         } catch (JAXBException | ParserConfigurationException | SAXException | IOException e) {
133             throw new ExceptionInInitializerError(e);
134         }
135     }
136
137     /**
138      * Ingests the given OXM files into DynamicJAXBContext
139      *
140      * @param inputStreams - inputStrean of oxms from SchemaService to be ingested
141      *
142      * @return DynamicJAXBContext including schema information from all given files
143      *
144      * @throws JAXBException if there's an error creating the DynamicJAXBContext
145      */
146     private DynamicJAXBContext ingest(List<InputStream> inputStreams) throws JAXBException {
147         Map<String, Object> properties = new HashMap<>();
148         properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, inputStreams);
149         LOGGER.debug("Ingested the InputStream");
150         return DynamicJAXBContextFactory.createContextFromOXM(this.getClass().getClassLoader(), properties);
151     }
152
153     private Set<String> getAllNodeTypes(List<InputStream> inputStreams) throws ParserConfigurationException, SAXException, IOException {
154         //Reset the InputStream to reset the offset to inital position
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
166             for (int i = 0; i < list.getLength(); i++) {
167                 String type = list.item(i).getAttributes().getNamedItem("name").getNodeValue();
168                 types.add(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, type));
169             }
170         }
171
172         LOGGER.debug("Types size" + types.size());
173         return types;
174     }
175
176     private Document createCombinedSchema(List<InputStream> inputStreams, SchemaVersion version, boolean localSchema) throws ParserConfigurationException, SAXException, IOException {
177         if (localSchema) {
178             return createCombinedSchema(inputStreams, version);
179         }
180
181         InputStream inputStream = inputStreams.get(0);
182         inputStream.reset();
183         final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
184         docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
185         DocumentBuilder masterDocBuilder = docFactory.newDocumentBuilder();
186         return masterDocBuilder.parse(inputStream);
187     }
188
189     private Document createCombinedSchema(List<InputStream> inputStreams, SchemaVersion version) throws ParserConfigurationException, SAXException, IOException {
190         final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
191         docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
192         final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
193         DocumentBuilder masterDocBuilder = docFactory.newDocumentBuilder();
194         Document combinedDoc = masterDocBuilder.parse(getShell(version));
195         NodeList masterList = combinedDoc.getElementsByTagName("java-types");
196         Node javaTypesContainer = masterList.getLength() == 0 ? combinedDoc.getDocumentElement() : masterList.item(0);
197
198         for (InputStream inputStream : inputStreams) {
199             inputStream.reset();
200             final Document doc = docBuilder.parse(inputStream);
201             final NodeList list = doc.getElementsByTagName("java-type");
202             for (int i = 0; i < list.getLength(); i++) {
203                 Node copy = combinedDoc.importNode(list.item(i), true);
204                 javaTypesContainer.appendChild(copy);
205             }
206         }
207         return combinedDoc;
208     }
209
210     /**
211      * Gets the DynamicJAXBContext for the given version
212      *
213      * @param v - schema version to retrieve the context
214      * @return DynamicJAXBContext
215      */
216     public DynamicJAXBContext getContextForVersion(SchemaVersion v) {
217         return versionContextMap.get(v);
218     }
219
220     /**
221      * Determines if the given version contains the given node type
222      *
223      * @param nodeType - node type to check, must be in lower hyphen form (ie "type-name")
224      * @param v - schema version to check against
225      * @return boolean
226      */
227     public boolean hasNodeType(String nodeType, SchemaVersion v) {
228         return typesPerVersion.get(v).contains(nodeType);
229     }
230
231     public Set<String> getObjectsInVersion(SchemaVersion v) {
232         return typesPerVersion.get(v);
233     }
234
235     /**
236      * Determines if the given version contains the given node type
237      *
238      * @param v - Schemaversion to retrieve the schema
239      * @return Document
240      */
241     public Document getSchema(SchemaVersion v) {
242         return schemaPerVersion.get(v);
243     }
244
245
246     public SchemaVersion getVersionFromClassName(String classname) {
247         Matcher m = classNamePattern.matcher(classname);
248         if (m.find()) {
249             String version = m.group(1);
250             return new SchemaVersion(version);
251         } else {
252             return this.schemaVersions.getDefaultVersion();
253         }
254     }
255
256     private List<InputStream> retrieveOXM(SchemaVersion version, Translator translator) throws IOException {
257             /*
258             Call Schema MS to get versions using RestTemplate or Local
259              */
260         return translator.getVersionNodeStream(version);
261
262     }
263
264     private InputStream getShell(SchemaVersion v) {
265         String source = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
266             "<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" +
267             "   <xml-schema element-form-default=\"QUALIFIED\">\n" +
268             "           <xml-ns namespace-uri=\"http://org.onap.aai.inventory/" + v.toString().toLowerCase() + "\" />\n" +
269             "   </xml-schema>\n" +
270             "   <java-types>\n" +
271             "   </java-types>\n" +
272             "</xml-bindings>";
273         return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
274     }
275 }