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