Renaming openecomp to onap
[aai/sparky-be.git] / src / main / java / org / onap / aai / sparky / config / oxm / OxmModelLoader.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017 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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  */
23 package org.onap.aai.sparky.config.oxm;
24
25 import java.io.File;
26 import java.io.FileInputStream;
27 import java.io.FileNotFoundException;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.HashMap;
33 import java.util.LinkedHashMap;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Map.Entry;
37 import java.util.Vector;
38 import java.util.regex.Matcher;
39 import java.util.regex.Pattern;
40
41 import org.eclipse.persistence.dynamic.DynamicType;
42 import org.eclipse.persistence.internal.oxm.mappings.Descriptor;
43 import org.eclipse.persistence.jaxb.JAXBContextProperties;
44 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
45 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory;
46 import org.eclipse.persistence.mappings.DatabaseMapping;
47 import org.onap.aai.sparky.logging.AaiUiMsgs;
48 import org.onap.aai.sparky.synchronizer.entity.SuggestionSearchEntity;
49 import org.onap.aai.sparky.viewandinspect.config.TierSupportUiConstants;
50 import org.onap.aai.cl.api.Logger;
51 import org.onap.aai.cl.eelf.LoggerFactory;
52
53 /**
54  * The Class OxmModelLoader.
55  */
56 public class OxmModelLoader {
57
58   private static OxmModelLoader instance;
59
60   private static final Logger LOG = LoggerFactory.getInstance().getLogger(OxmModelLoader.class);
61
62   private Map<String, HashMap<String, String>> oxmModel =
63       new LinkedHashMap<String, HashMap<String, String>>();
64
65   private Map<String, DynamicType> entityTypeLookup = new LinkedHashMap<String, DynamicType>();
66
67   private Map<String, HashMap<String, String>> searchableOxmModel =
68       new LinkedHashMap<String, HashMap<String, String>>();
69
70   private Map<String, HashMap<String, String>> crossReferenceEntityOxmModel =
71       new LinkedHashMap<String, HashMap<String, String>>();
72
73   private Map<String, HashMap<String, String>> geoEntityOxmModel =
74       new LinkedHashMap<String, HashMap<String, String>>();
75   
76   private Map<String, HashMap<String, String>> suggestionSearchEntityOxmModel =
77       new LinkedHashMap<String, HashMap<String, String>>();
78
79   private Map<String, OxmEntityDescriptor> entityDescriptors =
80       new HashMap<String, OxmEntityDescriptor>();
81
82   private Map<String, OxmEntityDescriptor> searchableEntityDescriptors =
83       new HashMap<String, OxmEntityDescriptor>();
84
85   private Map<String, OxmEntityDescriptor> crossReferenceEntityDescriptors =
86       new HashMap<String, OxmEntityDescriptor>();
87
88   private Map<String, OxmEntityDescriptor> geoEntityDescriptors =
89       new HashMap<String, OxmEntityDescriptor>();
90   
91   private Map<String, OxmEntityDescriptor> suggestionSearchEntityDescriptors =
92       new HashMap<String, OxmEntityDescriptor>();
93
94   public static OxmModelLoader getInstance() {
95     if (instance == null) {
96       instance = new OxmModelLoader();
97       LOG.info(AaiUiMsgs.INITIALIZE_OXM_MODEL_LOADER);
98       instance.loadModels();
99     }
100
101     return instance;
102
103   }
104
105   /**
106    * Instantiates a new oxm model loader.
107    */
108   public OxmModelLoader() {
109
110   }
111
112   /**
113    * Load models.
114    */
115   private void loadModels() {
116     // find latest version of OXM file in folder
117     String version = findLatestOxmVersion();
118     if (version == null) {
119       LOG.error(AaiUiMsgs.OXM_FILE_NOT_FOUND, TierSupportUiConstants.CONFIG_OXM_LOCATION);
120       return;
121     }
122
123     // load the latest version based on file name
124     loadModel(version);
125
126   }
127
128   /**
129    * Load model.
130    *
131    * @param version the version
132    */
133   public void loadModel(String version) {
134     String fileName = loadOxmFileName(version);
135
136     try(FileInputStream inputStream = new FileInputStream(new File(fileName))) {
137         Map<String, Object> properties = new HashMap<String, Object>();
138         properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, inputStream);
139
140         final DynamicJAXBContext oxmContext = DynamicJAXBContextFactory
141                                                .createContextFromOXM(Thread.currentThread()
142                                                .getContextClassLoader(), properties);
143         parseOxmContext(oxmContext);
144         // populateSearchableOxmModel();
145         LOG.info(AaiUiMsgs.OXM_LOAD_SUCCESS);
146
147     } catch (FileNotFoundException fnf) {
148         LOG.info(AaiUiMsgs.OXM_READ_ERROR_NONVERBOSE);
149         LOG.error(AaiUiMsgs.OXM_READ_ERROR_VERBOSE, fileName);
150     } catch (Exception exc) {
151         LOG.info(AaiUiMsgs.OXM_PARSE_ERROR_NONVERBOSE);
152         LOG.error(AaiUiMsgs.OXM_PARSE_ERROR_VERBOSE, fileName, exc.getMessage());
153     }
154   }
155
156   /**
157    * Parses the oxm context.
158    *
159    * @param oxmContext the oxm context
160    */
161   private void parseOxmContext(DynamicJAXBContext oxmContext) {
162     @SuppressWarnings("rawtypes")
163     List<Descriptor> descriptorsList = oxmContext.getXMLContext().getDescriptors();
164
165     for (@SuppressWarnings("rawtypes")
166         Descriptor desc : descriptorsList) {
167
168       DynamicType entity = oxmContext.getDynamicType(desc.getAlias());
169
170       LinkedHashMap<String, String> oxmProperties = new LinkedHashMap<String, String>();
171
172       // Not all fields have key attributes
173       if (desc.getPrimaryKeyFields() != null) {
174         oxmProperties.put("primaryKeyAttributeNames", desc.getPrimaryKeyFields().toString()
175             .replaceAll("/text\\(\\)", "").replaceAll("\\[", "").replaceAll("\\]", ""));
176       }
177
178       String entityName = desc.getDefaultRootElement();
179
180       entityTypeLookup.put(entityName, entity);
181
182       // add entityName
183       oxmProperties.put("entityName", entityName);
184
185       Map<String, String> properties = entity.getDescriptor().getProperties();
186       if (properties != null) {
187         for (Map.Entry<String, String> entry : properties.entrySet()) {
188           
189           if (entry.getKey().equalsIgnoreCase("searchable")) {
190             oxmProperties.put("searchableAttributes", entry.getValue());
191           } else if (entry.getKey().equalsIgnoreCase("crossEntityReference")) {
192             oxmProperties.put("crossEntityReference", entry.getValue());
193           } else if (entry.getKey().equalsIgnoreCase("geoLat")) {
194             if (entry.getValue().length() > 0) {
195               oxmProperties.put("geoLat", entry.getValue());
196             }
197           } else if (entry.getKey().equalsIgnoreCase("geoLong")) {
198             if (entry.getValue().length() > 0) {
199               oxmProperties.put("geoLong", entry.getValue());
200             }
201           } else if (entry.getKey().equalsIgnoreCase("containsSuggestibleProps")) {
202
203             oxmProperties.put("containsSuggestibleProps", "true");
204             
205             Vector<DatabaseMapping> descriptorMaps = entity.getDescriptor().getMappings();
206             List<String> listOfSuggestableAttributes = new ArrayList<String>();
207             
208             for (DatabaseMapping descMap : descriptorMaps) {
209               if (descMap.isAbstractDirectMapping()) {
210                 
211                 if (descMap.getProperties().get("suggestibleOnSearch") != null) {
212                   String suggestableOnSearchString = String.valueOf(
213                       descMap.getProperties().get("suggestibleOnSearch"));
214                   
215                   boolean isSuggestibleOnSearch = Boolean.valueOf(suggestableOnSearchString);
216
217                   if (isSuggestibleOnSearch) {
218                     /* Grab attribute types for suggestion */
219                     String attributeName = descMap.getField().getName()
220                         .replaceAll("/text\\(\\)", "");
221                     listOfSuggestableAttributes.add(attributeName);
222                     
223                     if (descMap.getProperties().get("suggestionVerbs") != null) {
224                       String suggestionVerbsString = String.valueOf(
225                           descMap.getProperties().get("suggestionVerbs"));
226                       
227                       oxmProperties.put("suggestionVerbs", suggestionVerbsString);
228                     }
229                   }
230                 }
231               }
232             }
233             if (!listOfSuggestableAttributes.isEmpty()) {
234               oxmProperties.put("suggestibleAttributes", String.join(",", 
235                   listOfSuggestableAttributes));
236             }
237           } else if (entry.getKey().equalsIgnoreCase("suggestionAliases")) {
238             oxmProperties.put("suggestionAliases", entry.getValue());
239           }
240         }
241       }
242
243       oxmModel.put(entityName, oxmProperties);
244
245       // Add all searchable entity types for reserve lookup
246       if (oxmProperties.containsKey("searchableAttributes")) {
247         searchableOxmModel.put(entityName, oxmProperties);
248       }
249
250       if (oxmProperties.containsKey("crossEntityReference")) {
251         crossReferenceEntityOxmModel.put(entityName, oxmProperties);
252       }
253
254       if (oxmProperties.containsKey("geoLat") && oxmProperties.containsKey("geoLong")) {
255         geoEntityOxmModel.put(entityName, oxmProperties);
256       }
257       
258       if (oxmProperties.containsKey("containsSuggestibleProps")) {
259         suggestionSearchEntityOxmModel.put(entityName, oxmProperties);
260       }
261     }
262
263     for (Entry<String, HashMap<String, String>> entityModel : oxmModel.entrySet()) {
264       HashMap<String, String> attribute = entityModel.getValue();
265       OxmEntityDescriptor entity = new OxmEntityDescriptor();
266       entity.setEntityName(attribute.get("entityName"));
267       if (attribute.containsKey("primaryKeyAttributeNames")) {
268
269         entity.setPrimaryKeyAttributeName(
270             Arrays.asList(attribute.get("primaryKeyAttributeNames").replace(" ", "").split(",")));
271         if (attribute.containsKey("searchableAttributes")) {
272           entity.setSearchableAttributes(
273               Arrays.asList(attribute.get("searchableAttributes").split(",")));
274         } else if (attribute.containsKey("crossEntityReference")) {
275           List<String> crossEntityRefTokens =
276               Arrays.asList(attribute.get("crossEntityReference").split(","));
277
278           if (crossEntityRefTokens.size() >= 2) {
279             CrossEntityReference entityRef = new CrossEntityReference();
280             entityRef.setTargetEntityType(crossEntityRefTokens.get(0));
281
282             for (int i = 1; i < crossEntityRefTokens.size(); i++) {
283               entityRef.addReferenceAttribute(crossEntityRefTokens.get(i));
284             }
285
286             entity.setCrossEntityReference(entityRef);
287           } else {
288             LOG.error(AaiUiMsgs.OXM_PROP_DEF_ERR_CROSS_ENTITY_REF, attribute.get("entityName"),
289                 attribute.get("crossEntityReference"));
290           }
291         }
292
293         if (attribute.containsKey("geoLat") || attribute.containsKey("geoLong")) {
294           entity.setGeoLatName(attribute.get("geoLat"));
295           entity.setGeoLongName(attribute.get("geoLong"));
296         }
297         
298         if (attribute.containsKey("suggestionVerbs")) {
299           String entityName = attribute.get("entityName");
300           SuggestionSearchEntity suggestionSearchEntity = new SuggestionSearchEntity(this);
301           suggestionSearchEntity.setEntityType(entityName);
302           
303           entity.setSuggestionSearchEntity(suggestionSearchEntity);
304         }
305
306         entityDescriptors.put(attribute.get("entityName"), entity);
307       }
308     }
309
310
311     for (Entry<String, HashMap<String, String>> searchableModel : searchableOxmModel.entrySet()) {
312       HashMap<String, String> attribute = searchableModel.getValue();
313       OxmEntityDescriptor entity = new OxmEntityDescriptor();
314       entity.setEntityName(attribute.get("entityName"));
315       entity.setPrimaryKeyAttributeName(
316           Arrays.asList(attribute.get("primaryKeyAttributeNames").replace(" ", "").split(",")));
317       entity
318           .setSearchableAttributes(Arrays.asList(attribute.get("searchableAttributes").split(",")));
319       searchableEntityDescriptors.put(attribute.get("entityName"), entity);
320     }
321
322     for (Entry<String, HashMap<String, String>> geoEntityModel : geoEntityOxmModel.entrySet()) {
323       HashMap<String, String> attribute = geoEntityModel.getValue();
324       OxmEntityDescriptor entity = new OxmEntityDescriptor();
325       entity.setEntityName(attribute.get("entityName"));
326       entity.setPrimaryKeyAttributeName(
327           Arrays.asList(attribute.get("primaryKeyAttributeNames").replace(" ", "").split(",")));
328       entity.setGeoLatName(attribute.get("geoLat"));
329       entity.setGeoLongName(attribute.get("geoLong"));
330       geoEntityDescriptors.put(attribute.get("entityName"), entity);
331     }
332
333     for (Entry<String, HashMap<String, String>> crossRefModel : crossReferenceEntityOxmModel
334         .entrySet()) {
335       HashMap<String, String> attribute = crossRefModel.getValue();
336       OxmEntityDescriptor entity = new OxmEntityDescriptor();
337       entity.setEntityName(attribute.get("entityName"));
338       entity.setPrimaryKeyAttributeName(
339           Arrays.asList(attribute.get("primaryKeyAttributeNames").replace(" ", "").split(",")));
340
341
342       List<String> crossEntityRefTokens =
343           Arrays.asList(attribute.get("crossEntityReference").split(","));
344
345       if (crossEntityRefTokens.size() >= 2) {
346         CrossEntityReference entityRef = new CrossEntityReference();
347         entityRef.setTargetEntityType(crossEntityRefTokens.get(0));
348
349         for (int i = 1; i < crossEntityRefTokens.size(); i++) {
350           entityRef.addReferenceAttribute(crossEntityRefTokens.get(i));
351         }
352
353         entity.setCrossEntityReference(entityRef);
354       }
355       crossReferenceEntityDescriptors.put(attribute.get("entityName"), entity);
356     }
357     
358     for (Entry<String, HashMap<String, String>> suggestionEntityModel :
359         suggestionSearchEntityOxmModel.entrySet()) {
360       HashMap<String, String> attribute = suggestionEntityModel.getValue();
361       
362       String entityName = attribute.get("entityName");
363       SuggestionSearchEntity suggestionSearchEntity = new SuggestionSearchEntity(this);
364       suggestionSearchEntity.setEntityType(entityName);
365       
366       if (attribute.get("suggestionVerbs") != null) {
367         suggestionSearchEntity.setSuggestionConnectorWords(Arrays.asList(
368             attribute.get("suggestionVerbs").split(",")));
369       }
370       
371       if (attribute.get("suggestionAliases") != null) {
372         suggestionSearchEntity.setSuggestionAliases(Arrays.asList(
373             attribute.get("suggestionAliases").split(",")));
374       }
375       
376       if (attribute.get("suggestibleAttributes") != null) {
377         suggestionSearchEntity.setSuggestionPropertyTypes(Arrays.asList(
378             attribute.get("suggestibleAttributes").split(",")));
379       }
380       
381       OxmEntityDescriptor entity = new OxmEntityDescriptor();
382       entity.setSuggestionSearchEntity(suggestionSearchEntity);
383       entity.setEntityName(entityName);
384       
385       if (attribute.get("primaryKeyAttributeNames") != null) {
386         entity.setPrimaryKeyAttributeName(
387             Arrays.asList(attribute.get("primaryKeyAttributeNames").replace(" ", "").split(",")));
388       }
389       
390       suggestionSearchEntityDescriptors.put(entityName, entity);
391     }
392   }
393
394   /**
395    * Find latest oxm version.
396    *
397    * @return the string
398    */
399   public String findLatestOxmVersion() {
400     File[] listOxmFiles = loadOxmFolder().listFiles();
401
402     if (listOxmFiles == null) {
403       return null;
404     }
405
406     Integer latestVersion = -1;
407
408     Pattern oxmFileNamePattern = Pattern.compile("^aai_oxm_v([0-9]*).xml");
409
410     for (File file : listOxmFiles) {
411       if (file.isFile()) {
412         String fileName = file.getName();
413         Matcher matcher = oxmFileNamePattern.matcher(fileName);
414         if (matcher.matches()) {
415           if (latestVersion <= Integer.parseInt(matcher.group(1))) {
416             latestVersion = Integer.parseInt(matcher.group(1));
417           }
418         }
419       }
420
421     }
422     if (latestVersion != -1) {
423       return "v" + latestVersion.toString();
424     } else {
425       return null;
426     }
427
428   }
429
430   /**
431    * Load oxm folder.
432    *
433    * @return the file
434    */
435   public File loadOxmFolder() {
436     return new File(TierSupportUiConstants.CONFIG_OXM_LOCATION);
437   }
438
439   /**
440    * Load oxm file name.
441    *
442    * @param version the version
443    * @return the string
444    */
445   public String loadOxmFileName(String version) {
446     return new String(TierSupportUiConstants.CONFIG_OXM_LOCATION + "aai_oxm_" + version + ".xml");
447   }
448   
449   /*
450    * Get the original representation of the OXM Model
451    */
452   public Map<String, HashMap<String, String>> getOxmModel() {
453     return oxmModel;
454   }
455
456   /*
457    * Get the searchable raw map entity types
458    */
459   public Map<String, HashMap<String, String>> getSearchableOxmModel() {
460     return searchableOxmModel;
461   }
462
463   public Map<String, HashMap<String, String>> getCrossReferenceEntityOxmModel() {
464     return crossReferenceEntityOxmModel;
465   }
466
467   public Map<String, OxmEntityDescriptor> getEntityDescriptors() {
468     return entityDescriptors;
469   }
470
471   /**
472    * Gets the entity descriptor.
473    *
474    * @param type the type
475    * @return the entity descriptor
476    */
477   public OxmEntityDescriptor getEntityDescriptor(String type) {
478     return entityDescriptors.get(type);
479   }
480
481   public Map<String, OxmEntityDescriptor> getSearchableEntityDescriptors() {
482     return searchableEntityDescriptors;
483   }
484
485   /**
486    * Gets the searchable entity descriptor.
487    *
488    * @param entityType the entity type
489    * @return the searchable entity descriptor
490    */
491   public OxmEntityDescriptor getSearchableEntityDescriptor(String entityType) {
492     return searchableEntityDescriptors.get(entityType);
493   }
494
495   public Map<String, OxmEntityDescriptor> getCrossReferenceEntityDescriptors() {
496     return crossReferenceEntityDescriptors;
497   }
498
499   public Map<String, OxmEntityDescriptor> getGeoEntityDescriptors() {
500     return geoEntityDescriptors;
501   }
502   
503   public Map<String, OxmEntityDescriptor> getSuggestionSearchEntityDescriptors() {
504     return suggestionSearchEntityDescriptors;
505   }
506
507   /**
508    * The main method.
509    *
510    * @param args the arguments
511    */
512   public static void main(String[] args) {
513     try {
514       System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/'));
515
516     } catch (IOException exc) {
517       // TODO Auto-generated catch block
518       exc.printStackTrace();
519     }
520     Map<String, OxmEntityDescriptor> temp =
521         OxmModelLoader.getInstance().getSearchableEntityDescriptors();
522     Map<String, OxmEntityDescriptor> temp2 = OxmModelLoader.getInstance().getEntityDescriptors();
523
524     System.out.println("Completed");
525   }
526
527 }