Upgrade version of aai-common
[aai/gizmo.git] / src / main / java / org / onap / schema / EdgeRulesLoader.java
1 /**\r
2  * ============LICENSE_START=======================================================\r
3  * org.onap.aai\r
4  * ================================================================================\r
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.\r
6  * Copyright © 2017-2018 Amdocs\r
7  * ================================================================================\r
8  * Licensed under the Apache License, Version 2.0 (the "License");\r
9  * you may not use this file except in compliance with the License.\r
10  * You may obtain a copy of the License at\r
11  *\r
12  *       http://www.apache.org/licenses/LICENSE-2.0\r
13  *\r
14  * Unless required by applicable law or agreed to in writing, software\r
15  * distributed under the License is distributed on an "AS IS" BASIS,\r
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
17  * See the License for the specific language governing permissions and\r
18  * limitations under the License.\r
19  * ============LICENSE_END=========================================================\r
20  */\r
21 package org.onap.schema;\r
22 \r
23 import java.io.File;\r
24 import java.io.FileInputStream;\r
25 import java.io.FileNotFoundException;\r
26 import java.io.IOException;\r
27 import java.util.Arrays;\r
28 import java.util.Map;\r
29 import java.util.concurrent.ConcurrentHashMap;\r
30 import java.util.function.Function;\r
31 import java.util.regex.Matcher;\r
32 import java.util.regex.Pattern;\r
33 import java.util.stream.Collectors;\r
34 \r
35 import javax.ws.rs.core.Response.Status;\r
36 \r
37 import org.apache.commons.io.IOUtils;\r
38 import org.onap.aai.cl.eelf.LoggerFactory;\r
39 import org.onap.aai.edges.EdgeIngestor;\r
40 import org.onap.aai.edges.EdgeRule;\r
41 import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;\r
42 import org.onap.aai.setup.ConfigTranslator;\r
43 import org.onap.aai.setup.SchemaVersion;\r
44 import org.onap.crud.exception.CrudException;\r
45 import org.onap.crud.logging.CrudServiceMsgs;\r
46 import org.springframework.beans.factory.annotation.Autowired;\r
47 \r
48 import com.google.common.collect.Multimap;\r
49 \r
50 public class EdgeRulesLoader {\r
51         \r
52         private static ConfigTranslator configTranslator;\r
53     private static EdgeIngestor edgeIngestor;\r
54 \r
55     private static EdgePropsConfiguration edgePropsConfiguration;\r
56 \r
57     private static Map<String, RelationshipSchema> versionContextMap =\r
58             new ConcurrentHashMap<> ();\r
59 \r
60     static final Pattern versionPattern = Pattern.compile("(?i)v(\\d*)");\r
61     static final String propsPrefix = "edge_properties_";\r
62     static final String propsSuffix = ".json";\r
63     final static Pattern propsFilePattern = Pattern.compile ( propsPrefix + "(.*)" + propsSuffix );\r
64     final static Pattern propsVersionPattern = Pattern.compile("(?i)v(\\d*)");\r
65 \r
66     private static org.onap.aai.cl.api.Logger logger =\r
67             LoggerFactory.getInstance ().getLogger ( EdgeRulesLoader.class.getName () );\r
68 \r
69     private EdgeRulesLoader () { }\r
70     \r
71     @Autowired\r
72     public EdgeRulesLoader(ConfigTranslator configTranslator, EdgeIngestor edgeIngestor, EdgePropsConfiguration edgePropsConfiguration) {\r
73         EdgeRulesLoader.configTranslator = configTranslator;\r
74         EdgeRulesLoader.edgeIngestor = edgeIngestor;\r
75         EdgeRulesLoader.edgePropsConfiguration = edgePropsConfiguration;\r
76     }\r
77 \r
78     /**\r
79      * Finds all DB Edge Rules and Edge Properties files for all OXM models.\r
80      *\r
81      * @throws CrudException\r
82      */\r
83     public static synchronized void loadModels () throws CrudException {\r
84         Map<String, File> propFiles = edgePropertyFiles(edgePropsConfiguration);\r
85 \r
86         if (logger.isDebugEnabled()) {\r
87             logger.debug("Loading DB Edge Rules");\r
88         }\r
89 \r
90         for (String version : OxmModelLoader.getLoadedOXMVersions()) {\r
91             try {\r
92                 SchemaVersion schemaVersion = configTranslator.getSchemaVersions().getVersions().stream()\r
93                         .filter(s -> s.toString().equalsIgnoreCase(version)).findAny().orElse(null);\r
94                 loadModel(schemaVersion, edgeIngestor, propFiles);\r
95             } catch (IOException | EdgeRuleNotFoundException e) {\r
96                 throw new CrudException(e.getMessage (), e);\r
97             }\r
98         }\r
99     }\r
100 \r
101     /**\r
102      * Loads DB Edge Rules and Edge Properties for a given version.\r
103      *\r
104      * @throws CrudException\r
105      */\r
106 \r
107     public static synchronized void loadModels ( String v ) throws CrudException {\r
108         Map<String, File> propFiles = edgePropertyFiles(edgePropsConfiguration);\r
109 \r
110         if (logger.isDebugEnabled()) {\r
111             logger.debug("Loading DB Edge Rules ");\r
112         }\r
113 \r
114         try {\r
115             SchemaVersion schemaVersion = configTranslator.getSchemaVersions().getVersions().stream()\r
116                     .filter(s -> s.toString().equalsIgnoreCase(v)).findAny().orElse(null);\r
117 \r
118             loadModel(schemaVersion, edgeIngestor, propFiles);\r
119         } catch (IOException | EdgeRuleNotFoundException e) {\r
120             throw new CrudException(e.getMessage (), Status.INTERNAL_SERVER_ERROR);\r
121         }\r
122     }\r
123 \r
124     /**\r
125      * Retrieves the DB Edge Rule relationship schema for a given version.\r
126      *\r
127      * @param version - The OXM version that we want the DB Edge Rule for.\r
128      * @return - A RelationshipSchema of the DB Edge Rule for the OXM version.\r
129      * @throws CrudException\r
130      */\r
131     public static RelationshipSchema getSchemaForVersion ( String version ) throws CrudException {\r
132 \r
133         // If we haven't already loaded in the available OXM models, then do so now.\r
134         if (versionContextMap == null || versionContextMap.isEmpty ()) {\r
135             loadModels ();\r
136         } else if (!versionContextMap.containsKey ( version )) {\r
137             logger.error ( CrudServiceMsgs.OXM_LOAD_ERROR, "Error loading DB Edge Rules for: " + version );\r
138             throw new CrudException ( "Error loading DB Edge Rules for: " + version, Status.NOT_FOUND );\r
139         }\r
140 \r
141         return versionContextMap.get ( version );\r
142     }\r
143 \r
144     /**\r
145      * Retrieves the DB Edge Rule relationship schema for all loaded OXM versions.\r
146      *\r
147      * @return - A Map of the OXM version and it's corresponding RelationshipSchema of the DB Edge Rule.\r
148      * @throws CrudException\r
149      */\r
150     public static Map<String, RelationshipSchema> getSchemas () throws CrudException {\r
151 \r
152         // If we haven't already loaded in the available OXM models, then do so now.\r
153         if (versionContextMap == null || versionContextMap.isEmpty ()) {\r
154             loadModels ();\r
155         }\r
156         return versionContextMap;\r
157     }\r
158 \r
159     /**\r
160      * Returns the latest available DB Edge Rule version.\r
161      *\r
162      * @return - A Map of the OXM version and it's corresponding RelationshipSchema of the DB Edge Rule.\r
163      * @throws CrudException\r
164      */\r
165     public static String getLatestSchemaVersion () throws CrudException {\r
166 \r
167         // If we haven't already loaded in the available OXM models, then do so now.\r
168         if (versionContextMap == null || versionContextMap.isEmpty ()) {\r
169             loadModels ();\r
170         }\r
171 \r
172         // If there are still no models available, then there's not much we can do...\r
173         if (versionContextMap.isEmpty ()) {\r
174             logger.error ( CrudServiceMsgs.OXM_LOAD_ERROR, "No available DB Edge Rules to get latest version for." );\r
175             throw new CrudException ( "No available DB Edge Rules to get latest version for.",\r
176                     Status.INTERNAL_SERVER_ERROR );\r
177         }\r
178 \r
179         // Iterate over the available model versions to determine which is the most\r
180         // recent.\r
181         Integer latestVersion = null;\r
182         String latestVersionStr = null;\r
183         for (String versionKey : versionContextMap.keySet ()) {\r
184 \r
185             Matcher matcher = versionPattern.matcher(versionKey);\r
186             if (matcher.find ()) {\r
187 \r
188                 int currentVersion = Integer.parseInt ( matcher.group ( 1 ) );\r
189 \r
190                 if ((latestVersion == null) || (currentVersion > latestVersion)) {\r
191                     latestVersion = currentVersion;\r
192                     latestVersionStr = versionKey;\r
193                 }\r
194             }\r
195         }\r
196 \r
197         return latestVersionStr;\r
198     }\r
199 \r
200     /**\r
201      * Reset the loaded DB Edge Rule schemas\r
202      *\r
203      */\r
204 \r
205     public static void resetSchemaVersionContext () {\r
206         versionContextMap = new ConcurrentHashMap<> ();\r
207     }\r
208 \r
209     private static synchronized void loadModel(SchemaVersion version, EdgeIngestor edgeIngestor,\r
210             Map<String, File> props) throws IOException, CrudException, EdgeRuleNotFoundException {\r
211 \r
212         Multimap<String, EdgeRule> edges = edgeIngestor.getAllRules ( version );\r
213         String edgeProps;\r
214         if (props.get ( version.toString().toLowerCase () ) != null) {\r
215             edgeProps = IOUtils.toString ( new FileInputStream ( props.get ( version.toString().toLowerCase () ) ), "UTF-8" );\r
216         } else {\r
217             throw new FileNotFoundException ( "The Edge Properties file for OXM version " + version + "was not found." );\r
218         }\r
219         if (edges != null) {\r
220             RelationshipSchema rs = new RelationshipSchema ( edges, edgeProps );\r
221             versionContextMap.put ( version.toString ().toLowerCase (), rs );\r
222             logger.info ( CrudServiceMsgs.LOADED_DB_RULE_FILE, version.toString () );\r
223         }\r
224     }\r
225 \r
226     private static Map<String, File> edgePropertyFiles ( EdgePropsConfiguration edgePropsConfiguration ) throws CrudException {\r
227         Map<String, File> propsFiles = Arrays.stream ( new File ( edgePropsConfiguration.getEdgePropsDir () )\r
228                 .listFiles ( ( d, name ) -> propsFilePattern.matcher ( name ).matches () ) )\r
229                 .collect ( Collectors.toMap ( new Function<File, String> () {\r
230                         @Override\r
231                         public String apply ( File f ) {\r
232                         Matcher m1 = propsVersionPattern.matcher ( f.getName () );\r
233                         m1.find ();\r
234                         return m1.group ( 0 );\r
235                     }\r
236                 }, f -> f ) );\r
237         return  propsFiles;\r
238     }\r
239 \r
240 }\r