[AAI-26] Adding gizmo data to the repository.
[aai/gizmo.git] / src / main / java / org / openecomp / schema / OxmModelLoader.java
1 /**
2  * ============LICENSE_START=======================================================
3  * Gizmo
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 is a trademark and service mark of AT&T Intellectual Property.
23  */
24 package org.openecomp.schema;
25
26 import org.eclipse.persistence.jaxb.JAXBContextProperties;
27 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
28 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory;
29 import org.openecomp.cl.eelf.LoggerFactory;
30 import org.openecomp.crud.exception.CrudException;
31 import org.openecomp.crud.logging.CrudServiceMsgs;
32 import org.openecomp.crud.util.CrudServiceConstants;
33 import org.openecomp.crud.util.FileWatcher;
34 import org.springframework.core.io.Resource;
35 import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
36 import org.springframework.core.io.support.ResourcePatternResolver;
37
38 import java.io.File;
39 import java.io.FileInputStream;
40 import java.io.IOException;
41 import java.io.InputStream;
42 import java.util.Date;
43 import java.util.HashMap;
44 import java.util.Map;
45 import java.util.Timer;
46 import java.util.TimerTask;
47 import java.util.concurrent.ConcurrentHashMap;
48 import java.util.regex.Matcher;
49 import java.util.regex.Pattern;
50 import javax.ws.rs.core.Response.Status;
51 import javax.xml.bind.JAXBException;
52
53
54 public class OxmModelLoader {
55
56   private static Map<String, DynamicJAXBContext> versionContextMap
57       = new ConcurrentHashMap<String, DynamicJAXBContext>();
58   private static Map<String, Timer> timers = new ConcurrentHashMap<String, Timer>();
59
60   final static Pattern p = Pattern.compile("aai_oxm_(.*).xml");
61
62   private static org.openecomp.cl.api.Logger logger = LoggerFactory.getInstance()
63       .getLogger(OxmModelLoader.class.getName());
64
65   public synchronized static void loadModels() throws CrudException {
66     ClassLoader cl = OxmModelLoader.class.getClassLoader();
67     ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
68     Resource[] resources;
69     try {
70       resources = resolver.getResources("classpath*:/oxm/aai_oxm*.xml");
71     } catch (IOException ex) {
72       logger.error(CrudServiceMsgs.OXM_LOAD_ERROR, ex.getMessage());
73       throw new CrudException("", Status.NOT_FOUND);
74     }
75
76     if (resources.length == 0) {
77       logger.error(CrudServiceMsgs.OXM_LOAD_ERROR, "No OXM schema files found on classpath");
78       throw new CrudException("Failed to load schema", Status.NOT_FOUND);
79     }
80
81     for (Resource resource : resources) {
82       Matcher matcher = p.matcher(resource.getFilename());
83
84       if (matcher.matches()) {
85         try {
86           OxmModelLoader.loadModel(matcher.group(1), resource);
87         } catch (Exception e) {
88           logger.error(CrudServiceMsgs.OXM_LOAD_ERROR, "Failed to load " + resource.getFilename()
89               + ": " + e.getMessage());
90           throw new CrudException("Failed to load schema", Status.NOT_FOUND);
91         }
92       }
93     }
94   }
95
96   private static void addtimer(String version, File file) {
97     TimerTask task = null;
98     task = new FileWatcher(
99         file) {
100       protected void onChange(File file) {
101         // here we implement the onChange
102         logger.info(CrudServiceMsgs.OXM_FILE_CHANGED, file.getName());
103
104         try {
105           OxmModelLoader.loadModel(version, file);
106         } catch (Exception e) {
107           e.printStackTrace();
108         }
109
110       }
111     };
112
113     if (!timers.containsKey(version)) {
114       Timer timer = new Timer("oxm-" + version);
115       timer.schedule(task, new Date(), 10000);
116       timers.put(version, timer);
117
118     }
119   }
120
121   private synchronized static void loadModel(String version, File file)
122       throws JAXBException, IOException {
123     InputStream inputStream = new FileInputStream(file);
124     loadModel(version, file.getName(), inputStream);
125     addtimer(version, file);
126   }
127
128   private synchronized static void loadModel(String version, Resource resource)
129       throws JAXBException, IOException {
130     InputStream inputStream = resource.getInputStream();
131     loadModel(version, resource.getFilename(), inputStream);
132   }
133
134   private synchronized static void loadModel(String version, String resourceName,
135                                              InputStream inputStream)
136       throws JAXBException, IOException {
137     Map<String, Object> properties = new HashMap<String, Object>();
138     properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, inputStream);
139     final DynamicJAXBContext jaxbContext = DynamicJAXBContextFactory
140         .createContextFromOXM(Thread.currentThread().getContextClassLoader(), properties);
141     versionContextMap.put(version, jaxbContext);
142     logger.info(CrudServiceMsgs.LOADED_OXM_FILE, resourceName);
143   }
144
145   public static DynamicJAXBContext getContextForVersion(String version) throws CrudException {
146     if (versionContextMap == null || versionContextMap.isEmpty()) {
147       loadModels();
148     } else if (!versionContextMap.containsKey(version)) {
149       try {
150         loadModel(version, new File(CrudServiceConstants.CRD_HOME_MODEL + "aai_oxm_"
151             + version + ".xml"));
152       } catch (Exception e) {
153         throw new CrudException("", Status.NOT_FOUND);
154       }
155     }
156
157     return versionContextMap.get(version);
158   }
159
160   public static Map<String, DynamicJAXBContext> getVersionContextMap() {
161     return versionContextMap;
162   }
163
164   public static void setVersionContextMap(Map<String, DynamicJAXBContext> versionContextMap) {
165     OxmModelLoader.versionContextMap = versionContextMap;
166   }
167
168 }