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