[AAI] Fix doc config files
[aai/aai-common.git] / aai-schema-abstraction / src / main / java / org / onap / aai / schemaif / oxm / OxmSchemaLoader.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2019 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2019 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.aai.schemaif.oxm;
22
23 import java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.HashMap;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.regex.Matcher;
30 import java.util.regex.Pattern;
31
32 import org.eclipse.persistence.dynamic.DynamicType;
33 import org.eclipse.persistence.internal.oxm.mappings.Descriptor;
34 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
35 import org.onap.aai.cl.eelf.LoggerFactory;
36 import org.onap.aai.nodes.NodeIngestor;
37 import org.onap.aai.schemaif.SchemaProviderException;
38 import org.onap.aai.schemaif.SchemaProviderMsgs;
39 import org.onap.aai.schemaif.definitions.VertexSchema;
40 import org.onap.aai.setup.SchemaVersion;
41 import org.onap.aai.setup.Translator;
42 import org.springframework.beans.factory.annotation.Autowired;
43 import org.springframework.stereotype.Component;
44
45 /**
46  * This class contains all of the logic for importing OXM model schemas from the available OXM
47  * schema files.
48  */
49 @Component
50 public class OxmSchemaLoader {
51
52     private static Translator translator;
53     private static NodeIngestor nodeIngestor;
54
55     private static Map<String, DynamicJAXBContext> versionContextMap = new ConcurrentHashMap<>();
56     private static Map<String, HashMap<String, DynamicType>> xmlElementLookup = new ConcurrentHashMap<>();
57     private static Map<String, HashMap<String, VertexSchema>> vertexLookup = new ConcurrentHashMap<>();
58
59     final static Pattern versionPattern = Pattern.compile("(?i)v(\\d*)");
60
61     private static org.onap.aai.cl.api.Logger logger =
62             LoggerFactory.getInstance().getLogger(OxmSchemaLoader.class.getName());
63
64     private OxmSchemaLoader() {}
65
66     /**
67      * This constructor presents an awkward marrying of Spring bean creation and static method use. This
68      * is technical debt that will need fixing.
69      *
70      * @param translator contains schema versions configuration
71      * @param nodeIngestor provides DynamicJAXBContext for the OXM version
72      */
73     @Autowired
74     public OxmSchemaLoader(Translator translator, NodeIngestor nodeIngestor) {
75         OxmSchemaLoader.translator = translator;
76         OxmSchemaLoader.nodeIngestor = nodeIngestor;
77     }
78
79     /**
80      * Finds all OXM model files
81      *
82      * @throws SchemaProviderException
83      * @throws IOException
84      *
85      */
86     public synchronized static void loadModels() throws SchemaProviderException {
87         if (logger.isDebugEnabled()) {
88             logger.debug("Loading OXM Models");
89         }
90
91         for (SchemaVersion oxmVersion : translator.getSchemaVersions().getVersions()) {
92             DynamicJAXBContext jaxbContext = nodeIngestor.getContextForVersion(oxmVersion);
93             if (jaxbContext != null) {
94                 loadModel(oxmVersion.toString(), jaxbContext);
95             }
96         }
97     }
98
99     private synchronized static void loadModel(String oxmVersion, DynamicJAXBContext jaxbContext) {
100         versionContextMap.put(oxmVersion, jaxbContext);
101         loadXmlLookupMap(oxmVersion, jaxbContext);
102         loadVertexLookupMap(oxmVersion, jaxbContext);
103         logger.info(SchemaProviderMsgs.LOADED_SCHEMA_FILE, oxmVersion);
104     }
105
106     /**
107      * Retrieves the JAXB context for the specified OXM model version.
108      *
109      * @param version - The OXM version that we want the JAXB context for.
110      *
111      * @return - A JAXB context derived from the OXM model schema.
112      *
113      * @throws SchemaProviderException
114      */
115     public static DynamicJAXBContext getContextForVersion(String version) throws SchemaProviderException {
116
117         // If we haven't already loaded in the available OXM models, then do so now.
118         if (versionContextMap == null || versionContextMap.isEmpty()) {
119             loadModels();
120         } else if (!versionContextMap.containsKey(version)) {
121             throw new SchemaProviderException("Error loading oxm model: " + version);
122         }
123
124         return versionContextMap.get(version);
125     }
126
127     public static String getLatestVersion() throws SchemaProviderException {
128
129         // If we haven't already loaded in the available OXM models, then do so now.
130         if (versionContextMap == null || versionContextMap.isEmpty()) {
131             loadModels();
132         }
133
134         // If there are still no models available, then there's not much we can do...
135         if (versionContextMap.isEmpty()) {
136             throw new SchemaProviderException("No available OXM schemas to get latest version for.");
137         }
138
139         // Iterate over the available model versions to determine which is the most
140         // recent.
141         Integer latestVersion = null;
142         String latestVersionStr = null;
143         for (String versionKey : versionContextMap.keySet()) {
144
145             Matcher matcher = versionPattern.matcher(versionKey);
146             if (matcher.find()) {
147
148                 int currentVersion = Integer.valueOf(matcher.group(1));
149
150                 if ((latestVersion == null) || (currentVersion > latestVersion)) {
151                     latestVersion = currentVersion;
152                     latestVersionStr = versionKey;
153                 }
154             }
155         }
156
157         return latestVersionStr;
158     }
159
160     private static void loadXmlLookupMap(String version, DynamicJAXBContext jaxbContext) {
161
162         @SuppressWarnings("rawtypes")
163         List<Descriptor> descriptorsList = jaxbContext.getXMLContext().getDescriptors();
164         HashMap<String, DynamicType> types = new HashMap<String, DynamicType>();
165
166         for (@SuppressWarnings("rawtypes")
167         Descriptor desc : descriptorsList) {
168
169             DynamicType entity = jaxbContext.getDynamicType(desc.getAlias());
170             String entityName = desc.getDefaultRootElement();
171             types.put(entityName, entity);
172         }
173         xmlElementLookup.put(version, types);
174     }
175     
176     private static void loadVertexLookupMap(String version, DynamicJAXBContext jaxbContext) {
177
178       @SuppressWarnings("rawtypes")
179       List<Descriptor> descriptorsList = jaxbContext.getXMLContext().getDescriptors();
180       HashMap<String, VertexSchema> vertexMap = new HashMap<String, VertexSchema>();
181
182       for (@SuppressWarnings("rawtypes")
183       Descriptor desc : descriptorsList) {
184         try {
185           FromOxmVertexSchema vs = new FromOxmVertexSchema();
186           vs.fromOxm(desc.getDefaultRootElement(), jaxbContext, getXmlLookupMap(version));
187           vertexMap.put(vs.getName(), vs);
188         } catch (SchemaProviderException e) {
189           continue;
190         }
191       }
192       vertexLookup.put(version, vertexMap);
193     }
194
195     /**
196      * Retrieves the list of all Loaded OXM versions.
197      *
198      * @return - A List of Strings of all loaded OXM versions.
199      *
200      * @throws SpikeException
201      */
202     public static List<String> getLoadedOXMVersions() throws SchemaProviderException {
203         // If we haven't already loaded in the available OXM models, then do so now.
204         if (versionContextMap == null || versionContextMap.isEmpty()) {
205             loadModels();
206         }
207         // If there are still no models available, then there's not much we can do...
208         if (versionContextMap.isEmpty()) {
209             logger.error(SchemaProviderMsgs.SCHEMA_LOAD_ERROR, "No available OXM schemas to get versions for.");
210             throw new SchemaProviderException("No available OXM schemas to get latest version for.");
211         }
212         List<String> versions = new ArrayList<String>();
213         for (String versionKey : versionContextMap.keySet()) {
214             Matcher matcher = versionPattern.matcher(versionKey);
215             if (matcher.find()) {
216                 versions.add("V" + matcher.group(1));
217             }
218         }
219         return versions;
220     }
221
222     public static HashMap<String, DynamicType> getXmlLookupMap(String version) {
223         return xmlElementLookup.get(version);
224     }
225
226     public static HashMap<String, VertexSchema> getVertexLookupForVersion(String version) throws SchemaProviderException {
227       // If we haven't already loaded in the available OXM models, then do so now.
228       if (vertexLookup == null || vertexLookup.isEmpty()) {
229           loadModels();
230       } else if (!vertexLookup.containsKey(version)) {
231           throw new SchemaProviderException("Error loading oxm model: " + version);
232       }
233       return vertexLookup.get(version);
234     }
235
236 }