Reduce the number of problems in aai-common by removing unused imports
[aai/aai-common.git] / aai-schema-abstraction / src / main / java / org / onap / aai / schemaif / oxm / OxmEdgeRulesLoader.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2019 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2019 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
22 package org.onap.aai.schemaif.oxm;
23
24 import com.google.common.collect.Multimap;
25
26 import java.io.File;
27 import java.io.FileInputStream;
28 import java.io.FileNotFoundException;
29 import java.io.IOException;
30 import java.util.Arrays;
31 import java.util.Map;
32 import java.util.concurrent.ConcurrentHashMap;
33 import java.util.function.Function;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
36 import java.util.stream.Collectors;
37
38 import org.apache.commons.io.IOUtils;
39 import org.onap.aai.cl.api.Logger;
40 import org.onap.aai.cl.eelf.LoggerFactory;
41 import org.onap.aai.edges.EdgeIngestor;
42 import org.onap.aai.edges.EdgeRule;
43 import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
44 import org.onap.aai.schemaif.SchemaProviderException;
45 import org.onap.aai.schemaif.SchemaProviderMsgs;
46 import org.onap.aai.setup.SchemaVersion;
47 import org.onap.aai.setup.Translator;
48 import org.springframework.beans.factory.annotation.Autowired;
49 import org.springframework.stereotype.Component;
50
51 @Component
52 public class OxmEdgeRulesLoader {
53
54     private static Translator translator;
55     private static EdgeIngestor edgeIngestor;
56
57     private static EdgePropsConfiguration edgePropsConfiguration;
58
59     private static Map<String, RelationshipSchema> versionContextMap = new ConcurrentHashMap<>();
60
61     static final Pattern versionPattern = Pattern.compile("(?i)v(\\d*)");
62     static final String propsPrefix = "edge_properties_";
63     static final String propsSuffix = ".json";
64     final static Pattern propsFilePattern = Pattern.compile(propsPrefix + "(.*)" + propsSuffix);
65     final static Pattern propsVersionPattern = Pattern.compile("(?i)v\\d*");
66
67     private static Logger logger = LoggerFactory.getInstance().getLogger(OxmEdgeRulesLoader.class.getName());
68
69     private OxmEdgeRulesLoader() {
70     }
71
72     /**
73      * This constructor presents an awkward marrying of Spring bean creation and static method use. This
74      * is technical debt that will need fixing.
75      *
76      * @param translator contains schema versions configuration
77      * @param edgeIngestor provides edge rules
78      * @param edgePropsConfiguration edge property validation configuration
79      */
80     @Autowired
81     public OxmEdgeRulesLoader(Translator translator, EdgeIngestor edgeIngestor,
82             EdgePropsConfiguration edgePropsConfiguration) {
83         OxmEdgeRulesLoader.translator = translator;
84         OxmEdgeRulesLoader.edgeIngestor = edgeIngestor;
85         OxmEdgeRulesLoader.edgePropsConfiguration = edgePropsConfiguration;
86     }
87
88     /**
89      * Finds all DB Edge Rules and Edge Properties files for all OXM models.
90      *
91      * @throws SchemaProviderException
92      * @throws SchemaProviderException
93      */
94     public static synchronized void loadModels() throws SchemaProviderException {
95         Map<String, File> propFiles = edgePropertyFiles(edgePropsConfiguration);
96
97         if (logger.isDebugEnabled()) {
98             logger.debug("Loading DB Edge Rules");
99         }
100
101         for (String version : OxmSchemaLoader.getLoadedOXMVersions()) {
102             try {
103                 SchemaVersion schemaVersion = translator.getSchemaVersions().getVersions().stream()
104                         .filter(s -> s.toString().equalsIgnoreCase(version)).findAny().orElse(null);
105                 loadModel(schemaVersion, edgeIngestor, propFiles);
106             } catch (IOException | EdgeRuleNotFoundException e) {
107                 throw new SchemaProviderException(e.getMessage(), e);
108             }
109         }
110     }
111
112     /**
113      * Loads DB Edge Rules and Edge Properties for a given version.
114      *
115      * @throws SchemaProviderException
116      */
117
118     public static synchronized void loadModels(String v) throws SchemaProviderException {
119         Map<String, File> propFiles = edgePropertyFiles(edgePropsConfiguration);
120
121         if (logger.isDebugEnabled()) {
122             logger.debug("Loading DB Edge Rules ");
123         }
124
125         try {
126             SchemaVersion schemaVersion = translator.getSchemaVersions().getVersions().stream()
127                     .filter(s -> s.toString().equalsIgnoreCase(v)).findAny().orElse(null);
128
129             loadModel(schemaVersion, edgeIngestor, propFiles);
130         } catch (IOException | EdgeRuleNotFoundException e) {
131             throw new SchemaProviderException(e.getMessage());
132         }
133     }
134
135     /**
136      * Retrieves the DB Edge Rule relationship schema for a given version.
137      *
138      * @param version - The OXM version that we want the DB Edge Rule for.
139      * @return - A RelationshipSchema of the DB Edge Rule for the OXM version.
140      * @throws SchemaProviderException
141      */
142     public static RelationshipSchema getSchemaForVersion(String version) throws SchemaProviderException {
143
144         // If we haven't already loaded in the available OXM models, then do so now.
145         if (versionContextMap == null || versionContextMap.isEmpty()) {
146             loadModels();
147         } else if (!versionContextMap.containsKey(version)) {
148             logger.error(SchemaProviderMsgs.SCHEMA_LOAD_ERROR, "Error loading DB Edge Rules for: " + version);
149             throw new SchemaProviderException("Error loading DB Edge Rules for: " + version);
150         }
151
152         return versionContextMap.get(version);
153     }
154
155     /**
156      * Retrieves the DB Edge Rule relationship schema for all loaded OXM versions.
157      *
158      * @return - A Map of the OXM version and it's corresponding RelationshipSchema of the DB Edge Rule.
159      * @throws SchemaProviderException
160      */
161     public static Map<String, RelationshipSchema> getSchemas() throws SchemaProviderException {
162
163         // If we haven't already loaded in the available OXM models, then do so now.
164         if (versionContextMap == null || versionContextMap.isEmpty()) {
165             loadModels();
166         }
167         return versionContextMap;
168     }
169
170     /**
171      * Returns the latest available DB Edge Rule version.
172      *
173      * @return - A Map of the OXM version and it's corresponding RelationshipSchema of the DB Edge Rule.
174      * @throws SchemaProviderException
175      */
176     public static String getLatestSchemaVersion() throws SchemaProviderException {
177
178         // If we haven't already loaded in the available OXM models, then do so now.
179         if (versionContextMap == null || versionContextMap.isEmpty()) {
180             loadModels();
181         }
182
183         // If there are still no models available, then there's not much we can do...
184         if (versionContextMap.isEmpty()) {
185             logger.error(SchemaProviderMsgs.SCHEMA_LOAD_ERROR, "No available DB Edge Rules to get latest version for.");
186             throw new SchemaProviderException("No available DB Edge Rules to get latest version for.");
187         }
188
189         // Iterate over the available model versions to determine which is the most
190         // recent.
191         Integer latestVersion = null;
192         String latestVersionStr = null;
193         for (String versionKey : versionContextMap.keySet()) {
194
195             Matcher matcher = versionPattern.matcher(versionKey);
196             if (matcher.find()) {
197
198                 int currentVersion = Integer.parseInt(matcher.group(1));
199
200                 if ((latestVersion == null) || (currentVersion > latestVersion)) {
201                     latestVersion = currentVersion;
202                     latestVersionStr = versionKey;
203                 }
204             }
205         }
206
207         return latestVersionStr;
208     }
209
210     /**
211      * Reset the loaded DB Edge Rule schemas
212      *
213      */
214     public static void resetSchemaVersionContext() {
215         versionContextMap = new ConcurrentHashMap<>();
216     }
217
218     private static synchronized void loadModel(SchemaVersion version, EdgeIngestor edgeIngestor,
219             Map<String, File> props) throws IOException, SchemaProviderException, EdgeRuleNotFoundException {
220
221         Multimap<String, EdgeRule> edges = edgeIngestor.getAllRules(version);
222         String edgeProps;
223         if (props.get(version.toString().toLowerCase()) != null) {
224             edgeProps = IOUtils.toString(new FileInputStream(props.get(version.toString().toLowerCase())), "UTF-8");
225         } else {
226             throw new FileNotFoundException("The Edge Properties file for OXM version " + version + "was not found.");
227         }
228         if (edges != null) {
229             RelationshipSchema rs = new RelationshipSchema(edges, edgeProps);
230             versionContextMap.put(version.toString().toLowerCase(), rs);
231             logger.info(SchemaProviderMsgs.LOADED_DB_RULE_FILE, version.toString());
232         }
233     }
234
235     private static Map<String, File> edgePropertyFiles(EdgePropsConfiguration edgePropsConfiguration)
236             throws SchemaProviderException {
237         Map<String, File> propsFiles = Arrays
238                 .stream(new File(edgePropsConfiguration.getEdgePropsDir())
239                         .listFiles((d, name) -> propsFilePattern.matcher(name).matches()))
240                 .collect(Collectors.toMap(new Function<File, String>() {
241                     @Override
242                     public String apply(File f) {
243                         Matcher m1 = propsVersionPattern.matcher(f.getName());
244                         m1.find();
245                         return m1.group(0);
246                     }
247                 }, f -> f));
248         return propsFiles;
249     }
250 }