2 * ============LICENSE_START=======================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
23 package org.onap.aai.nodes;
25 import com.google.common.base.CaseFormat;
27 import java.io.ByteArrayInputStream;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.nio.charset.StandardCharsets;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.List;
36 import java.util.regex.Matcher;
37 import java.util.regex.Pattern;
39 import javax.annotation.PostConstruct;
40 import javax.xml.XMLConstants;
41 import javax.xml.bind.JAXBException;
42 import javax.xml.parsers.DocumentBuilder;
43 import javax.xml.parsers.DocumentBuilderFactory;
44 import javax.xml.parsers.ParserConfigurationException;
46 import org.eclipse.persistence.jaxb.JAXBContextProperties;
47 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
48 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory;
49 import org.onap.aai.setup.ConfigTranslator;
50 import org.onap.aai.setup.SchemaVersion;
51 import org.onap.aai.setup.SchemaVersions;
52 import org.onap.aai.setup.Translator;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.springframework.beans.factory.annotation.Autowired;
56 import org.springframework.context.annotation.PropertySource;
57 import org.springframework.stereotype.Component;
58 import org.w3c.dom.Document;
59 import org.w3c.dom.Node;
60 import org.w3c.dom.NodeList;
61 import org.xml.sax.SAXException;
65 * NodeIngestor - ingests A&AI OXM files per given config, serves DynamicJAXBContext per version
67 @PropertySource(value = "classpath:schema-ingest.properties", ignoreResourceNotFound = true)
68 @PropertySource(value = "file:${schema.ingest.file}", ignoreResourceNotFound = true)
69 public class NodeIngestor {
71 private static final Logger LOGGER = LoggerFactory.getLogger(NodeIngestor.class);
72 private static final Pattern classNamePattern = Pattern.compile("\\.(v\\d+)\\.");
73 private Map<SchemaVersion, DynamicJAXBContext> versionContextMap = new HashMap<>();
74 private Map<SchemaVersion, Set<String>> typesPerVersion = new HashMap<>();
75 private Map<SchemaVersion, Document> schemaPerVersion = new HashMap<>();
76 private String localSchema;
77 private SchemaVersions schemaVersions;
78 private Set<Translator> translators;
80 private CaseFormatStore caseFormatStore;
81 // TODO : See if you can get rid of InputStream resets
84 * Instantiates the NodeIngestor bean.
86 * @param translatorSet
90 public NodeIngestor(Set<Translator> translatorSet) {
91 this.translators = translatorSet;
92 this.caseFormatStore = new CaseFormatStore();
96 public void initialize() {
98 for (Translator translator : translators) {
100 LOGGER.debug("Processing the translator");
101 translateAll(translator);
103 } catch (Exception e) {
104 LOGGER.error("Error while Processing the translator" + e.getMessage());
105 throw new ExceptionInInitializerError("NodeIngestor could not ingest schema");
108 if (versionContextMap.isEmpty() || schemaPerVersion.isEmpty() || typesPerVersion.isEmpty()) {
109 throw new ExceptionInInitializerError("NodeIngestor could not ingest schema");
113 private void translateAll(Translator translator) throws ExceptionInInitializerError {
114 if (translator instanceof ConfigTranslator) {
115 this.localSchema = "true";
118 Boolean retrieveLocalSchema = Boolean.parseBoolean(this.localSchema);
120 * Set this to default schemaVersion
122 this.schemaVersions = translator.getSchemaVersions();
123 List<SchemaVersion> schemaVersionList = translator.getSchemaVersions().getVersions();
126 for (SchemaVersion version : schemaVersionList) {
127 LOGGER.debug("Version being processed" + version);
128 List<InputStream> inputStreams = retrieveOXM(version, translator);
129 LOGGER.debug("Retrieved OXMs from SchemaService");
131 * IOUtils.copy and copy the inputstream
133 if (inputStreams.isEmpty()) {
137 final DynamicJAXBContext ctx = ingest(inputStreams);
138 versionContextMap.put(version, ctx);
139 setAllTypesAndProperties(version, inputStreams);
140 schemaPerVersion.put(version, createCombinedSchema(inputStreams, version, retrieveLocalSchema));
142 } catch (JAXBException | ParserConfigurationException | SAXException | IOException e) {
143 throw new ExceptionInInitializerError(e);
148 * Ingests the given OXM files into DynamicJAXBContext
150 * @param inputStreams - inputStrean of oxms from SchemaService to be ingested
152 * @return DynamicJAXBContext including schema information from all given files
154 * @throws JAXBException if there's an error creating the DynamicJAXBContext
156 private DynamicJAXBContext ingest(List<InputStream> inputStreams) throws JAXBException {
157 Map<String, Object> properties = new HashMap<>();
158 properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, inputStreams);
159 LOGGER.debug("Ingested the InputStream");
160 return DynamicJAXBContextFactory.createContextFromOXM(this.getClass().getClassLoader(), properties);
163 private void setAllTypesAndProperties(SchemaVersion version, List<InputStream> inputStreams)
164 throws ParserConfigurationException, IOException, SAXException {
165 Set<String> types = new HashSet<>();
166 final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
167 docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
168 docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
169 docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
170 final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
172 for (InputStream inputStream : inputStreams) {
175 final Document doc = docBuilder.parse(inputStream);
176 final NodeList list = doc.getElementsByTagName("java-type");
177 getAllNodeTypes(list, types);
178 caseFormatStore.parse(doc);
181 LOGGER.debug("Types size {}", types.size());
182 typesPerVersion.put(version, types);
185 private void getAllNodeTypes(NodeList list, Set<String> types) {
187 for (int i = 0; i < list.getLength(); i++) {
188 String type = list.item(i).getAttributes().getNamedItem("name").getNodeValue();
189 types.add(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, type));
193 private Document createCombinedSchema(List<InputStream> inputStreams, SchemaVersion version, boolean localSchema)
194 throws ParserConfigurationException, SAXException, IOException {
196 return createCombinedSchema(inputStreams, version);
199 InputStream inputStream = inputStreams.get(0);
201 final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
202 docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
203 docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
204 docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
205 DocumentBuilder masterDocBuilder = docFactory.newDocumentBuilder();
206 return masterDocBuilder.parse(inputStream);
209 private Document createCombinedSchema(List<InputStream> inputStreams, SchemaVersion version)
210 throws ParserConfigurationException, SAXException, IOException {
211 final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
212 docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
213 docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
214 docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
215 final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
216 DocumentBuilder masterDocBuilder = docFactory.newDocumentBuilder();
217 Document combinedDoc = masterDocBuilder.parse(getShell(version));
218 NodeList masterList = combinedDoc.getElementsByTagName("java-types");
219 Node javaTypesContainer = masterList.getLength() == 0 ? combinedDoc.getDocumentElement() : masterList.item(0);
221 for (InputStream inputStream : inputStreams) {
223 final Document doc = docBuilder.parse(inputStream);
224 final NodeList list = doc.getElementsByTagName("java-type");
225 for (int i = 0; i < list.getLength(); i++) {
226 Node copy = combinedDoc.importNode(list.item(i), true);
227 javaTypesContainer.appendChild(copy);
234 * Gets the DynamicJAXBContext for the given version
236 * @param v - schema version to retrieve the context
237 * @return DynamicJAXBContext
239 public DynamicJAXBContext getContextForVersion(SchemaVersion v) {
240 return versionContextMap.get(v);
244 * Determines if the given version contains the given node type
246 * @param nodeType - node type to check, must be in lower hyphen form (ie "type-name")
247 * @param v - schema version to check against
250 public boolean hasNodeType(String nodeType, SchemaVersion v) {
251 return typesPerVersion.get(v).contains(nodeType);
254 public Set<String> getObjectsInVersion(SchemaVersion v) {
255 return typesPerVersion.get(v);
259 * Determines if the given version contains the given node type
261 * @param v - Schemaversion to retrieve the schema
264 public Document getSchema(SchemaVersion v) {
265 return schemaPerVersion.get(v);
268 public SchemaVersion getVersionFromClassName(String classname) {
269 Matcher m = classNamePattern.matcher(classname);
271 String version = m.group(1);
272 return new SchemaVersion(version);
274 return this.schemaVersions.getDefaultVersion();
278 private List<InputStream> retrieveOXM(SchemaVersion version, Translator translator) throws IOException {
280 * Call Schema MS to get versions using RestTemplate or Local
282 return translator.getVersionNodeStream(version);
286 private InputStream getShell(SchemaVersion v) {
287 String source = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
288 + "<xml-bindings xmlns=\"http://www.eclipse.org/eclipselink/xsds/persistence/oxm\" package-name=\"inventory.aai.onap.org."
289 + v.toString().toLowerCase() + "\" xml-mapping-metadata-complete=\"true\">\n"
290 + " <xml-schema element-form-default=\"QUALIFIED\">\n"
291 + " <xml-ns namespace-uri=\"http://org.onap.aai.inventory/" + v.toString().toLowerCase() + "\" />\n"
292 + " </xml-schema>\n" + " <java-types>\n" + " </java-types>\n" + "</xml-bindings>";
293 return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
296 public CaseFormatStore getCaseFormatStore() {
297 return caseFormatStore;