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