Migrate Spike code to ONAP
[aai/spike.git] / src / main / java / org / onap / aai / spike / schema / EdgeRulesLoader.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.spike.schema;
22
23 import java.io.File;
24 import java.io.FileInputStream;
25 import java.io.FileNotFoundException;
26 import java.io.IOException;
27 import java.util.Arrays;
28 import java.util.Map;
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.function.Function;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
33 import java.util.stream.Collectors;
34 import com.google.common.collect.Multimap;
35 import org.apache.commons.io.IOUtils;
36 import org.onap.aai.cl.eelf.LoggerFactory;
37 import org.onap.aai.edges.EdgeIngestor;
38 import org.onap.aai.edges.EdgeRule;
39 import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
40 import org.onap.aai.setup.ConfigTranslator;
41 import org.onap.aai.setup.SchemaLocationsBean;
42 import org.onap.aai.setup.Version;
43 import org.onap.aai.spike.exception.SpikeException;
44 import org.onap.aai.spike.logging.SpikeMsgs;
45 import org.onap.aai.spike.util.SchemaIngestPropertiesReader;
46
47
48 public class EdgeRulesLoader {
49
50     private static Map<String, RelationshipSchema> versionContextMap = new ConcurrentHashMap<>();
51
52     static final Pattern versionPattern = Pattern.compile("V(\\d*)");
53     static final String propsPrefix = "edge_properties_";
54     static final String propsSuffix = ".json";
55     final static Pattern propsFilePattern = Pattern.compile(propsPrefix + "(.*)" + propsSuffix);
56     final static Pattern propsVersionPattern = Pattern.compile("v\\d*");
57
58     private static org.onap.aai.cl.api.Logger logger =
59             LoggerFactory.getInstance().getLogger(EdgeRulesLoader.class.getName());
60
61     private EdgeRulesLoader() {}
62
63     /**
64      * Finds all DB Edge Rules and Edge Properties files for all OXM models.
65      *
66      * @throws SpikeException
67      */
68     public static synchronized void loadModels() throws SpikeException {
69         SchemaIngestPropertiesReader SchemaIngestPropertiesReader = new SchemaIngestPropertiesReader();
70         SchemaLocationsBean schemaLocationsBean = new SchemaLocationsBean();
71         schemaLocationsBean.setEdgeDirectory(SchemaIngestPropertiesReader.getEdgeDir());
72         ConfigTranslator configTranslator = new OxmConfigTranslator(schemaLocationsBean);
73         EdgeIngestor edgeIngestor = new EdgeIngestor(configTranslator);
74         Map<String, File> propFiles = edgePropertyFiles(SchemaIngestPropertiesReader);
75
76         if (logger.isDebugEnabled()) {
77             logger.debug("Loading DB Edge Rules");
78         }
79
80         for (String version : OXMModelLoader.getLoadedOXMVersions()) {
81             try {
82                 loadModel(Version.valueOf(version), edgeIngestor, propFiles);
83             } catch (IOException | EdgeRuleNotFoundException e) {
84                 throw new SpikeException(e.getMessage(), e);
85             }
86         }
87     }
88
89     /**
90      * Loads DB Edge Rules and Edge Properties for a given version.
91      *
92      * @throws SpikeException
93      */
94
95     public static synchronized void loadModels(String v) throws SpikeException {
96         SchemaIngestPropertiesReader SchemaIngestPropertiesReader = new SchemaIngestPropertiesReader();
97         SchemaLocationsBean schemaLocationsBean = new SchemaLocationsBean();
98         schemaLocationsBean.setEdgeDirectory(SchemaIngestPropertiesReader.getEdgeDir());
99         ConfigTranslator configTranslator = new OxmConfigTranslator(schemaLocationsBean);
100         EdgeIngestor edgeIngestor = new EdgeIngestor(configTranslator);
101         String version = v.toUpperCase();
102         Map<String, File> propFiles = edgePropertyFiles(SchemaIngestPropertiesReader);
103
104         if (logger.isDebugEnabled()) {
105             logger.debug("Loading DB Edge Rules ");
106         }
107
108         try {
109             loadModel(Version.valueOf(version), edgeIngestor, propFiles);
110         } catch (IOException | EdgeRuleNotFoundException e) {
111             throw new SpikeException(e.getMessage());
112         }
113     }
114
115     /**
116      * Retrieves the DB Edge Rule relationship schema for a given version.
117      *
118      * @param version - The OXM version that we want the DB Edge Rule for.
119      * @return - A RelationshipSchema of the DB Edge Rule for the OXM version.
120      * @throws SpikeException
121      */
122     public static RelationshipSchema getSchemaForVersion(String version) throws SpikeException {
123
124         // If we haven't already loaded in the available OXM models, then do so now.
125         if (versionContextMap == null || versionContextMap.isEmpty()) {
126             loadModels();
127         } else if (!versionContextMap.containsKey(version)) {
128             logger.error(SpikeMsgs.OXM_LOAD_ERROR, "Error loading DB Edge Rules for: " + version);
129             throw new SpikeException("Error loading DB Edge Rules for: " + version);
130         }
131
132         return versionContextMap.get(version);
133     }
134
135     /**
136      * Retrieves the DB Edge Rule relationship schema for all loaded OXM versions.
137      *
138      * @return - A Map of the OXM version and it's corresponding RelationshipSchema of the DB Edge Rule.
139      * @throws SpikeException
140      */
141     public static Map<String, RelationshipSchema> getSchemas() throws SpikeException {
142
143         // If we haven't already loaded in the available OXM models, then do so now.
144         if (versionContextMap == null || versionContextMap.isEmpty()) {
145             loadModels();
146         }
147         return versionContextMap;
148     }
149
150     /**
151      * Returns the latest available DB Edge Rule version.
152      *
153      * @return - A Map of the OXM version and it's corresponding RelationshipSchema of the DB Edge Rule.
154      * @throws SpikeException
155      */
156     public static String getLatestSchemaVersion() throws SpikeException {
157
158         // If we haven't already loaded in the available OXM models, then do so now.
159         if (versionContextMap == null || versionContextMap.isEmpty()) {
160             loadModels();
161         }
162
163         // If there are still no models available, then there's not much we can do...
164         if (versionContextMap.isEmpty()) {
165             logger.error(SpikeMsgs.OXM_LOAD_ERROR, "No available DB Edge Rules to get latest version for.");
166             throw new SpikeException("No available DB Edge Rules to get latest version for.");
167         }
168
169         // Iterate over the available model versions to determine which is the most
170         // recent.
171         Integer latestVersion = null;
172         String latestVersionStr = null;
173         for (String versionKey : versionContextMap.keySet()) {
174
175             Matcher matcher = versionPattern.matcher(versionKey.toUpperCase());
176             if (matcher.find()) {
177
178                 int currentVersion = Integer.parseInt(matcher.group(1));
179
180                 if ((latestVersion == null) || (currentVersion > latestVersion)) {
181                     latestVersion = currentVersion;
182                     latestVersionStr = versionKey;
183                 }
184             }
185         }
186
187         return latestVersionStr;
188     }
189
190     /**
191      * Reset the loaded DB Edge Rule schemas
192      *
193      */
194
195     public static void resetSchemaVersionContext() {
196         versionContextMap = new ConcurrentHashMap<>();
197     }
198
199     private static synchronized void loadModel(Version version, EdgeIngestor edgeIngestor, Map<String, File> props)
200             throws IOException, SpikeException, EdgeRuleNotFoundException {
201
202         Multimap<String, EdgeRule> edges = edgeIngestor.getAllRules(version);
203         String edgeProps;
204         if (props.get(version.toString().toLowerCase()) != null) {
205             edgeProps = IOUtils.toString(new FileInputStream(props.get(version.toString().toLowerCase())), "UTF-8");
206         } else {
207             throw new FileNotFoundException("The Edge Properties file for OXM version " + version + "was not found.");
208         }
209         if (edges != null) {
210             RelationshipSchema rs = new RelationshipSchema(edges, edgeProps);
211             versionContextMap.put(version.toString().toLowerCase(), rs);
212             logger.info(SpikeMsgs.LOADED_DB_RULE_FILE, version.toString());
213         }
214     }
215
216     private static Map<String, File> edgePropertyFiles(SchemaIngestPropertiesReader dir) throws SpikeException {
217         Map<String, File> propsFiles = Arrays
218                 .stream(new File(dir.getEdgePropsDir())
219                         .listFiles((d, name) -> propsFilePattern.matcher(name).matches()))
220                 .collect(Collectors.toMap(new Function<File, String>() {
221                     public String apply(File f) {
222                         Matcher m1 = propsVersionPattern.matcher(f.getName());
223                         m1.find();
224                         return m1.group(0);
225                     }
226                 }, f -> f));
227         return propsFiles;
228     }
229 }