Convert Sparky to Spring-Boot
[aai/sparky-be.git] / sparkybe-onap-service / src / main / java / org / onap / aai / sparky / config / oxm / OxmModelLoader.java
1 /**
2  * ============LICENSE_START===================================================
3  * SPARKY (AAI UI service)
4  * ============================================================================
5  * Copyright © 2017 AT&T Intellectual Property.
6  * Copyright © 2017 Amdocs
7  * All rights reserved.
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  * ECOMP and OpenECOMP are trademarks
23  * and service marks of AT&T Intellectual Property.
24  */
25 package org.onap.aai.sparky.config.oxm;
26
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.util.HashMap;
30 import java.util.HashSet;
31 import java.util.Map;
32 import java.util.Set;
33 import java.util.regex.Matcher;
34 import java.util.regex.Pattern;
35
36 import org.eclipse.persistence.jaxb.JAXBContextProperties;
37 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
38 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory;
39 import org.onap.aai.cl.api.Logger;
40 import org.onap.aai.cl.eelf.LoggerFactory;
41 import org.onap.aai.sparky.logging.AaiUiMsgs;
42 import org.springframework.core.io.Resource;
43 import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
44 import org.springframework.core.io.support.ResourcePatternResolver;
45
46 public class OxmModelLoader {
47   
48   private static final Logger LOG = LoggerFactory.getInstance().getLogger(OxmModelLoader.class);
49   
50   /*
51    * The intent of this parameter is to be able to programmatically over-ride the latest AAI schema
52    * version discovered from the aai-schema jar file. This property is optional, but if set on the
53    * bean or by another class in the system, then it will override the spec version that is loaded.
54    * 
55    * If the latestVersionOverride is greater than 0 then it will set the latest version to the
56    * specified version, and that stream will be returned if available.
57    */
58
59   protected int oxmApiVersionOverride;
60   protected Set<OxmModelProcessor> processors;
61   private int latestVersionNum = 0;
62   
63   private final static Pattern p = Pattern.compile("aai_oxm_(v)(.*).xml");
64   
65   public OxmModelLoader() {
66     this(-1, new HashSet<OxmModelProcessor>());
67   }
68   
69   public OxmModelLoader(int apiVersionOverride,Set<OxmModelProcessor> oxmModelProcessors) {
70     this.oxmApiVersionOverride = apiVersionOverride;
71     this.processors = oxmModelProcessors;
72   }
73   
74   protected synchronized Map<Integer, InputStream> getStreamHandlesForOxmFromResource() {
75     Map<Integer, InputStream> listOfOxmFiles = new HashMap<Integer, InputStream>();
76     ClassLoader oxmClassLoader = OxmModelLoader.class.getClassLoader();
77     ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(oxmClassLoader);
78     Resource[] resources = null;
79     try {
80       resources = resolver.getResources("classpath*:/oxm/aai_oxm*.xml");
81     } catch (IOException ex) {
82       LOG.error(AaiUiMsgs.OXM_LOADING_ERROR, ex.getMessage());
83     }
84
85     if (resources == null) {
86       LOG.error(AaiUiMsgs.OXM_LOADING_ERROR, "No OXM schema files found on classpath");
87     }
88
89     for (Resource resource : resources) {
90       Matcher m = p.matcher(resource.getFilename());
91
92       if (m.matches()) {
93         try {
94           listOfOxmFiles.put(new Integer(m.group(2)), resource.getInputStream());
95         } catch (Exception e) {
96           LOG.error(AaiUiMsgs.OXM_LOADING_ERROR,
97               resource.getFilename(), e.getMessage());
98         }
99       }
100     }
101     return listOfOxmFiles;
102   }
103   
104   /**
105    * Load an oxm model.
106    * @param inputStream file handle for oxm
107    */
108   protected void loadModel(InputStream inputStream) {
109     Map<String, Object> properties = new HashMap<String, Object>();
110     properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, inputStream);
111     try {
112       final DynamicJAXBContext oxmContext = DynamicJAXBContextFactory
113           .createContextFromOXM(Thread.currentThread().getContextClassLoader(), properties);
114
115       parseOxmContext(oxmContext);
116       // populateSearchableOxmModel();
117       LOG.info(AaiUiMsgs.OXM_LOAD_SUCCESS, String.valueOf(latestVersionNum));
118     } catch (Exception exc) {
119       LOG.info(AaiUiMsgs.OXM_PARSE_ERROR_NONVERBOSE);
120       LOG.error(AaiUiMsgs.OXM_PARSE_ERROR_VERBOSE, "OXM v" + latestVersionNum, exc.getMessage());
121     }
122   }
123   
124   /**
125    * Load the latest oxm model.
126    */
127   public synchronized void loadLatestOxmModel() {
128
129     LOG.info(AaiUiMsgs.INITIALIZE_OXM_MODEL_LOADER);
130     
131     // find handles for available oxm models
132     final Map<Integer, InputStream> listOfOxmStreams = getStreamHandlesForOxmFromResource();
133     if (listOfOxmStreams.isEmpty()) {
134       LOG.error(AaiUiMsgs.OXM_FILE_NOT_FOUND);
135       return;
136     }
137
138     InputStream stream = null;
139
140     if (oxmApiVersionOverride > 0) {
141       latestVersionNum = oxmApiVersionOverride;
142       LOG.warn(AaiUiMsgs.WARN_GENERIC, "Overriding AAI Schema with version = " + latestVersionNum);
143       stream = listOfOxmStreams.get(latestVersionNum);
144     } else {
145
146       for (Integer key : listOfOxmStreams.keySet()) {
147         if (key.intValue() > latestVersionNum) {
148           latestVersionNum = key.intValue();
149           stream = listOfOxmStreams.get(key);
150         }
151       }
152     }
153
154     // load the latest oxm file
155     loadModel(stream);
156
157   }
158   
159   public int getLatestVersionNum() {
160     return latestVersionNum;
161   }
162
163   public void setLatestVersionNum(int latestVersionNum) {
164     this.latestVersionNum = latestVersionNum;
165   }
166   
167   /**
168    * Parses the oxm context.
169    *
170    * @param oxmContext the oxm context
171    */
172   private void parseOxmContext(DynamicJAXBContext oxmContext) {
173
174     if (processors != null && processors.size() > 0) {
175
176       for (OxmModelProcessor processor : processors) {
177
178         try {
179
180           processor.processOxmModel(oxmContext);
181
182         } catch (Exception exc) {
183
184           LOG.warn(AaiUiMsgs.WARN_GENERIC,
185               "OxmModelProcessor experienced an error. Error: " + exc.getMessage());
186
187         }
188
189       }
190
191     }
192
193   }
194   
195 }