Merge "Unit/SONAR/Checkstyle in ONAP-REST"
[policy/engine.git] / ONAP-REST / src / main / java / org / onap / policy / rest / util / MSModelUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-REST
4  * ================================================================================
5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
7  * Modifications Copyright (C) 2019 Nordix Foundation.
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
23 package org.onap.policy.rest.util;
24
25 import com.att.research.xacml.util.XACMLProperties;
26 import com.google.gson.Gson;
27 import java.io.File;
28 import java.io.FileInputStream;
29 import java.io.FileNotFoundException;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.Collections;
35 import java.util.HashMap;
36 import java.util.HashSet;
37 import java.util.Iterator;
38 import java.util.LinkedHashMap;
39 import java.util.List;
40 import java.util.Map;
41 import java.util.Map.Entry;
42 import java.util.Set;
43 import org.apache.commons.lang.StringUtils;
44 import org.apache.commons.logging.Log;
45 import org.apache.commons.logging.LogFactory;
46 import org.eclipse.emf.common.util.EList;
47 import org.eclipse.emf.common.util.EMap;
48 import org.eclipse.emf.common.util.Enumerator;
49 import org.eclipse.emf.common.util.TreeIterator;
50 import org.eclipse.emf.common.util.URI;
51 import org.eclipse.emf.ecore.EAnnotation;
52 import org.eclipse.emf.ecore.EClass;
53 import org.eclipse.emf.ecore.EClassifier;
54 import org.eclipse.emf.ecore.EEnum;
55 import org.eclipse.emf.ecore.EEnumLiteral;
56 import org.eclipse.emf.ecore.EObject;
57 import org.eclipse.emf.ecore.EPackage;
58 import org.eclipse.emf.ecore.EReference;
59 import org.eclipse.emf.ecore.EStructuralFeature;
60 import org.eclipse.emf.ecore.impl.EAttributeImpl;
61 import org.eclipse.emf.ecore.impl.EEnumImpl;
62 import org.eclipse.emf.ecore.resource.Resource;
63 import org.eclipse.emf.ecore.resource.ResourceSet;
64 import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
65 import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
66 import org.json.JSONObject;
67 import org.onap.policy.rest.XacmlRestProperties;
68 import org.onap.policy.rest.dao.CommonClassDao;
69 import org.onap.policy.rest.jpa.DictionaryData;
70 import org.yaml.snakeyaml.Yaml;
71
72
73 public class MSModelUtils {
74
75     private static final Log logger = LogFactory.getLog(MSModelUtils.class);
76
77     private HashMap<String, MSAttributeObject> classMap = new HashMap<>();
78     private HashMap<String, String> enumMap = new HashMap<>();
79     private HashMap<String, String> matchingClass = new HashMap<>();
80     private String configuration = "configuration";
81     private String dictionary = "dictionary";
82     private String onap = "";
83     private String policy = "";
84     private String eProxyURI = "eProxyURI:";
85     private List<String> orderedElements = new ArrayList<>();
86     private String dataOrderInfo = "";
87     private Set<String> uniqueDataKeys = new HashSet<>();
88     private Set<String> uniqueKeys = new HashSet<>();
89     private String listConstraints = null;
90     private String referenceAttributes;
91     private LinkedHashMap<String, Object> retmap = new LinkedHashMap<>();
92     private Map<String, String> matchableValues;
93     private static final String PROPERTIES = ".properties.";
94     private static final String DATATYPE = "data_types.policy.data.";
95     private static final String TYPE = ".type";
96     private static final String REQUIRED = ".required";
97     private static final String DICTIONARYNAME = "dictionaryName";
98     private static final String DICTIONARY = "dictionary:";
99     private static final String MATCHABLE = ".matchable";
100     public static final String STRING = "string";
101     public static final String INTEGER = "integer";
102     private static final String BOOLEAN = "boolean";
103     public static final String LIST = "list";
104     public static final String MAP = "map";
105     private static final String DEFAULT = ".default";
106     private static final String MANYFALSE = ":MANY-false";
107     private static final String DESCRIPTION = ".description";
108
109     private static final String MANYTRUE = ":MANY-true";
110     private static final String DEFAULTVALUE = ":defaultValue-";
111     private static final String REQUIREDVALUE = ":required-";
112     private static final String MATCHABLEKEY = "matchable";
113     private static final String REQUIREDFALSE = ":required-false";
114     private static final String REQUIREDTRUE = ":required-true";
115     private static final String MATCHINGTRUE = "matching-true";
116     private static final String DESCRIPTION_KEY = "description";
117     private static final String DESCRIPTION_TOKEN = ":description-";
118     private static final String PROPERTIES_KEY = "properties";
119     private static final String DATA_TYPE = "data_types";
120     private static final String ERROR = "error";
121     private static final String NODE_TYPE = "node_types";
122     private static final String TOSCA_DEFINITION_VERSION = "tosca_definitions_version";
123     private static final String TOSCA_SIMPLE_YAML_1_0_0 = "tosca_simple_yaml_1_0_0";
124     private static final String JSON_MODEL = "JSON_MODEL";
125     private StringBuilder dataListBuffer = new StringBuilder();
126     private List<String> dataConstraints = new ArrayList<>();
127     private String attributeString = null;
128     private boolean isDuplicatedAttributes = false;
129     private String jsonRuleFormation = null;
130
131     private static CommonClassDao commonClassDao;
132
133     public MSModelUtils() {
134         // Default Constructor
135     }
136
137     public MSModelUtils(CommonClassDao commonClassDao) {
138         MSModelUtils.commonClassDao = commonClassDao;
139     }
140
141     public MSModelUtils(String onap, String policy) {
142         this.onap = onap;
143         this.policy = policy;
144     }
145
146     private enum ANNOTATION_TYPE {
147         MATCHING, VALIDATION, DICTIONARY
148     };
149
150     public enum MODEL_TYPE {
151         XMI
152     };
153
154     public enum SearchType {
155         TOSCA_DEFINITION_VERSION, TOSCA_SIMPLE_YAML_1_0_0, NODE_TYPE, DATA_TYPE, JSON_MODEL
156     }
157
158     public Map<String, MSAttributeObject> processEpackage(String file, MODEL_TYPE model) {
159         if (model == MODEL_TYPE.XMI) {
160             processXMIEpackage(file);
161         }
162         return classMap;
163
164     }
165
166     private void processXMIEpackage(String xmiFile) {
167         EPackage root = getEpackage(xmiFile);
168         TreeIterator<EObject> treeItr = root.eAllContents();
169         String className;
170         String returnValue;
171
172         // Pulling out dependency from file
173         while (treeItr.hasNext()) {
174             EObject obj = treeItr.next();
175             if (obj instanceof EClassifier) {
176                 EClassifier eClassifier = (EClassifier) obj;
177                 className = eClassifier.getName();
178
179                 if (obj instanceof EEnum) {
180                     enumMap.putAll(getEEnum(obj));
181                 } else if (obj instanceof EClass) {
182                     String temp = getDependencyList(eClassifier).toString();
183                     returnValue = StringUtils.replaceEach(temp, new String[] {"[", "]"}, new String[] {"", ""});
184                     getAttributes(className, returnValue, root);
185                 }
186             }
187         }
188
189         if (!enumMap.isEmpty()) {
190             addEnumClassMap();
191         }
192         if (!matchingClass.isEmpty()) {
193             checkForMatchingClass();
194         }
195     }
196
197     private void checkForMatchingClass() {
198         HashMap<String, String> tempAttribute = new HashMap<>();
199
200         for (Entry<String, String> set : matchingClass.entrySet()) {
201             String key = set.getKey();
202             if (classMap.containsKey(key)) {
203                 Map<String, String> listAttributes = classMap.get(key).getAttribute();
204                 Map<String, String> listRef = classMap.get(key).getRefAttribute();
205                 for (Entry<String, String> eSet : listAttributes.entrySet()) {
206                     String key2 = eSet.getKey();
207                     tempAttribute.put(key2, MATCHINGTRUE);
208                 }
209                 for (Entry<String, String> eSet : listRef.entrySet()) {
210                     String key3 = eSet.getKey();
211                     tempAttribute.put(key3, MATCHINGTRUE);
212                 }
213
214             }
215             updateMatching(tempAttribute, key);
216         }
217
218     }
219
220
221
222     private void updateMatching(HashMap<String, String> tempAttribute, String key) {
223         Map<String, MSAttributeObject> newClass = classMap;
224
225         for (Entry<String, MSAttributeObject> updateClass : newClass.entrySet()) {
226             Map<String, String> valueMap = updateClass.getValue().getMatchingSet();
227             String keymap = updateClass.getKey();
228             if (valueMap.containsKey(key)) {
229                 Map<String, String> modifyMap = classMap.get(keymap).getMatchingSet();
230                 modifyMap.remove(key);
231                 modifyMap.putAll(tempAttribute);
232                 classMap.get(keymap).setMatchingSet(modifyMap);
233             }
234
235         }
236     }
237
238     private void addEnumClassMap() {
239         for (Entry<String, MSAttributeObject> value : classMap.entrySet()) {
240             value.getValue().setEnumType(enumMap);
241         }
242     }
243
244     private EPackage getEpackage(String xmiFile) {
245         ResourceSet resSet = new ResourceSetImpl();
246         Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
247         Map<String, Object> m = reg.getExtensionToFactoryMap();
248         m.put("xmi", new XMIResourceFactoryImpl());
249         Resource resource = resSet.getResource(URI.createFileURI(xmiFile), true);
250         try {
251             resource.load(Collections.emptyMap());
252         } catch (IOException e) {
253             logger.error("Error loading Encore Resource for new Model" + e);
254         }
255
256         return (EPackage) resource.getContents().get(0);
257     }
258
259     private HashMap<String, String> getEEnum(EObject obj) {
260         List<String> valueList = new ArrayList<>();
261         HashMap<String, String> returnMap = new HashMap<>();
262         EEnum eenum = (EEnum) obj;
263
264         String name = eenum.getName();
265         for (EEnumLiteral eEnumLiteral : eenum.getELiterals()) {
266             Enumerator instance = eEnumLiteral.getInstance();
267             String value = instance.getLiteral();
268             valueList.add(value);
269         }
270         returnMap.put(name, valueList.toString());
271         return returnMap;
272     }
273
274     public void getAttributes(String className, String dependency, EPackage root) {
275         List<String> dpendList = new ArrayList<>();
276         if (dependency != null) {
277             dpendList = new ArrayList<>(Arrays.asList(dependency.split(",")));
278         }
279         MSAttributeObject msAttributeObject = new MSAttributeObject();
280         msAttributeObject.setClassName(className);
281         String extendClass = getSubTypes(root, className);
282         Map<String, String> returnRefList = getRefAttributeList(root, className, extendClass);
283         Map<String, String> returnAttributeList = getAttributeList(root, className, extendClass);
284         Map<String, Object> returnSubList = getSubAttributeList(root, className, extendClass);
285         HashMap<String, String> returnAnnotation = getAnnotation(root, className, extendClass);
286         msAttributeObject.setAttribute(returnAttributeList);
287         msAttributeObject.setRefAttribute(returnRefList);
288         msAttributeObject.setSubClass(returnSubList);
289         msAttributeObject.setDependency(dpendList.toString());
290         msAttributeObject.addMatchingSet(returnAnnotation);
291         msAttributeObject.setPolicyTempalate(isPolicyTemplate(root, className));
292
293         this.classMap.put(className, msAttributeObject);
294     }
295
296     private HashMap<String, String> getAnnotation(EPackage root, String className, String extendClass) {
297         TreeIterator<EObject> treeItr = root.eAllContents();
298         boolean requiredAttribute = false;
299         boolean requiredMatchAttribute = false;
300         HashMap<String, String> annotationSet = new HashMap<>();
301
302         // Pulling out dependency from file
303         while (treeItr.hasNext()) {
304             EObject obj = treeItr.next();
305             if (obj instanceof EClassifier) {
306                 requiredAttribute = isRequiredAttribute(obj, className);
307                 requiredMatchAttribute = isRequiredAttribute(obj, extendClass);
308             }
309
310             if (requiredAttribute) {
311                 if (obj instanceof EStructuralFeature) {
312                     checkAnnotation(annotationSet, (EStructuralFeature) obj);
313                 }
314             } else if (requiredMatchAttribute && (obj instanceof EStructuralFeature)) {
315                 findMatchingAnnotation(annotationSet, obj);
316             }
317         }
318         return annotationSet;
319     }
320
321     private void findMatchingAnnotation(HashMap<String, String> annotationSet, EObject obj) {
322         EStructuralFeature eStrucClassifier = (EStructuralFeature) obj;
323         if (eStrucClassifier.getEAnnotations().isEmpty()) {
324             return;
325         }
326         String matching = annotationValue(eStrucClassifier, ANNOTATION_TYPE.MATCHING, policy);
327         if (matching != null) {
328             if (obj instanceof EReference) {
329                 EClass refType = ((EReference) obj).getEReferenceType();
330                 annotationSet.put(refType.getName(), matching);
331                 matchingClass.put(refType.getName(), matching);
332             } else {
333                 annotationSet.put(eStrucClassifier.getName(), matching);
334             }
335         }
336
337     }
338
339     private void checkAnnotation(HashMap<String, String> annotationSet, EStructuralFeature obj) {
340         EStructuralFeature eStrucClassifier = obj;
341         if (eStrucClassifier.getEAnnotations().isEmpty()) {
342             return;
343         }
344         String matching = annotationValue(eStrucClassifier, ANNOTATION_TYPE.MATCHING, policy);
345         if (matching != null) {
346             annotationSet.put(eStrucClassifier.getName(), matching);
347         }
348         String range = annotationValue(eStrucClassifier, ANNOTATION_TYPE.VALIDATION, policy);
349         if (range != null) {
350             annotationSet.put(eStrucClassifier.getName(), range);
351         }
352         String annotationDict = annotationValue(eStrucClassifier, ANNOTATION_TYPE.DICTIONARY, policy);
353         if (annotationDict != null) {
354             annotationSet.put(eStrucClassifier.getName(), annotationDict);
355         }
356     }
357
358     private Map<String, Object> getSubAttributeList(EPackage root, String className, String superClass) {
359         TreeIterator<EObject> treeItr = root.eAllContents();
360         boolean requiredAttribute = false;
361         Map<String, Object> subAttribute = new HashMap<>();
362         int rollingCount = 0;
363         int processClass = 0;
364
365         // Pulling out dependency from file
366         while (treeItr.hasNext() && rollingCount < 2) {
367
368             EObject obj = treeItr.next();
369             if (obj instanceof EClassifier) {
370                 requiredAttribute = isRequiredAttribute(obj, className) || isRequiredAttribute(obj, superClass);
371                 if (requiredAttribute) {
372                     processClass++;
373                 }
374                 rollingCount = rollingCount + processClass;
375             }
376
377             if (requiredAttribute && (obj instanceof EStructuralFeature)) {
378                 EStructuralFeature eStrucClassifier = (EStructuralFeature) obj;
379                 if (!eStrucClassifier.getEAnnotations().isEmpty()) {
380                     updateSubAttributes(subAttribute, obj, eStrucClassifier);
381                 }
382             }
383         }
384         return subAttribute;
385     }
386
387     private void updateSubAttributes(Map<String, Object> subAttribute, EObject obj,
388             EStructuralFeature eStrucClassifier) {
389         if (!(obj instanceof EReference)) {
390             return;
391         }
392         if (annotationTest(eStrucClassifier, configuration, onap)) {
393             EClass refType = ((EReference) obj).getEReferenceType();
394             if (!refType.toString().contains(eProxyURI)) {
395                 String required = REQUIREDFALSE;
396                 if (eStrucClassifier.getLowerBound() == 1) {
397                     required = REQUIREDTRUE;
398                 }
399                 subAttribute.put(eStrucClassifier.getName(), refType.getName() + required);
400             }
401         }
402     }
403
404     public String checkDefultValue(String defultValue) {
405         if (defultValue != null) {
406             return DEFAULTVALUE + defultValue;
407         }
408         return ":defaultValue-NA";
409
410     }
411
412     public String checkRequiredPattern(int upper, int lower) {
413         String pattern = XACMLProperties.getProperty(XacmlRestProperties.PROP_XCORE_REQUIRED_PATTERN);
414         if (pattern != null && upper == Integer.parseInt(pattern.split(",")[1])
415                 && lower == Integer.parseInt(pattern.split(",")[0])) {
416             return REQUIREDTRUE;
417         }
418         return REQUIREDFALSE;
419     }
420
421     public JSONObject buildJavaObject(Map<String, String> map) {
422         return new JSONObject(map);
423     }
424
425     public Map<String, String> getRefAttributeList(EPackage root, String className, String superClass) {
426
427         TreeIterator<EObject> treeItr = root.eAllContents();
428         boolean requiredAttribute = false;
429         HashMap<String, String> refAttribute = new HashMap<>();
430         int rollingCount = 0;
431         int processClass = 0;
432         boolean annotation;
433         // Pulling out dependency from file
434         while (treeItr.hasNext()) {
435             EObject obj = treeItr.next();
436             if (obj instanceof EClassifier) {
437                 requiredAttribute = isRequiredAttribute(obj, className) || isRequiredAttribute(obj, superClass);
438                 if (requiredAttribute) {
439                     processClass++;
440                 }
441                 rollingCount = rollingCount + processClass;
442             }
443
444             if (requiredAttribute && (obj instanceof EStructuralFeature)) {
445                 EStructuralFeature eStrucClassifier = (EStructuralFeature) obj;
446                 if (!eStrucClassifier.getEAnnotations().isEmpty()) {
447                     annotation = annotationTest(eStrucClassifier, configuration, onap);
448                     if (annotation && obj instanceof EReference) {
449                         updRefAttributes(refAttribute, (EStructuralFeature) obj, eStrucClassifier);
450                     } else if (annotation && obj instanceof EAttributeImpl) {
451                         updEnumTypeRefAttrib(refAttribute, (EStructuralFeature) obj, eStrucClassifier);
452                     }
453                 }
454             }
455         }
456
457         return refAttribute;
458     }
459
460     private void updEnumTypeRefAttrib(HashMap<String, String> refAttribute, EStructuralFeature obj,
461             EStructuralFeature eStrucClassifier) {
462         EClassifier refType = ((EAttributeImpl) obj).getEType();
463         if (!(refType instanceof EEnumImpl)) {
464             return;
465         }
466
467         String array = arrayCheck(obj.getUpperBound());
468         String required = REQUIREDFALSE;
469         if (obj.getLowerBound() == 1) {
470             required = REQUIREDTRUE;
471         }
472         refAttribute.put(eStrucClassifier.getName(), refType.getName() + array + required);
473     }
474
475     private void updRefAttributes(HashMap<String, String> refAttribute, EStructuralFeature obj,
476             EStructuralFeature eStrucClassifier) {
477         EClass refType = ((EReference) obj).getEReferenceType();
478         if (refType.toString().contains(eProxyURI)) {
479             String one = refType.toString().split(eProxyURI)[1];
480             String refValue =
481                     StringUtils.replaceEach(one.split("#")[1], new String[] {"//", ")"}, new String[] {"", ""});
482             refAttribute.put(eStrucClassifier.getName(), refValue);
483         } else {
484             String required = REQUIREDFALSE;
485             if (obj.getLowerBound() == 1) {
486                 required = REQUIREDTRUE;
487             }
488             refAttribute.put(eStrucClassifier.getName(),
489                     refType.getName() + arrayCheck(obj.getUpperBound()) + required);
490         }
491     }
492
493     private boolean annotationTest(EStructuralFeature eStrucClassifier, String annotation, String type) {
494         String annotationType;
495         EAnnotation eAnnotation;
496         String onapType;
497         String onapValue;
498
499         EList<EAnnotation> value = eStrucClassifier.getEAnnotations();
500
501         for (int i = 0; i < value.size(); i++) {
502             annotationType = value.get(i).getSource();
503             eAnnotation = eStrucClassifier.getEAnnotations().get(i);
504             onapType = eAnnotation.getDetails().get(0).getValue();
505             onapValue = eAnnotation.getDetails().get(0).getKey();
506
507             if (annotationType.contains(type) && onapType.contains(annotation)) {
508                 return true;
509             }
510
511             if (annotationType.contains(type) && onapValue.contains(annotation)) {
512                 return true;
513             }
514         }
515
516         return false;
517     }
518
519
520     private String annotationValue(EStructuralFeature eStrucClassifier, ANNOTATION_TYPE annotation, String type) {
521         String annotationType;
522         EAnnotation eAnnotation;
523         String onapType;
524         String onapValue = null;
525
526         EList<EAnnotation> value = eStrucClassifier.getEAnnotations();
527
528         for (int i = 0; i < value.size(); i++) {
529             annotationType = value.get(i).getSource();
530             eAnnotation = eStrucClassifier.getEAnnotations().get(i);
531             onapType = eAnnotation.getDetails().get(0).getKey();
532             if (annotationType.contains(type) && onapType.compareToIgnoreCase(annotation.toString()) == 0) {
533                 onapValue = eAnnotation.getDetails().get(0).getValue();
534                 if (annotation == ANNOTATION_TYPE.VALIDATION) {
535                     return onapValue;
536                 } else {
537                     return onapType + "-" + onapValue;
538                 }
539             }
540         }
541
542         return onapValue;
543     }
544
545     public boolean isRequiredAttribute(EObject obj, String className) {
546         EClassifier eClassifier = (EClassifier) obj;
547         String workingClass = eClassifier.getName().trim();
548         if (workingClass.equalsIgnoreCase(className)) {
549             return true;
550         }
551
552         return false;
553     }
554
555     private boolean isPolicyTemplate(EPackage root, String className) {
556         boolean result = false;
557         for (EClassifier classifier : root.getEClassifiers()) {
558             if (classifier instanceof EClass) {
559                 EClass eClass = (EClass) classifier;
560                 if (eClass.getName().contentEquals(className)) {
561                     result = checkPolicyTemplate(eClass);
562                     break;
563                 }
564             }
565         }
566         return result;
567     }
568
569     private boolean checkPolicyTemplate(EClass eClass) {
570         EList<EAnnotation> value = eClass.getEAnnotations();
571         for (EAnnotation workingValue : value) {
572             EMap<String, String> keyMap = workingValue.getDetails();
573             if (keyMap.containsKey("policyTemplate")) {
574                 return true;
575             }
576         }
577         return false;
578     }
579
580     private String getSubTypes(EPackage root, String className) {
581         String returnSubTypes = null;
582         for (EClassifier classifier : root.getEClassifiers()) {
583             if (classifier instanceof EClass) {
584                 returnSubTypes = findSubTypes(className, returnSubTypes, (EClass) classifier);
585             }
586         }
587         return returnSubTypes;
588     }
589
590     private String findSubTypes(String className, String returnSubTypes, EClass classifier) {
591         EClass eClass = classifier;
592
593         for (EClass eSuperType : eClass.getEAllSuperTypes()) {
594             if (eClass.getName().contentEquals(className)) {
595                 returnSubTypes = eSuperType.getName();
596             }
597         }
598         return returnSubTypes;
599     }
600
601     public Map<String, String> getAttributeList(EPackage root, String className, String superClass) {
602
603         TreeIterator<EObject> treeItr = root.eAllContents();
604         boolean requiredAttribute = false;
605         HashMap<String, String> refAttribute = new HashMap<>();
606
607         // Pulling out dependency from file
608         while (treeItr.hasNext()) {
609             EObject obj = treeItr.next();
610             if (obj instanceof EClassifier) {
611                 requiredAttribute = isRequiredAttribute(obj, className) || isRequiredAttribute(obj, superClass);
612             }
613
614             if (requiredAttribute && (obj instanceof EStructuralFeature)) {
615                 EStructuralFeature eStrucClassifier = (EStructuralFeature) obj;
616                 if (!eStrucClassifier.getEAnnotations().isEmpty()) {
617                     checkStrucClassifier(refAttribute, obj, eStrucClassifier);
618                 }
619             }
620         }
621         return refAttribute;
622
623     }
624
625     private void checkStrucClassifier(HashMap<String, String> refAttribute, EObject obj,
626             EStructuralFeature eStrucClassifier) {
627         EClassifier refType = ((EStructuralFeature) obj).getEType();
628         boolean annotation = annotationTest(eStrucClassifier, configuration, onap);
629         boolean dictionaryTest = annotationTest(eStrucClassifier, dictionary, policy);
630         if (annotation && !(obj instanceof EReference) && !(refType instanceof EEnumImpl)) {
631             updEReferenceAttrib(refAttribute, dictionaryTest, (EStructuralFeature) obj, eStrucClassifier);
632         }
633     }
634
635     private void updEReferenceAttrib(HashMap<String, String> refAttribute, boolean dictionaryTest,
636             EStructuralFeature obj, EStructuralFeature eStrucClassifier) {
637         String eType;
638         String name = eStrucClassifier.getName();
639         if (dictionaryTest) {
640             eType = annotationValue(eStrucClassifier, ANNOTATION_TYPE.DICTIONARY, policy);
641         } else {
642             eType = eStrucClassifier.getEType().getInstanceClassName();
643         }
644         String defaultValue = checkDefultValue(obj.getDefaultValueLiteral());
645         String array = arrayCheck(obj.getUpperBound());
646         String required = checkRequiredPattern(obj.getUpperBound(), obj.getLowerBound());
647         refAttribute.put(name, eType + defaultValue + required + array);
648     }
649
650     public String arrayCheck(int upperBound) {
651
652         if (upperBound == -1) {
653             return MANYTRUE;
654         }
655
656         return MANYFALSE;
657     }
658
659     public List<String> getDependencyList(EClassifier eClassifier) {
660         List<String> returnValue = new ArrayList<>();;
661         EList<EClass> somelist = ((EClass) eClassifier).getEAllSuperTypes();
662         if (somelist.isEmpty()) {
663             return returnValue;
664         }
665         for (EClass depend : somelist) {
666             if (depend.toString().contains(eProxyURI)) {
667                 String one = depend.toString().split(eProxyURI)[1];
668                 String value =
669                         StringUtils.replaceEach(one.split("#")[1], new String[] {"//", ")"}, new String[] {"", ""});
670                 returnValue.add(value);
671             }
672         }
673
674         return returnValue;
675     }
676
677     public Map<String, String> buildSubList(Map<String, String> subClassAttributes,
678             Map<String, MSAttributeObject> classMap, String className) {
679         Map<String, String> missingValues = new HashMap<>();
680         Map<String, String> workingMap;
681         boolean enumType;
682
683         for (Entry<String, String> map : classMap.get(className).getRefAttribute().entrySet()) {
684             String value = map.getValue().split(":")[0];
685             if (value != null) {
686                 classMap.get(className).getEnumType();
687                 enumType = classMap.get(className).getEnumType().containsKey(value);
688                 if (!enumType) {
689                     workingMap = classMap.get(value).getRefAttribute();
690                     for (Entry<String, String> subMab : workingMap.entrySet()) {
691                         String value2 = subMab.getValue().split(":")[0];
692                         if (!subClassAttributes.containsValue(value2)) {
693                             missingValues.put(subMab.getKey(), subMab.getValue());
694                         }
695                     }
696
697                 }
698             }
699         }
700
701         return missingValues;
702     }
703
704     public Map<String, Map<String, String>> recursiveReference(Map<String, MSAttributeObject> classMap,
705             String className) {
706
707         Map<String, Map<String, String>> returnObject = new HashMap<>();
708         Map<String, String> returnClass = getRefclass(classMap, className);
709         returnObject.put(className, returnClass);
710         for (Entry<String, String> reAttribute : returnClass.entrySet()) {
711             if (reAttribute.getValue().split(":")[1].contains("MANY")
712                     && classMap.get(reAttribute.getValue().split(":")[0]) != null) {
713                 returnObject.putAll(recursiveReference(classMap, reAttribute.getValue().split(":")[0]));
714             }
715
716         }
717
718         return returnObject;
719
720     }
721
722     public String createJson(Map<String, MSAttributeObject> classMap, String className) {
723         boolean enumType;
724         Map<String, Map<String, String>> myObject = new HashMap<>();
725         for (Entry<String, String> map : classMap.get(className).getRefAttribute().entrySet()) {
726             String value = map.getValue().split(":")[0];
727             if (value != null) {
728                 enumType = classMap.get(className).getEnumType().containsKey(value);
729                 if (!enumType && map.getValue().split(":")[1].contains("MANY")) {
730                     Map<String, Map<String, String>> testRecursive =
731                             recursiveReference(classMap, map.getValue().split(":")[0]);
732                     myObject.putAll(testRecursive);
733                 }
734             }
735         }
736
737         Gson gson = new Gson();
738         return gson.toJson(myObject);
739     }
740
741     public Map<String, String> getRefclass(Map<String, MSAttributeObject> classMap, String className) {
742         HashMap<String, String> missingValues = new HashMap<>();
743
744         if (classMap.get(className).getAttribute() != null || !classMap.get(className).getAttribute().isEmpty()) {
745             missingValues.putAll(classMap.get(className).getAttribute());
746         }
747
748         if (classMap.get(className).getRefAttribute() != null || !classMap.get(className).getRefAttribute().isEmpty()) {
749             missingValues.putAll(classMap.get(className).getRefAttribute());
750         }
751
752         return missingValues;
753     }
754
755     public String createSubAttributes(List<String> dependency, Map<String, MSAttributeObject> classMap,
756             String modelName) {
757
758         HashMap<String, Object> workingMap = new HashMap<>();
759         MSAttributeObject tempObject;
760         if (dependency != null) {
761             if (dependency.isEmpty()) {
762                 return "{}";
763             }
764             dependency.add(modelName);
765             for (String element : dependency) {
766                 tempObject = classMap.get(element);
767                 if (tempObject != null) {
768                     workingMap.putAll(classMap.get(element).getSubClass());
769                 }
770             }
771         }
772
773         return createJson(classMap, modelName);
774     }
775
776     public List<String> getFullDependencyList(List<String> dependency, Map<String, MSAttributeObject> classMap) {
777         ArrayList<String> returnList = new ArrayList<>();
778         ArrayList<String> workingList;
779         returnList.addAll(dependency);
780         for (String element : dependency) {
781             if (classMap.containsKey(element)) {
782                 MSAttributeObject value = classMap.get(element);
783                 String rawValue =
784                         StringUtils.replaceEach(value.getDependency(), new String[] {"[", "]"}, new String[] {"", ""});
785                 workingList = new ArrayList<>(Arrays.asList(rawValue.split(",")));
786                 for (String depend : workingList) {
787                     updDependencyList(returnList, depend);
788                 }
789             }
790         }
791
792         return returnList;
793     }
794
795     private void updDependencyList(ArrayList<String> returnList, String depend) {
796         if (!returnList.contains(depend) && !depend.isEmpty()) {
797             returnList.add(depend.trim());
798         }
799     }
800
801     /*
802      * For TOSCA Model
803      */
804     public String parseTosca(String fileName) {
805         Map<String, String> map = new LinkedHashMap<>();
806         try {
807             map = load(fileName);
808             if (map != null && map.get(ERROR) != null) {
809                 return map.get(ERROR);
810             }
811             parseDataAndPolicyNodes(map);
812             LinkedHashMap<String, String> dataMapForJson = parseDataNodes(map);
813             constructJsonForDataFields(dataMapForJson);
814             LinkedHashMap<String, LinkedHashMap<String, String>> mapKey = parsePolicyNodes(map);
815             createAttributes(mapKey);
816
817         } catch (IOException e) {
818             logger.error(e);
819         } catch (ParserException e) {
820             logger.error(e);
821             return e.getMessage();
822         }
823
824         return null;
825     }
826
827     @SuppressWarnings("unchecked")
828     public Map<String, String> load(String fileName) throws IOException, ParserException {
829         File newConfiguration = new File(fileName);
830         StringBuilder orderInfo = new StringBuilder("[");
831         Yaml yaml = new Yaml();
832         LinkedHashMap<Object, Object> yamlMap = null;
833         try (InputStream is = new FileInputStream(newConfiguration)) {
834             yamlMap = (LinkedHashMap<Object, Object>) yaml.load(is);
835         } catch (FileNotFoundException e) {
836             logger.error(e);
837         } catch (Exception e) {
838             logger.error(e);
839             throw new ParserException("Invalid TOSCA Model format. Please make sure it is a valid YAML file");
840         }
841
842         StringBuilder sb = new StringBuilder();
843         LinkedHashMap<String, String> settings = new LinkedHashMap<>();
844         if (yamlMap == null) {
845             return settings;
846         }
847
848         String message = validations(yamlMap);
849
850         if (message != null) {
851             settings.put(ERROR, message);
852             return settings;
853         }
854
855         findNode(yamlMap);
856
857         if (!isDuplicatedAttributes && orderedElements != null && !orderedElements.isEmpty()) {
858             orderedElements.stream().forEach(string -> {
859                 orderInfo.append(string);
860                 orderInfo.append(",");
861                 logger.info("Content: " + string);
862             });
863
864             orderInfo.append("]");
865
866             dataOrderInfo = orderInfo.toString();
867             dataOrderInfo = dataOrderInfo.replace(",]", "]");
868
869             logger.info("dataOrderInfo :" + dataOrderInfo);
870         }
871
872         List<String> path = new ArrayList<>();
873         serializeMap(settings, sb, path, yamlMap);
874         return settings;
875     }
876
877     @SuppressWarnings("unchecked")
878     private String validations(@SuppressWarnings("rawtypes") Map yamlMap) {
879
880         boolean isNoteTypeFound = false;
881         boolean isDataTypeFound = false;
882         boolean isToscaVersionKeyFound = false;
883         boolean isToscaVersionValueFound = false;
884         @SuppressWarnings("rawtypes")
885         Map m1 = new HashMap();
886         short order = 0;
887         if (yamlMap != null) {
888             // Get a set of the entries
889             @SuppressWarnings("rawtypes")
890             Set<Entry> entries = yamlMap.entrySet();
891             for (@SuppressWarnings("rawtypes")
892                 Map.Entry me : entries) {
893                 if (TOSCA_SIMPLE_YAML_1_0_0.equals(me.getValue())) {
894                     isToscaVersionValueFound = true;
895                 }
896
897                 switch (me.getKey().toString()) {
898                     case TOSCA_DEFINITION_VERSION:
899                         isToscaVersionKeyFound = true;
900                         order++;
901                         m1.put(TOSCA_DEFINITION_VERSION, order);
902                         break;
903                     case NODE_TYPE:
904                         isNoteTypeFound = true;
905                         order++;
906                         m1.put(NODE_TYPE, order);
907                         break;
908                     case DATA_TYPE:
909                         isDataTypeFound = true;
910                         order++;
911                         m1.put(DATA_TYPE, order);
912                         break;
913                     case JSON_MODEL:
914                         setJsonRuleFormation(me.getValue().toString());
915                         break;
916                     default:
917                         break;
918                 }
919             }
920             if (!isDataTypeFound) {
921                 return "data_types are missing or invalid.";
922             }
923             if (!isToscaVersionKeyFound || !isToscaVersionValueFound) {
924                 return "tosca_definitions_version is missing or invalid.";
925             }
926
927             if (!isNoteTypeFound) {
928                 return "node_types are missing or invalid.";
929             }
930
931             short version = (short) m1.get(TOSCA_DEFINITION_VERSION);
932
933             if (version > 1) {
934                 return "tosca_definitions_version should be defined first.";
935             }
936
937             short data = (short) m1.get(DATA_TYPE);
938             short node = (short) m1.get(NODE_TYPE);
939             if (isDataTypeFound && node > data) {
940                 return "node_types should be defined before data_types.";
941             }
942
943         }
944
945         return null;
946     }
947
948     @SuppressWarnings({"unchecked", "rawtypes"})
949     private void serializeMap(LinkedHashMap<String, String> settings, StringBuilder sb, List<String> path,
950             Map<Object, Object> yamlMap) {
951         for (Map.Entry<Object, Object> entry : yamlMap.entrySet()) {
952
953             if (entry.getValue() instanceof Map) {
954                 path.add((String) entry.getKey());
955                 serializeMap(settings, sb, path, (Map<Object, Object>) entry.getValue());
956                 path.remove(path.size() - 1);
957             } else if (entry.getValue() instanceof List) {
958                 path.add((String) entry.getKey());
959                 serializeList(settings, sb, path, (List) entry.getValue());
960                 path.remove(path.size() - 1);
961             } else {
962                 serializeValue(settings, sb, path, (String) entry.getKey(), entry.getValue());
963             }
964         }
965     }
966
967     @SuppressWarnings("unchecked")
968     private void serializeList(LinkedHashMap<String, String> settings, StringBuilder sb, List<String> path,
969             List<String> yamlList) {
970         int counter = 0;
971         for (Object listEle : yamlList) {
972             if (listEle instanceof Map) {
973                 path.add(Integer.toString(counter));
974                 serializeMap(settings, sb, path, (Map<Object, Object>) listEle);
975                 path.remove(path.size() - 1);
976             } else if (listEle instanceof List) {
977                 path.add(Integer.toString(counter));
978                 serializeList(settings, sb, path, (List<String>) listEle);
979                 path.remove(path.size() - 1);
980             } else {
981                 serializeValue(settings, sb, path, Integer.toString(counter), listEle);
982             }
983             counter++;
984         }
985     }
986
987     private void serializeValue(LinkedHashMap<String, String> settings, StringBuilder sb, List<String> path,
988             String name, Object value) {
989         if (value == null) {
990             return;
991         }
992         sb.setLength(0);
993         for (String pathEle : path) {
994             sb.append(pathEle).append('.');
995         }
996         sb.append(name);
997         settings.put(sb.toString(), value.toString());
998     }
999
1000
1001     void parseDataAndPolicyNodes(Map<String, String> map) {
1002         for (String key : map.keySet()) {
1003             if (key.contains("policy.nodes.Root")) {
1004                 continue;
1005             } else if (key.contains("policy.nodes")) {
1006                 String wordToFind = "policy.nodes.";
1007                 int indexForPolicyNode = key.indexOf(wordToFind);
1008                 String subNodeString = key.substring(indexForPolicyNode + 13, key.length());
1009
1010                 stringBetweenDots(subNodeString);
1011             } else if (key.contains("policy.data")) {
1012                 String wordToFind = "policy.data.";
1013                 int indexForPolicyNode = key.indexOf(wordToFind);
1014                 String subNodeString = key.substring(indexForPolicyNode + 12, key.length());
1015
1016                 stringBetweenDotsForDataFields(subNodeString);
1017             }
1018         }
1019     }
1020
1021     // Second index of dot should be returned.
1022     public int stringBetweenDots(String str) {
1023         String stringToSearch = str;
1024         String[] ss = stringToSearch.split("\\.");
1025         if (ss != null) {
1026             int len = ss.length;
1027             if (len > 2) {
1028                 uniqueKeys.add(ss[2]);
1029             }
1030         }
1031
1032         return uniqueKeys.size();
1033     }
1034
1035
1036     public void stringBetweenDotsForDataFields(String str) {
1037         String stringToSearch = str;
1038         String[] ss = stringToSearch.split("\\.");
1039         if (ss != null) {
1040             int len = ss.length;
1041
1042             if (len > 2) {
1043                 uniqueDataKeys.add(ss[0] + "%" + ss[2]);
1044             }
1045         }
1046     }
1047
1048     void constructJsonForDataFields(LinkedHashMap<String, String> dataMapForJson) {
1049         LinkedHashMap<String, LinkedHashMap<String, String>> dataMapKey = new LinkedHashMap<>();
1050         LinkedHashMap<String, String> hmSub;
1051         for (Map.Entry<String, String> entry : dataMapForJson.entrySet()) {
1052             String uniqueDataKey = entry.getKey();
1053             String[] uniqueDataKeySplit = uniqueDataKey.split("%");
1054             String value = dataMapForJson.get(uniqueDataKey);
1055             if (dataMapKey.containsKey(uniqueDataKeySplit[0])) {
1056                 hmSub = dataMapKey.get(uniqueDataKeySplit[0]);
1057                 hmSub.put(uniqueDataKeySplit[1], value);
1058             } else {
1059                 hmSub = new LinkedHashMap<>();
1060                 hmSub.put(uniqueDataKeySplit[1], value);
1061             }
1062
1063             dataMapKey.put(uniqueDataKeySplit[0], hmSub);
1064         }
1065
1066         JSONObject mainObject = new JSONObject();
1067         JSONObject json;
1068         for (Map.Entry<String, LinkedHashMap<String, String>> entry : dataMapKey.entrySet()) {
1069             String s = entry.getKey();
1070             json = new JSONObject();
1071             HashMap<String, String> jsonHm = dataMapKey.get(s);
1072             for (Map.Entry<String, String> entryMap : jsonHm.entrySet()) {
1073                 String key = entryMap.getKey();
1074                 json.put(key, jsonHm.get(key));
1075             }
1076             mainObject.put(s, json);
1077         }
1078         Iterator<String> keysItr = mainObject.keys();
1079         while (keysItr.hasNext()) {
1080             String key = keysItr.next();
1081             String value = mainObject.get(key).toString();
1082             retmap.put(key, value);
1083         }
1084
1085         logger.info("#############################################################################");
1086         logger.info(mainObject);
1087         logger.info("###############################################################################");
1088     }
1089
1090     LinkedHashMap<String, String> parseDataNodes(Map<String, String> map) {
1091         LinkedHashMap<String, String> dataMapForJson = new LinkedHashMap<>();
1092         matchableValues = new HashMap<>();
1093         for (String uniqueDataKey : uniqueDataKeys) {
1094             if (uniqueDataKey.contains("%")) {
1095                 String[] uniqueDataKeySplit = uniqueDataKey.split("%");
1096                 String findType = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] + TYPE;
1097                 String typeValue = map.get(findType);
1098                 logger.info(typeValue);
1099
1100                 String findRequired = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] + REQUIRED;
1101                 String requiredValue = map.get(findRequired);
1102
1103                 String matchable = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] + MATCHABLE;
1104
1105                 String matchableValue = map.get(matchable);
1106
1107                 if ("true".equalsIgnoreCase(matchableValue)) {
1108                     String key = uniqueDataKeySplit[uniqueDataKeySplit.length - 1];
1109                     matchableValues.put(key, MATCHINGTRUE);
1110                 }
1111
1112                 if (requiredValue == null || requiredValue.isEmpty()) {
1113                     requiredValue = "false";
1114                 }
1115                 if (INTEGER.equalsIgnoreCase(typeValue) || STRING.equalsIgnoreCase(typeValue)
1116                         || typeValue.equalsIgnoreCase(BOOLEAN)) {
1117                     String findDefault =
1118                             DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] + DEFAULT;
1119                     String findDescription =
1120                             DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] + DESCRIPTION;
1121                     String defaultValue = map.get(findDefault);
1122                     String descriptionDefined = map.get(findDescription);
1123                     logger.info("defaultValue is:" + defaultValue);
1124                     logger.info("requiredValue is:" + requiredValue);
1125
1126                     StringBuilder attributeIndividualStringBuilder = new StringBuilder();
1127                     attributeIndividualStringBuilder.append(typeValue + DEFAULTVALUE);
1128                     attributeIndividualStringBuilder.append(defaultValue + REQUIREDVALUE);
1129                     attributeIndividualStringBuilder.append(requiredValue + MANYFALSE);
1130                     attributeIndividualStringBuilder.append(DESCRIPTION_TOKEN + descriptionDefined);
1131                     dataMapForJson.put(uniqueDataKey, attributeIndividualStringBuilder.toString());
1132                 } else if (LIST.equalsIgnoreCase(typeValue) || MAP.equalsIgnoreCase(typeValue)) {
1133                     logger.info("requiredValue is:" + requiredValue);
1134                     String findList = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1]
1135                             + ".entry_schema.type";
1136                     String findDefaultValue = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1]
1137                             + ".entry_schema.default";
1138                     String findDescription = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1]
1139                             + ".entry_schema.description";
1140                     String listValue = map.get(findList);
1141                     String defaultValue = map.get(findDefaultValue);
1142                     String description = map.get(findDescription);
1143                     if (listValue != null) {
1144                         logger.info("Type of list is:" + listValue);
1145                         // Its userdefined
1146                         if (listValue.contains(".")) {
1147                             String trimValue = listValue.substring(listValue.lastIndexOf('.') + 1);
1148                             StringBuilder referenceIndividualStringBuilder = new StringBuilder();
1149                             referenceIndividualStringBuilder.append(trimValue + REQUIREDVALUE);
1150                             referenceIndividualStringBuilder.append(requiredValue + MANYTRUE);
1151                             referenceIndividualStringBuilder.append(DESCRIPTION_TOKEN + description);
1152                             dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString());
1153                         } else { // Its string
1154                             StringBuilder stringListItems = new StringBuilder();
1155                             if (LIST.equalsIgnoreCase(typeValue)) {
1156                                 stringListItems.append(uniqueDataKeySplit[1].toUpperCase() + DEFAULTVALUE + defaultValue
1157                                         + REQUIREDVALUE + requiredValue + MANYFALSE + DESCRIPTION_TOKEN + description);
1158                             } else if (MAP.equalsIgnoreCase(typeValue)) {
1159                                 stringListItems.append(uniqueDataKeySplit[1].toUpperCase() + DEFAULTVALUE + defaultValue
1160                                         + REQUIREDVALUE + requiredValue + MANYTRUE + DESCRIPTION_TOKEN + description);
1161                             }
1162                             dataMapForJson.put(uniqueDataKey, stringListItems.toString());
1163                             dataListBuffer.append(uniqueDataKeySplit[1].toUpperCase() + "=[");
1164                             for (int i = 0; i < 10; i++) {
1165                                 String findConstraints = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES
1166                                         + uniqueDataKeySplit[1] + ".entry_schema.constraints.0.valid_values." + i;
1167                                 String constraintsValue = map.get(findConstraints);
1168                                 logger.info(constraintsValue);
1169                                 boolean ruleCheck = false;
1170                                 if (constraintsValue == null) {
1171                                     break;
1172                                 } else if (constraintsValue.startsWith(DICTIONARY)) {
1173                                     List<Object> dictFromDB = null;
1174                                     String[] dictionaryNameValRule;
1175                                     String[] dictionaryName = constraintsValue.split(":");
1176                                     String dictionaryNameVal = dictionaryName[1];
1177                                     if (dictionaryNameVal.contains("#Rules")) {
1178                                         ruleCheck = true;
1179                                         dictionaryNameValRule = dictionaryNameVal.split("#");
1180                                         dictFromDB = commonClassDao.getDataById(DictionaryData.class, DICTIONARYNAME,
1181                                                 dictionaryNameValRule[0]);
1182                                     } else {
1183                                         dictFromDB = commonClassDao.getDataById(DictionaryData.class, DICTIONARYNAME,
1184                                                 dictionaryName[1]);
1185                                     }
1186                                     if (dictFromDB != null && !dictFromDB.isEmpty()) {
1187                                         DictionaryData data = (DictionaryData) dictFromDB.get(0);
1188                                         if (ruleCheck) {
1189                                             constraintsValue = DICTIONARY + data.getDictionaryUrl() + "@"
1190                                                     + data.getDictionaryDataByName() + "&Rule";
1191                                         } else {
1192                                             constraintsValue = DICTIONARY + data.getDictionaryUrl() + "@"
1193                                                     + data.getDictionaryDataByName();
1194                                         }
1195                                     }
1196                                     dataListBuffer.append(constraintsValue + ",");
1197                                 } else {
1198                                     logger.info("constraintsValue => " + constraintsValue);
1199                                     if (constraintsValue.contains("=")) {
1200                                         constraintsValue = constraintsValue.replace("=", "equal-sign");
1201                                     }
1202                                     dataConstraints.add(constraintsValue);
1203                                     dataListBuffer.append(constraintsValue + ",");
1204                                 }
1205                             }
1206                             dataListBuffer.append("]#");
1207                             logger.info(dataListBuffer);
1208                         }
1209                     }
1210                 } else {
1211                     String findUserDefined = DATATYPE + uniqueDataKeySplit[0] + "." + PROPERTIES_KEY + "."
1212                             + uniqueDataKeySplit[1] + TYPE;
1213                     String findDescription = DATATYPE + uniqueDataKeySplit[0] + "." + PROPERTIES_KEY + "."
1214                             + uniqueDataKeySplit[1] + DESCRIPTION;
1215                     String userDefinedValue = map.get(findUserDefined);
1216                     String description = map.get(findDescription);
1217                     String trimValue = userDefinedValue.substring(userDefinedValue.lastIndexOf('.') + 1);
1218                     StringBuilder referenceIndividualStringBuilder = new StringBuilder();
1219                     referenceIndividualStringBuilder.append(trimValue + REQUIREDVALUE);
1220                     referenceIndividualStringBuilder.append(requiredValue + MANYFALSE);
1221                     referenceIndividualStringBuilder.append(DESCRIPTION_TOKEN + description);
1222                     dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString());
1223
1224                 }
1225             } else {
1226                 matchableValues.put(uniqueDataKey, MATCHINGTRUE);
1227             }
1228         }
1229
1230         return dataMapForJson;
1231     }
1232
1233     LinkedHashMap<String, LinkedHashMap<String, String>> parsePolicyNodes(Map<String, String> map)
1234             throws ParserException {
1235         LinkedHashMap<String, LinkedHashMap<String, String>> mapKey = new LinkedHashMap<>();
1236         for (String uniqueKey : uniqueKeys) {
1237             LinkedHashMap<String, String> hm;
1238
1239             for (Entry<String, String> entry : map.entrySet()) {
1240                 String key = entry.getKey();
1241                 if (key.contains(uniqueKey) && key.contains("policy.nodes")) {
1242                     if (mapKey.containsKey(uniqueKey)) {
1243                         hm = mapKey.get(uniqueKey);
1244                         String keyStr = key.substring(key.lastIndexOf('.') + 1);
1245                         String valueStr = map.get(key);
1246                         if ("type".equalsIgnoreCase(keyStr) && key.contains("entry_schema.0.type")
1247                                 || key.contains("entry_schema.type") && valueStr.contains("policy.data.")) {
1248                             throw new ParserException(
1249                                     "For user defined object type, Please make sure no space between 'type:' and object "
1250                                             + valueStr);
1251
1252                         }
1253                         if ("type".equals(keyStr)) {
1254                             if (!key.contains("entry_schema")) {
1255                                 hm.put(keyStr, valueStr);
1256                             }
1257                         } else {
1258                             hm.put(keyStr, valueStr);
1259                         }
1260
1261                     } else {
1262                         hm = new LinkedHashMap<>();
1263                         String keyStr = key.substring(key.lastIndexOf('.') + 1);
1264                         String valueStr = map.get(key);
1265
1266                         if (("type").equals(keyStr)) {
1267                             if (!key.contains("entry_schema")) {
1268                                 hm.put(keyStr, valueStr);
1269                             }
1270                         } else {
1271                             hm.put(keyStr, valueStr);
1272                         }
1273                         mapKey.put(uniqueKey, hm);
1274                     }
1275                 }
1276             }
1277         }
1278         return mapKey;
1279     }
1280
1281     private void createAttributes(LinkedHashMap<String, LinkedHashMap<String, String>> mapKey) {
1282         StringBuilder attributeStringBuilder = new StringBuilder();
1283         StringBuilder referenceStringBuilder = new StringBuilder();
1284         StringBuilder listBuffer = new StringBuilder();
1285         List<String> constraints = new ArrayList<>();
1286         for (Map.Entry<String, LinkedHashMap<String, String>> entry : mapKey.entrySet()) {
1287             String keySetString = entry.getKey();
1288             LinkedHashMap<String, String> keyValues = mapKey.get(keySetString);
1289             if (keyValues.get("type") != null && (STRING.equalsIgnoreCase(keyValues.get("type"))
1290                     || INTEGER.equalsIgnoreCase(keyValues.get("type"))
1291                     || BOOLEAN.equalsIgnoreCase(keyValues.get("type")))) {
1292                 StringBuilder attributeIndividualStringBuilder = new StringBuilder();
1293                 attributeIndividualStringBuilder.append(keySetString + "=");
1294                 attributeIndividualStringBuilder.append(keyValues.get("type") + DEFAULTVALUE);
1295                 attributeIndividualStringBuilder.append(keyValues.get("default") + REQUIREDVALUE);
1296                 attributeIndividualStringBuilder.append(keyValues.get("required") + MANYFALSE);
1297                 attributeIndividualStringBuilder.append(DESCRIPTION_TOKEN + keyValues.get(DESCRIPTION_KEY));
1298                 attributeStringBuilder.append(attributeIndividualStringBuilder + ",");
1299                 if (keyValues.get(MATCHABLEKEY) != null && "true".equalsIgnoreCase(keyValues.get(MATCHABLEKEY))) {
1300                     matchableValues.put(keySetString, MATCHINGTRUE);
1301                 }
1302             } else if (LIST.equalsIgnoreCase(keyValues.get("type"))) {
1303                 if ("true".equalsIgnoreCase(keyValues.get(MATCHABLEKEY))) {
1304                     matchableValues.put(keySetString, MATCHINGTRUE);
1305                 }
1306                 // List Data type
1307                 Set<String> keys = keyValues.keySet();
1308                 Iterator<String> itr = keys.iterator();
1309                 boolean isDefinedType = false;
1310                 while (itr.hasNext()) {
1311                     String key = itr.next();
1312                     if ((!("type").equals(key) || ("required").equals(key))) {
1313                         String value = keyValues.get(key);
1314                         // The "." in the value determines if its a string or a user defined type.
1315                         if (!value.contains(".")) {
1316                             // This is string
1317                             if (StringUtils.isNumeric(key)) { // only integer key for the value of Constrains
1318                                 constraints.add(keyValues.get(key));
1319                             }
1320                         } else {
1321                             // This is user defined type
1322                             String trimValue = value.substring(value.lastIndexOf('.') + 1);
1323                             StringBuilder referenceIndividualStringBuilder = new StringBuilder();
1324                             referenceIndividualStringBuilder.append(keySetString + "=" + trimValue + MANYTRUE
1325                                     + DESCRIPTION_TOKEN + keyValues.get(DESCRIPTION_KEY));
1326                             referenceStringBuilder.append(referenceIndividualStringBuilder + ",");
1327                             isDefinedType = true;
1328                         }
1329                     }
1330
1331                 }
1332
1333                 if (!isDefinedType && LIST.equalsIgnoreCase(keyValues.get("type"))
1334                         && (constraints == null || constraints.isEmpty())) {
1335                     referenceStringBuilder.append(keySetString + "=MANY-true" + ",");
1336                 }
1337             } else {
1338                 // User defined Datatype.
1339                 if ("true".equalsIgnoreCase(keyValues.get(MATCHABLEKEY))) {
1340                     matchableValues.put(keySetString, MATCHINGTRUE);
1341                 }
1342                 String value = keyValues.get("type");
1343                 if (value != null && !value.isEmpty()) {
1344                     String trimValue = value.substring(value.lastIndexOf('.') + 1);
1345                     StringBuilder referenceIndividualStringBuilder = new StringBuilder();
1346                     referenceIndividualStringBuilder.append(keySetString + "=" + trimValue + MANYFALSE
1347                             + DESCRIPTION_TOKEN + keyValues.get(DESCRIPTION_KEY));
1348                     referenceStringBuilder.append(referenceIndividualStringBuilder + ",");
1349                 } else {
1350                     logger.info("keyValues.get(type) is null/empty");
1351                 }
1352
1353             }
1354             if (constraints != null && !constraints.isEmpty()) {
1355                 // List handling.
1356                 listBuffer.append(keySetString.toUpperCase() + "=[");
1357                 for (String str : constraints) {
1358                     if (str.contains(DICTIONARY)) {
1359                         String[] dictionaryName = str.split(":");
1360                         List<Object> dictFromDB =
1361                                 commonClassDao.getDataById(DictionaryData.class, DICTIONARYNAME, dictionaryName[1]);
1362                         if (dictFromDB != null && !dictFromDB.isEmpty()) {
1363                             DictionaryData data = (DictionaryData) dictFromDB.get(0);
1364                             str = DICTIONARY + data.getDictionaryUrl() + "@" + data.getDictionaryDataByName();
1365                         }
1366                     }
1367                     listBuffer.append(str + ",");
1368                 }
1369                 listBuffer.append("]#");
1370                 logger.info(listBuffer);
1371
1372
1373                 StringBuilder referenceIndividualStringBuilder = new StringBuilder();
1374                 referenceIndividualStringBuilder.append(keySetString + "=" + keySetString.toUpperCase() + MANYFALSE);
1375                 referenceStringBuilder.append(referenceIndividualStringBuilder + ",");
1376                 constraints.clear();
1377             }
1378         }
1379
1380         dataListBuffer.append(listBuffer);
1381
1382
1383         logger.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
1384         logger.info("Whole attribute String is:" + attributeStringBuilder);
1385         logger.info("Whole reference String is:" + referenceStringBuilder);
1386         logger.info("List String is:" + listBuffer);
1387         logger.info("Data list buffer is:" + dataListBuffer);
1388         logger.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
1389
1390         this.listConstraints = dataListBuffer.toString();
1391         this.referenceAttributes = referenceStringBuilder.toString();
1392         this.attributeString = attributeStringBuilder.toString();
1393     }
1394
1395     @SuppressWarnings("unchecked")
1396     private void findNode(LinkedHashMap<Object, Object> map) {
1397
1398         map.forEach((key, value) -> {
1399             // if the value is properties and its type is map object, then save all the keys
1400             if (key.equals(PROPERTIES_KEY) && value instanceof Map) {
1401                 saveNodes((LinkedHashMap<?, ?>) value);
1402                 if (isDuplicatedAttributes) {
1403                     orderedElements = new ArrayList<>();
1404                     return;
1405                 }
1406             }
1407
1408             if (!"policy.nodes.Root".equals(key) && value instanceof Map) {
1409                 // value is a Map object, then make a recursive call
1410                 findNode((LinkedHashMap<Object, Object>) value);
1411             }
1412         });
1413
1414     }
1415
1416     private void saveNodes(LinkedHashMap<?, ?> map) {
1417
1418         for (Entry<?, ?> entry : map.entrySet()) {
1419
1420             if (orderedElements.indexOf(entry.getKey()) >= 0) { // duplicated attribute names
1421                 isDuplicatedAttributes = true;
1422                 return;
1423             } else {
1424                 orderedElements.add((String) entry.getKey());
1425             }
1426         }
1427     }
1428
1429     public String getAttributeString() {
1430         return attributeString;
1431     }
1432
1433     public void setAttributeString(String attributeString) {
1434         this.attributeString = attributeString;
1435     }
1436
1437     public LinkedHashMap<String, Object> getRetmap() {
1438         return retmap;
1439     }
1440
1441     public void setRetmap(LinkedHashMap<String, Object> retmap) {
1442         this.retmap = retmap;
1443     }
1444
1445     public Map<String, String> getMatchableValues() {
1446         return matchableValues;
1447     }
1448
1449     public void setMatchableValues(Map<String, String> matchableValues) {
1450         this.matchableValues = matchableValues;
1451     }
1452
1453     public String getReferenceAttributes() {
1454         return referenceAttributes;
1455     }
1456
1457     public void setReferenceAttributes(String referenceAttributes) {
1458         this.referenceAttributes = referenceAttributes;
1459     }
1460
1461     public String getListConstraints() {
1462         return listConstraints;
1463     }
1464
1465     public void setListConstraints(String listConstraints) {
1466         this.listConstraints = listConstraints;
1467     }
1468
1469     public String getDataOrderInfo() {
1470         return dataOrderInfo;
1471     }
1472
1473     public void setDataOrderInfo(String dataOrderInfo) {
1474         this.dataOrderInfo = dataOrderInfo;
1475     }
1476
1477     public String getJsonRuleFormation() {
1478         return jsonRuleFormation;
1479     }
1480
1481     public void setJsonRuleFormation(String jsonRuleFormation) {
1482         this.jsonRuleFormation = jsonRuleFormation;
1483     }
1484
1485 }