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