2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017 AT&T Intellectual Property.
6 * Copyright © 2017 Amdocs
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=========================================================
22 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
24 package org.onap.schema;
27 import java.io.FileInputStream;
28 import java.io.FileNotFoundException;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.Comparator;
34 import java.util.Date;
35 import java.util.List;
37 import java.util.SortedSet;
38 import java.util.Timer;
39 import java.util.TimerTask;
40 import java.util.TreeSet;
41 import java.util.concurrent.ConcurrentHashMap;
42 import java.util.regex.Matcher;
43 import java.util.regex.Pattern;
44 import java.util.stream.Collectors;
46 import javax.ws.rs.core.Response.Status;
48 import org.apache.commons.io.IOUtils;
49 import org.onap.aai.cl.eelf.LoggerFactory;
50 import org.onap.crud.exception.CrudException;
51 import org.onap.crud.logging.CrudServiceMsgs;
52 import org.onap.crud.util.CrudServiceConstants;
53 import org.onap.crud.util.FileWatcher;
54 import org.springframework.core.io.UrlResource;
55 import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
56 import org.springframework.core.io.support.ResourcePatternResolver;
58 public class RelationshipSchemaLoader {
60 private static Map<String, RelationshipSchema> versionContextMap = new ConcurrentHashMap<>();
61 private static SortedSet<Integer> versions = new TreeSet<Integer>();
62 private static Map<String, Timer> timers = new ConcurrentHashMap<String, Timer>();
63 final static String edgePropsFiles = "edge_properties_";
64 final static String fileExt = ".json";
65 final static Pattern rulesFilePattern = Pattern.compile("DbEdgeRules(.*)" + fileExt);
66 final static Pattern propsFilePattern = Pattern.compile(edgePropsFiles + "(.*)" + fileExt);
67 final static Pattern versionPattern = Pattern.compile(".*(v\\d+)" + fileExt);
69 private static org.onap.aai.cl.api.Logger logger = LoggerFactory.getInstance()
70 .getLogger(RelationshipSchemaLoader.class.getName());
72 public synchronized static void loadModels() throws CrudException {
73 load(rulesFilePattern, propsFilePattern);
76 public synchronized static void loadModels(String version) throws CrudException {
77 String pattern = String.format(".*(%s)" + fileExt, version);
78 load(Pattern.compile(pattern), Pattern.compile(edgePropsFiles + version + fileExt));
81 public static RelationshipSchema getSchemaForVersion(String version) throws CrudException {
82 if (versionContextMap == null || versionContextMap.isEmpty()) {
84 } else if (!versionContextMap.containsKey(version)) {
87 } catch (Exception e) {
88 throw new CrudException("", Status.NOT_FOUND);
91 RelationshipSchema schema = versionContextMap.get(version);
93 throw new CrudException("", Status.NOT_FOUND);
98 public static String getLatestSchemaVersion() throws CrudException {
99 return "v" + versions.last();
102 public static Map<String, RelationshipSchema> getVersionContextMap() {
103 return versionContextMap;
106 public static void setVersionContextMap(Map<String, RelationshipSchema> versionContextMap) {
107 RelationshipSchemaLoader.versionContextMap = versionContextMap;
110 public static void resetVersionContextMap() {
111 RelationshipSchemaLoader.versionContextMap = new ConcurrentHashMap<>();
114 private static void load(Pattern rulesPattern, Pattern edgePropsPattern) throws CrudException {
115 ClassLoader cl = RelationshipSchemaLoader.class.getClassLoader();
116 ResourcePatternResolver rulesResolver = new PathMatchingResourcePatternResolver(cl);
117 List<Object> rulesFiles;
118 String rulesDir = CrudServiceConstants.CRD_HOME_MODEL;
121 // getResources method returns objects of type "Resource"
122 // 1. We are getting all the objects from the classpath which has
123 // "DbEdgeRules" in the name.
124 // 2. We run them through a filter and return only the objects which match
125 // the supplied pattern "p"
126 // 3. We then collect the objects in a list. At this point we have a list
127 // of the kind of files we require.
128 rulesFiles = Arrays.stream(rulesResolver.getResources("classpath*:/dbedgerules/DbEdgeRules*" + fileExt))
129 .filter(r -> !myMatcher(rulesPattern, r.getFilename()).isEmpty()).collect(Collectors.toList());
131 // This gets all the objects of type "File" from external directory (not
133 // 1. From an external directory (one not on the classpath) we get all the
134 // objects of type "File"
135 // 2. We only return the files whose names matched the supplied pattern
137 // 3. We then collect all the objects in a list and add the contents of
139 // to the previous collection (rulesFiles)
141 .addAll(Arrays.stream(new File(rulesDir).listFiles((d, name) -> edgePropsPattern.matcher(name).matches()))
142 .collect(Collectors.toList()));
144 if (rulesFiles.isEmpty()) {
145 logger.error(CrudServiceMsgs.INVALID_OXM_DIR, rulesDir);
146 throw new FileNotFoundException("DbEdgeRules and edge_properties files were not found.");
149 // Sort and then group the files with their versions, convert them to the
150 // schema, and add them to versionContextMap
151 // 1. Sort the files. We need the DbEdgeRules files to be before the
152 // edgeProperties files.
153 // 2. Group the files with their versions. ie. v11 ->
154 // ["DbEdgeRule_v11.json", "edgeProperties_v11.json"].
155 // The "group method" returns a HashMap whose key is the version and the
156 // value is a list of objects.
157 // 3. Go through each version and map the files into one schema using the
158 // "jsonFilesLoader" method.
159 // Also update the "versionContextMap" with the version and it's schema.
160 rulesFiles.stream().sorted(Comparator.comparing(RelationshipSchemaLoader::filename))
161 .collect(Collectors.groupingBy(f -> myMatcher(versionPattern, filename(f))))
162 .forEach((version, resourceAndFile) -> {
163 if (resourceAndFile.size() == 2) {
164 versionContextMap.put(version, jsonFilesLoader(version, resourceAndFile));
166 String filenames = resourceAndFile.stream().map(f -> filename(f)).collect(Collectors.toList()).toString();
167 String errorMsg = "Expecting a rules and a edge_properties files for " + version + ". Found: "
169 logger.warn(CrudServiceMsgs.INVALID_OXM_FILE, errorMsg);
172 logger.info(CrudServiceMsgs.LOADED_OXM_FILE, "Relationship Schema and Properties files: "
173 + rulesFiles.stream().map(f -> filename(f)).collect(Collectors.toList()));
174 } catch (IOException e) {
175 logger.error(CrudServiceMsgs.INVALID_OXM_DIR, rulesDir);
176 throw new CrudException("DbEdgeRules or edge_properties files were not found.", new FileNotFoundException());
180 private static String filename(Object k) throws ClassCastException {
181 if (k instanceof UrlResource) {
182 return ((UrlResource) k).getFilename();
183 } else if (k instanceof File) {
184 return ((File) k).getName();
186 throw new ClassCastException();
190 private static RelationshipSchema jsonFilesLoader(String version, List<Object> files) {
191 List<String> fileContents = new ArrayList<>();
192 RelationshipSchema rsSchema = null;
193 if (files.size() == 2) {
194 for (Object file : files) {
195 fileContents.add(jsonToRelationSchema(version, file));
196 versions.add(Integer.parseInt(version.substring(1)));
200 rsSchema = new RelationshipSchema(fileContents);
201 } catch (CrudException | IOException e) {
203 logger.error(CrudServiceMsgs.INVALID_OXM_FILE,
204 files.stream().map(f -> filename(f)).collect(Collectors.toList()).toString(), e.getMessage());
211 private synchronized static void updateVersionContext(String version, RelationshipSchema rs) {
212 versionContextMap.put(version, rs);
215 private synchronized static String jsonToRelationSchema(String version, Object file) {
216 InputStream inputStream = null;
217 String content = null;
220 if (file instanceof UrlResource) {
221 inputStream = ((UrlResource) file).getInputStream();
223 inputStream = new FileInputStream((File) file);
224 addtimer(version, file);
226 content = IOUtils.toString(inputStream, "UTF-8");
227 } catch (IOException e) {
233 private static void addtimer(String version, Object file) {
234 TimerTask task = null;
235 task = new FileWatcher((File) file) {
236 protected void onChange(File file) {
237 // here we implement the onChange
238 logger.info(CrudServiceMsgs.OXM_FILE_CHANGED, file.getName());
241 // Cannot use the file object here because we also have to get the
242 // edge properties associated with that version.
243 // The properties are stored in a different file.
244 RelationshipSchemaLoader.loadModels(version);
245 } catch (Exception e) {
251 if (!timers.containsKey(version)) {
252 Timer timer = new Timer("db_edge_rules_" + version);
253 timer.schedule(task, new Date(), 10000);
254 timers.put(version, timer);
259 private static String myMatcher(Pattern p, String s) {
260 Matcher m = p.matcher(s);
261 return m.matches() ? m.group(1) : "";