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