48727a051259b8bb111528b5612d06a6cd53b206
[aai/gizmo.git] / src / main / java / org / onap / schema / RelationshipSchemaLoader.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.onap.schema;
25
26 import java.io.File;
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;
36 import java.util.Map;
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;
45
46 import javax.ws.rs.core.Response.Status;
47
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;
57
58 public class RelationshipSchemaLoader {
59
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);
68
69   private static org.onap.aai.cl.api.Logger logger = LoggerFactory.getInstance()
70       .getLogger(RelationshipSchemaLoader.class.getName());
71
72   public synchronized static void loadModels() throws CrudException {
73     load(rulesFilePattern, propsFilePattern);
74   }
75
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));
79   }
80
81   public static RelationshipSchema getSchemaForVersion(String version) throws CrudException {
82     if (versionContextMap == null || versionContextMap.isEmpty()) {
83       loadModels();
84     } else if (!versionContextMap.containsKey(version)) {
85       try {
86         loadModels(version);
87       } catch (Exception e) {
88         throw new CrudException("", Status.NOT_FOUND);
89       }
90     }
91     RelationshipSchema schema = versionContextMap.get(version);
92     if (schema == null) {
93       throw new CrudException("", Status.NOT_FOUND);
94     } else
95       return schema;
96   }
97
98   public static String getLatestSchemaVersion() throws CrudException {
99     return "v" + versions.last();
100   }
101
102   public static Map<String, RelationshipSchema> getVersionContextMap() {
103     return versionContextMap;
104   }
105
106   public static void setVersionContextMap(Map<String, RelationshipSchema> versionContextMap) {
107     RelationshipSchemaLoader.versionContextMap = versionContextMap;
108   }
109
110   public static void resetVersionContextMap() {
111     RelationshipSchemaLoader.versionContextMap = new ConcurrentHashMap<>();
112   }
113
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;
119     try {
120
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());
130
131       // This gets all the objects of type "File" from external directory (not
132       // on the classpath)
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
136       // "p2".
137       // 3. We then collect all the objects in a list and add the contents of
138       // this list
139       // to the previous collection (rulesFiles)
140       rulesFiles
141           .addAll(Arrays.stream(new File(rulesDir).listFiles((d, name) -> edgePropsPattern.matcher(name).matches()))
142               .collect(Collectors.toList()));
143
144       if (rulesFiles.isEmpty()) {
145         logger.error(CrudServiceMsgs.INVALID_OXM_DIR, rulesDir);
146         throw new FileNotFoundException("DbEdgeRules and edge_properties files were not found.");
147       }
148
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));
165             } else {
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: "
168                   + filenames;
169               logger.warn(CrudServiceMsgs.INVALID_OXM_FILE, errorMsg);
170             }
171           });
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());
177     }
178   }
179
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();
185     } else {
186       throw new ClassCastException();
187     }
188   }
189
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)));
197       }
198
199       try {
200         rsSchema = new RelationshipSchema(fileContents);
201       } catch (CrudException | IOException e) {
202         e.printStackTrace();
203         logger.error(CrudServiceMsgs.INVALID_OXM_FILE,
204             files.stream().map(f -> filename(f)).collect(Collectors.toList()).toString(), e.getMessage());
205       }
206       return rsSchema;
207     }
208     return rsSchema;
209   }
210
211   private synchronized static void updateVersionContext(String version, RelationshipSchema rs) {
212     versionContextMap.put(version, rs);
213   }
214
215   private synchronized static String jsonToRelationSchema(String version, Object file) {
216     InputStream inputStream = null;
217     String content = null;
218
219     try {
220       if (file instanceof UrlResource) {
221         inputStream = ((UrlResource) file).getInputStream();
222       } else {
223         inputStream = new FileInputStream((File) file);
224         addtimer(version, file);
225       }
226       content = IOUtils.toString(inputStream, "UTF-8");
227     } catch (IOException e) {
228       e.printStackTrace();
229     }
230     return content;
231   }
232
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());
239
240         try {
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) {
246           e.printStackTrace();
247         }
248       }
249     };
250
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);
255
256     }
257   }
258
259   private static String myMatcher(Pattern p, String s) {
260     Matcher m = p.matcher(s);
261     return m.matches() ? m.group(1) : "";
262   }
263 }