2 * ============LICENSE_START=======================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
23 package org.onap.policy.rest.util;
25 import com.att.research.xacml.util.XACMLProperties;
26 import com.google.gson.Gson;
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;
41 import java.util.Map.Entry;
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;
73 public class MSModelUtils {
75 private static final Log logger = LogFactory.getLog(MSModelUtils.class);
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";
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;
131 private static CommonClassDao commonClassDao;
133 public MSModelUtils() {
134 // Default Constructor
137 public MSModelUtils(CommonClassDao commonClassDao) {
138 MSModelUtils.commonClassDao = commonClassDao;
141 public MSModelUtils(String onap, String policy) {
143 this.policy = policy;
146 private enum ANNOTATION_TYPE {
147 MATCHING, VALIDATION, DICTIONARY
150 public enum MODEL_TYPE {
154 public enum SearchType {
155 TOSCA_DEFINITION_VERSION, TOSCA_SIMPLE_YAML_1_0_0, NODE_TYPE, DATA_TYPE, JSON_MODEL
158 public Map<String, MSAttributeObject> processEpackage(String file, MODEL_TYPE model) {
159 if (model == MODEL_TYPE.XMI) {
160 processXMIEpackage(file);
166 private void processXMIEpackage(String xmiFile) {
167 EPackage root = getEpackage(xmiFile);
168 TreeIterator<EObject> treeItr = root.eAllContents();
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();
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);
189 if (!enumMap.isEmpty()) {
192 if (!matchingClass.isEmpty()) {
193 checkForMatchingClass();
197 private void checkForMatchingClass() {
198 HashMap<String, String> tempAttribute = new HashMap<>();
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);
209 for (Entry<String, String> eSet : listRef.entrySet()) {
210 String key3 = eSet.getKey();
211 tempAttribute.put(key3, MATCHINGTRUE);
215 updateMatching(tempAttribute, key);
222 private void updateMatching(HashMap<String, String> tempAttribute, String key) {
223 Map<String, MSAttributeObject> newClass = classMap;
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);
238 private void addEnumClassMap() {
239 for (Entry<String, MSAttributeObject> value : classMap.entrySet()) {
240 value.getValue().setEnumType(enumMap);
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);
251 resource.load(Collections.emptyMap());
252 } catch (IOException e) {
253 logger.error("Error loading Encore Resource for new Model" + e);
256 return (EPackage) resource.getContents().get(0);
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;
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);
270 returnMap.put(name, valueList.toString());
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(",")));
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));
293 this.classMap.put(className, msAttributeObject);
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<>();
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);
310 if (requiredAttribute) {
311 if (obj instanceof EStructuralFeature) {
312 checkAnnotation(annotationSet, (EStructuralFeature) obj);
314 } else if (requiredMatchAttribute && (obj instanceof EStructuralFeature)) {
315 findMatchingAnnotation(annotationSet, obj);
318 return annotationSet;
321 private void findMatchingAnnotation(HashMap<String, String> annotationSet, EObject obj) {
322 EStructuralFeature eStrucClassifier = (EStructuralFeature) obj;
323 if (eStrucClassifier.getEAnnotations().isEmpty()) {
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);
333 annotationSet.put(eStrucClassifier.getName(), matching);
339 private void checkAnnotation(HashMap<String, String> annotationSet, EStructuralFeature obj) {
340 EStructuralFeature eStrucClassifier = obj;
341 if (eStrucClassifier.getEAnnotations().isEmpty()) {
344 String matching = annotationValue(eStrucClassifier, ANNOTATION_TYPE.MATCHING, policy);
345 if (matching != null) {
346 annotationSet.put(eStrucClassifier.getName(), matching);
348 String range = annotationValue(eStrucClassifier, ANNOTATION_TYPE.VALIDATION, policy);
350 annotationSet.put(eStrucClassifier.getName(), range);
352 String annotationDict = annotationValue(eStrucClassifier, ANNOTATION_TYPE.DICTIONARY, policy);
353 if (annotationDict != null) {
354 annotationSet.put(eStrucClassifier.getName(), annotationDict);
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;
365 // Pulling out dependency from file
366 while (treeItr.hasNext() && rollingCount < 2) {
368 EObject obj = treeItr.next();
369 if (obj instanceof EClassifier) {
370 requiredAttribute = isRequiredAttribute(obj, className) || isRequiredAttribute(obj, superClass);
371 if (requiredAttribute) {
374 rollingCount = rollingCount + processClass;
377 if (requiredAttribute && (obj instanceof EStructuralFeature)) {
378 EStructuralFeature eStrucClassifier = (EStructuralFeature) obj;
379 if (!eStrucClassifier.getEAnnotations().isEmpty()) {
380 updateSubAttributes(subAttribute, obj, eStrucClassifier);
387 private void updateSubAttributes(Map<String, Object> subAttribute, EObject obj,
388 EStructuralFeature eStrucClassifier) {
389 if (!(obj instanceof EReference)) {
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;
399 subAttribute.put(eStrucClassifier.getName(), refType.getName() + required);
404 public String checkDefultValue(String defultValue) {
405 if (defultValue != null) {
406 return DEFAULTVALUE + defultValue;
408 return ":defaultValue-NA";
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])) {
418 return REQUIREDFALSE;
421 public JSONObject buildJavaObject(Map<String, String> map) {
422 return new JSONObject(map);
425 public Map<String, String> getRefAttributeList(EPackage root, String className, String superClass) {
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;
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) {
441 rollingCount = rollingCount + processClass;
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);
460 private void updEnumTypeRefAttrib(HashMap<String, String> refAttribute, EStructuralFeature obj,
461 EStructuralFeature eStrucClassifier) {
462 EClassifier refType = ((EAttributeImpl) obj).getEType();
463 if (!(refType instanceof EEnumImpl)) {
467 String array = arrayCheck(obj.getUpperBound());
468 String required = REQUIREDFALSE;
469 if (obj.getLowerBound() == 1) {
470 required = REQUIREDTRUE;
472 refAttribute.put(eStrucClassifier.getName(), refType.getName() + array + required);
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];
481 StringUtils.replaceEach(one.split("#")[1], new String[] {"//", ")"}, new String[] {"", ""});
482 refAttribute.put(eStrucClassifier.getName(), refValue);
484 String required = REQUIREDFALSE;
485 if (obj.getLowerBound() == 1) {
486 required = REQUIREDTRUE;
488 refAttribute.put(eStrucClassifier.getName(),
489 refType.getName() + arrayCheck(obj.getUpperBound()) + required);
493 private boolean annotationTest(EStructuralFeature eStrucClassifier, String annotation, String type) {
494 String annotationType;
495 EAnnotation eAnnotation;
499 EList<EAnnotation> value = eStrucClassifier.getEAnnotations();
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();
507 if (annotationType.contains(type) && onapType.contains(annotation)) {
511 if (annotationType.contains(type) && onapValue.contains(annotation)) {
520 private String annotationValue(EStructuralFeature eStrucClassifier, ANNOTATION_TYPE annotation, String type) {
521 String annotationType;
522 EAnnotation eAnnotation;
524 String onapValue = null;
526 EList<EAnnotation> value = eStrucClassifier.getEAnnotations();
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) {
537 return onapType + "-" + onapValue;
545 public boolean isRequiredAttribute(EObject obj, String className) {
546 EClassifier eClassifier = (EClassifier) obj;
547 String workingClass = eClassifier.getName().trim();
548 if (workingClass.equalsIgnoreCase(className)) {
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);
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")) {
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);
587 return returnSubTypes;
590 private String findSubTypes(String className, String returnSubTypes, EClass classifier) {
591 EClass eClass = classifier;
593 for (EClass eSuperType : eClass.getEAllSuperTypes()) {
594 if (eClass.getName().contentEquals(className)) {
595 returnSubTypes = eSuperType.getName();
598 return returnSubTypes;
601 public Map<String, String> getAttributeList(EPackage root, String className, String superClass) {
603 TreeIterator<EObject> treeItr = root.eAllContents();
604 boolean requiredAttribute = false;
605 HashMap<String, String> refAttribute = new HashMap<>();
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);
614 if (requiredAttribute && (obj instanceof EStructuralFeature)) {
615 EStructuralFeature eStrucClassifier = (EStructuralFeature) obj;
616 if (!eStrucClassifier.getEAnnotations().isEmpty()) {
617 checkStrucClassifier(refAttribute, obj, eStrucClassifier);
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);
635 private void updEReferenceAttrib(HashMap<String, String> refAttribute, boolean dictionaryTest,
636 EStructuralFeature obj, EStructuralFeature eStrucClassifier) {
638 String name = eStrucClassifier.getName();
639 if (dictionaryTest) {
640 eType = annotationValue(eStrucClassifier, ANNOTATION_TYPE.DICTIONARY, policy);
642 eType = eStrucClassifier.getEType().getInstanceClassName();
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);
650 public String arrayCheck(int upperBound) {
652 if (upperBound == -1) {
659 public List<String> getDependencyList(EClassifier eClassifier) {
660 List<String> returnValue = new ArrayList<>();;
661 EList<EClass> somelist = ((EClass) eClassifier).getEAllSuperTypes();
662 if (somelist.isEmpty()) {
665 for (EClass depend : somelist) {
666 if (depend.toString().contains(eProxyURI)) {
667 String one = depend.toString().split(eProxyURI)[1];
669 StringUtils.replaceEach(one.split("#")[1], new String[] {"//", ")"}, new String[] {"", ""});
670 returnValue.add(value);
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;
683 for (Entry<String, String> map : classMap.get(className).getRefAttribute().entrySet()) {
684 String value = map.getValue().split(":")[0];
686 classMap.get(className).getEnumType();
687 enumType = classMap.get(className).getEnumType().containsKey(value);
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());
701 return missingValues;
704 public Map<String, Map<String, String>> recursiveReference(Map<String, MSAttributeObject> classMap,
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]));
722 public String createJson(Map<String, MSAttributeObject> classMap, String className) {
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];
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);
737 Gson gson = new Gson();
738 return gson.toJson(myObject);
741 public Map<String, String> getRefclass(Map<String, MSAttributeObject> classMap, String className) {
742 HashMap<String, String> missingValues = new HashMap<>();
744 if (classMap.get(className).getAttribute() != null || !classMap.get(className).getAttribute().isEmpty()) {
745 missingValues.putAll(classMap.get(className).getAttribute());
748 if (classMap.get(className).getRefAttribute() != null || !classMap.get(className).getRefAttribute().isEmpty()) {
749 missingValues.putAll(classMap.get(className).getRefAttribute());
752 return missingValues;
755 public String createSubAttributes(List<String> dependency, Map<String, MSAttributeObject> classMap,
758 HashMap<String, Object> workingMap = new HashMap<>();
759 MSAttributeObject tempObject;
760 if (dependency != null) {
761 if (dependency.isEmpty()) {
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());
773 return createJson(classMap, modelName);
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);
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);
795 private void updDependencyList(ArrayList<String> returnList, String depend) {
796 if (!returnList.contains(depend) && !depend.isEmpty()) {
797 returnList.add(depend.trim());
804 public String parseTosca(String fileName) {
805 Map<String, String> map = new LinkedHashMap<>();
807 map = load(fileName);
808 if (map != null && map.get(ERROR) != null) {
809 return map.get(ERROR);
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);
817 } catch (IOException e) {
819 } catch (ParserException e) {
821 return e.getMessage();
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) {
837 } catch (Exception e) {
839 throw new ParserException("Invalid TOSCA Model format. Please make sure it is a valid YAML file");
842 StringBuilder sb = new StringBuilder();
843 LinkedHashMap<String, String> settings = new LinkedHashMap<>();
844 if (yamlMap == null) {
848 String message = validations(yamlMap);
850 if (message != null) {
851 settings.put(ERROR, message);
857 if (!isDuplicatedAttributes && orderedElements != null && !orderedElements.isEmpty()) {
858 orderedElements.stream().forEach(string -> {
859 orderInfo.append(string);
860 orderInfo.append(",");
861 logger.info("Content: " + string);
864 orderInfo.append("]");
866 dataOrderInfo = orderInfo.toString();
867 dataOrderInfo = dataOrderInfo.replace(",]", "]");
869 logger.info("dataOrderInfo :" + dataOrderInfo);
872 List<String> path = new ArrayList<>();
873 serializeMap(settings, sb, path, yamlMap);
877 @SuppressWarnings("unchecked")
878 private String validations(@SuppressWarnings("rawtypes") Map yamlMap) {
880 boolean isNoteTypeFound = false;
881 boolean isDataTypeFound = false;
882 boolean isToscaVersionKeyFound = false;
883 boolean isToscaVersionValueFound = false;
884 @SuppressWarnings("rawtypes")
885 Map m1 = new HashMap();
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;
897 switch (me.getKey().toString()) {
898 case TOSCA_DEFINITION_VERSION:
899 isToscaVersionKeyFound = true;
901 m1.put(TOSCA_DEFINITION_VERSION, order);
904 isNoteTypeFound = true;
906 m1.put(NODE_TYPE, order);
909 isDataTypeFound = true;
911 m1.put(DATA_TYPE, order);
914 setJsonRuleFormation(me.getValue().toString());
920 if (!isDataTypeFound) {
921 return "data_types are missing or invalid.";
923 if (!isToscaVersionKeyFound || !isToscaVersionValueFound) {
924 return "tosca_definitions_version is missing or invalid.";
927 if (!isNoteTypeFound) {
928 return "node_types are missing or invalid.";
931 short version = (short) m1.get(TOSCA_DEFINITION_VERSION);
934 return "tosca_definitions_version should be defined first.";
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.";
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()) {
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);
962 serializeValue(settings, sb, path, (String) entry.getKey(), entry.getValue());
967 @SuppressWarnings("unchecked")
968 private void serializeList(LinkedHashMap<String, String> settings, StringBuilder sb, List<String> path,
969 List<String> yamlList) {
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);
981 serializeValue(settings, sb, path, Integer.toString(counter), listEle);
987 private void serializeValue(LinkedHashMap<String, String> settings, StringBuilder sb, List<String> path,
988 String name, Object value) {
993 for (String pathEle : path) {
994 sb.append(pathEle).append('.');
997 settings.put(sb.toString(), value.toString());
1001 void parseDataAndPolicyNodes(Map<String, String> map) {
1002 for (String key : map.keySet()) {
1003 if (key.contains("policy.nodes.Root")) {
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());
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());
1016 stringBetweenDotsForDataFields(subNodeString);
1021 // Second index of dot should be returned.
1022 public int stringBetweenDots(String str) {
1023 String stringToSearch = str;
1024 String[] ss = stringToSearch.split("\\.");
1026 int len = ss.length;
1028 uniqueKeys.add(ss[2]);
1032 return uniqueKeys.size();
1036 public void stringBetweenDotsForDataFields(String str) {
1037 String stringToSearch = str;
1038 String[] ss = stringToSearch.split("\\.");
1040 int len = ss.length;
1043 uniqueDataKeys.add(ss[0] + "%" + ss[2]);
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);
1059 hmSub = new LinkedHashMap<>();
1060 hmSub.put(uniqueDataKeySplit[1], value);
1063 dataMapKey.put(uniqueDataKeySplit[0], hmSub);
1066 JSONObject mainObject = new JSONObject();
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));
1076 mainObject.put(s, json);
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);
1085 logger.info("#############################################################################");
1086 logger.info(mainObject);
1087 logger.info("###############################################################################");
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);
1100 String findRequired = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] + REQUIRED;
1101 String requiredValue = map.get(findRequired);
1103 String matchable = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] + MATCHABLE;
1105 String matchableValue = map.get(matchable);
1107 if ("true".equalsIgnoreCase(matchableValue)) {
1108 String key = uniqueDataKeySplit[uniqueDataKeySplit.length - 1];
1109 matchableValues.put(key, MATCHINGTRUE);
1112 if (requiredValue == null || requiredValue.isEmpty()) {
1113 requiredValue = "false";
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);
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);
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);
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) {
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")) {
1179 dictionaryNameValRule = dictionaryNameVal.split("#");
1180 dictFromDB = commonClassDao.getDataById(DictionaryData.class, DICTIONARYNAME,
1181 dictionaryNameValRule[0]);
1183 dictFromDB = commonClassDao.getDataById(DictionaryData.class, DICTIONARYNAME,
1186 if (dictFromDB != null && !dictFromDB.isEmpty()) {
1187 DictionaryData data = (DictionaryData) dictFromDB.get(0);
1189 constraintsValue = DICTIONARY + data.getDictionaryUrl() + "@"
1190 + data.getDictionaryDataByName() + "&Rule";
1192 constraintsValue = DICTIONARY + data.getDictionaryUrl() + "@"
1193 + data.getDictionaryDataByName();
1196 dataListBuffer.append(constraintsValue + ",");
1198 logger.info("constraintsValue => " + constraintsValue);
1199 if (constraintsValue.contains("=")) {
1200 constraintsValue = constraintsValue.replace("=", "equal-sign");
1202 dataConstraints.add(constraintsValue);
1203 dataListBuffer.append(constraintsValue + ",");
1206 dataListBuffer.append("]#");
1207 logger.info(dataListBuffer);
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());
1226 matchableValues.put(uniqueDataKey, MATCHINGTRUE);
1230 return dataMapForJson;
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;
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 "
1253 if ("type".equals(keyStr)) {
1254 if (!key.contains("entry_schema")) {
1255 hm.put(keyStr, valueStr);
1258 hm.put(keyStr, valueStr);
1262 hm = new LinkedHashMap<>();
1263 String keyStr = key.substring(key.lastIndexOf('.') + 1);
1264 String valueStr = map.get(key);
1266 if (("type").equals(keyStr)) {
1267 if (!key.contains("entry_schema")) {
1268 hm.put(keyStr, valueStr);
1271 hm.put(keyStr, valueStr);
1273 mapKey.put(uniqueKey, hm);
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);
1302 } else if (LIST.equalsIgnoreCase(keyValues.get("type"))) {
1303 if ("true".equalsIgnoreCase(keyValues.get(MATCHABLEKEY))) {
1304 matchableValues.put(keySetString, MATCHINGTRUE);
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(".")) {
1317 if (StringUtils.isNumeric(key)) { // only integer key for the value of Constrains
1318 constraints.add(keyValues.get(key));
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;
1333 if (!isDefinedType && LIST.equalsIgnoreCase(keyValues.get("type"))
1334 && (constraints == null || constraints.isEmpty())) {
1335 referenceStringBuilder.append(keySetString + "=MANY-true" + ",");
1338 // User defined Datatype.
1339 if ("true".equalsIgnoreCase(keyValues.get(MATCHABLEKEY))) {
1340 matchableValues.put(keySetString, MATCHINGTRUE);
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 + ",");
1350 logger.info("keyValues.get(type) is null/empty");
1354 if (constraints != null && !constraints.isEmpty()) {
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();
1367 listBuffer.append(str + ",");
1369 listBuffer.append("]#");
1370 logger.info(listBuffer);
1373 StringBuilder referenceIndividualStringBuilder = new StringBuilder();
1374 referenceIndividualStringBuilder.append(keySetString + "=" + keySetString.toUpperCase() + MANYFALSE);
1375 referenceStringBuilder.append(referenceIndividualStringBuilder + ",");
1376 constraints.clear();
1380 dataListBuffer.append(listBuffer);
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("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
1390 this.listConstraints = dataListBuffer.toString();
1391 this.referenceAttributes = referenceStringBuilder.toString();
1392 this.attributeString = attributeStringBuilder.toString();
1395 @SuppressWarnings("unchecked")
1396 private void findNode(LinkedHashMap<Object, Object> map) {
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<>();
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);
1416 private void saveNodes(LinkedHashMap<?, ?> map) {
1418 for (Entry<?, ?> entry : map.entrySet()) {
1420 if (orderedElements.indexOf(entry.getKey()) >= 0) { // duplicated attribute names
1421 isDuplicatedAttributes = true;
1424 orderedElements.add((String) entry.getKey());
1429 public String getAttributeString() {
1430 return attributeString;
1433 public void setAttributeString(String attributeString) {
1434 this.attributeString = attributeString;
1437 public LinkedHashMap<String, Object> getRetmap() {
1441 public void setRetmap(LinkedHashMap<String, Object> retmap) {
1442 this.retmap = retmap;
1445 public Map<String, String> getMatchableValues() {
1446 return matchableValues;
1449 public void setMatchableValues(Map<String, String> matchableValues) {
1450 this.matchableValues = matchableValues;
1453 public String getReferenceAttributes() {
1454 return referenceAttributes;
1457 public void setReferenceAttributes(String referenceAttributes) {
1458 this.referenceAttributes = referenceAttributes;
1461 public String getListConstraints() {
1462 return listConstraints;
1465 public void setListConstraints(String listConstraints) {
1466 this.listConstraints = listConstraints;
1469 public String getDataOrderInfo() {
1470 return dataOrderInfo;
1473 public void setDataOrderInfo(String dataOrderInfo) {
1474 this.dataOrderInfo = dataOrderInfo;
1477 public String getJsonRuleFormation() {
1478 return jsonRuleFormation;
1481 public void setJsonRuleFormation(String jsonRuleFormation) {
1482 this.jsonRuleFormation = jsonRuleFormation;