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