2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.rest.util;
24 import java.io.FileInputStream;
25 import java.io.FileNotFoundException;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Collections;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.Iterator;
34 import java.util.LinkedHashMap;
35 import java.util.List;
38 import java.util.Map.Entry;
40 import org.apache.commons.lang.StringUtils;
41 import org.apache.commons.logging.Log;
42 import org.apache.commons.logging.LogFactory;
43 import org.eclipse.emf.common.util.EList;
44 import org.eclipse.emf.common.util.EMap;
45 import org.eclipse.emf.common.util.Enumerator;
46 import org.eclipse.emf.common.util.TreeIterator;
47 import org.eclipse.emf.common.util.URI;
48 import org.eclipse.emf.ecore.EAnnotation;
49 import org.eclipse.emf.ecore.EClass;
50 import org.eclipse.emf.ecore.EClassifier;
51 import org.eclipse.emf.ecore.EEnum;
52 import org.eclipse.emf.ecore.EEnumLiteral;
53 import org.eclipse.emf.ecore.EObject;
54 import org.eclipse.emf.ecore.EPackage;
55 import org.eclipse.emf.ecore.EReference;
56 import org.eclipse.emf.ecore.EStructuralFeature;
57 import org.eclipse.emf.ecore.impl.EAttributeImpl;
58 import org.eclipse.emf.ecore.impl.EEnumImpl;
59 import org.eclipse.emf.ecore.resource.Resource;
60 import org.eclipse.emf.ecore.resource.ResourceSet;
61 import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
62 import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
63 import org.json.JSONObject;
64 import org.onap.policy.rest.XACMLRestProperties;
65 import org.yaml.snakeyaml.Yaml;
67 import com.att.research.xacml.util.XACMLProperties;
68 import com.google.gson.Gson;
71 public class MSModelUtils {
73 private static final Log logger = LogFactory.getLog(MSModelUtils.class);
75 private HashMap<String,MSAttributeObject > classMap = new HashMap<>();
76 private HashMap<String, String> enumMap = new HashMap<>();
77 private HashMap<String, String> matchingClass = new HashMap<>();
78 private String configuration = "configuration";
79 private String dictionary = "dictionary";
80 private String onap = "";
81 private String policy = "";
82 private String eProxyURI = "eProxyURI:";
83 private List<String> orderedElements = new ArrayList<>();
84 private String dataOrderInfo = null;
85 private Set<String> uniqueDataKeys= new HashSet<>();
86 private Set<String> uniqueKeys= new HashSet<>();
87 private String listConstraints = null;
88 private String referenceAttributes;
89 private LinkedHashMap<String, Object> retmap = new LinkedHashMap<>();
90 private Map<String, String> matchableValues;
91 public static final String PROPERTIES=".properties.";
92 public static final String DATATYPE = "data_types.policy.data.";
93 public static final String TYPE=".type";
94 public static final String REQUIRED=".required";
95 public static final String MATCHABLE=".matchable";
96 public static final String STRING="string";
97 public static final String INTEGER="integer";
98 public static final String LIST="list";
99 public static final String DEFAULT=".default";
100 public static final String MANYFALSE=":MANY-false";
101 public static final String MANYTRUE=":MANY-true";
102 public static final String DEFAULTVALUE=":defaultValue-";
103 public static final String REQUIREDVALUE=":required-";
104 public static final String MATCHABLEKEY="matchable";
105 public static final String REQUIREDFALSE=":required-false";
106 public static final String REQUIREDTRUE=":required-true";
107 public static final String MATCHINGTRUE="matching-true";
109 private StringBuilder dataListBuffer=new StringBuilder();
110 private List<String> dataConstraints= new ArrayList <>();
111 private String attributeString = null;
113 public MSModelUtils(){
116 public MSModelUtils(String onap, String policy){
118 this.policy = policy;
121 private enum ANNOTATION_TYPE{
122 MATCHING, VALIDATION, DICTIONARY
125 public enum MODEL_TYPE {
130 public Map<String, MSAttributeObject> processEpackage(String file, MODEL_TYPE model){
131 if (model == MODEL_TYPE.XMI ){
132 processXMIEpackage(file);
138 private void processXMIEpackage(String xmiFile){
139 EPackage root = getEpackage(xmiFile);
140 TreeIterator<EObject> treeItr = root.eAllContents();
144 // Pulling out dependency from file
145 while (treeItr.hasNext()) {
146 EObject obj = treeItr.next();
147 if (obj instanceof EClassifier) {
148 EClassifier eClassifier = (EClassifier) obj;
149 className = eClassifier.getName();
151 if (obj instanceof EEnum) {
152 enumMap.putAll(getEEnum(obj));
153 }else if (obj instanceof EClass) {
154 String temp = getDependencyList(eClassifier).toString();
155 returnValue = StringUtils.replaceEach(temp, new String[]{"[", "]"}, new String[]{"", ""});
156 getAttributes(className, returnValue, root);
161 if (!enumMap.isEmpty()){
164 if (!matchingClass.isEmpty()){
165 CheckForMatchingClass();
169 private void CheckForMatchingClass() {
170 HashMap<String, String> tempAttribute = new HashMap<>();
172 for (Entry<String, String> set : matchingClass.entrySet()){
173 String key = set.getKey();
174 if (classMap.containsKey(key)){
175 Map<String, String> listAttributes = classMap.get(key).getAttribute();
176 Map<String, String> listRef = classMap.get(key).getRefAttribute();
177 for ( Entry<String, String> eSet : listAttributes.entrySet()){
178 String key2 = eSet.getKey();
179 tempAttribute.put(key2, MATCHINGTRUE);
181 for ( Entry<String, String> eSet : listRef.entrySet()){
182 String key3 = eSet.getKey();
183 tempAttribute.put(key3, MATCHINGTRUE);
187 UpdateMatching(tempAttribute, key);
194 private void UpdateMatching(HashMap<String, String> tempAttribute, String key) {
195 Map<String, MSAttributeObject> newClass = classMap;
197 for (Entry<String, MSAttributeObject> updateClass : newClass.entrySet()){
198 Map<String, String> valueMap = updateClass.getValue().getMatchingSet();
199 String keymap = updateClass.getKey();
200 if (valueMap.containsKey(key)){
201 Map<String, String> modifyMap = classMap.get(keymap).getMatchingSet();
202 modifyMap.remove(key);
203 modifyMap.putAll(tempAttribute);
204 classMap.get(keymap).setMatchingSet(modifyMap);
210 private void addEnumClassMap() {
211 for (Entry<String, MSAttributeObject> value :classMap.entrySet()){
212 value.getValue().setEnumType(enumMap);
216 private EPackage getEpackage(String xmiFile) {
217 ResourceSet resSet = new ResourceSetImpl();
218 Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
219 Map<String, Object> m = reg.getExtensionToFactoryMap();
220 m.put("xmi", new XMIResourceFactoryImpl());
221 Resource resource = resSet.getResource(URI.createFileURI(xmiFile), true);
223 resource.load(Collections.emptyMap());
224 } catch (IOException e) {
225 logger.error("Error loading Encore Resource for new Model" + e);
228 return (EPackage) resource.getContents().get(0);
231 private HashMap<String, String> getEEnum(EObject obj) {
232 List<String> valueList = new ArrayList<>();
233 HashMap<String, String> returnMap = new HashMap<>();
234 EEnum eenum = (EEnum)obj;
236 String name = eenum.getName();
237 for (EEnumLiteral eEnumLiteral : eenum.getELiterals())
239 Enumerator instance = eEnumLiteral.getInstance();
240 String value = instance.getLiteral();
241 valueList.add(value);
243 returnMap.put(name, valueList.toString());
247 public void getAttributes(String className, String dependency, EPackage root) {
248 List<String> dpendList = new ArrayList<>();
249 if (dependency!=null){
250 dpendList = new ArrayList<>(Arrays.asList(dependency.split(",")));
252 MSAttributeObject msAttributeObject = new MSAttributeObject();
253 msAttributeObject.setClassName(className);
254 String extendClass = getSubTypes(root, className);
255 Map<String, String> returnRefList = getRefAttributeList(root, className, extendClass);
256 Map<String, String> returnAttributeList = getAttributeList(root, className, extendClass);
257 Map<String, Object> returnSubList = getSubAttributeList(root, className, extendClass);
258 HashMap<String, String> returnAnnotation = getAnnotation(root, className, extendClass);
259 msAttributeObject.setAttribute(returnAttributeList);
260 msAttributeObject.setRefAttribute(returnRefList);
261 msAttributeObject.setSubClass(returnSubList);
262 msAttributeObject.setDependency(dpendList.toString());
263 msAttributeObject.addMatchingSet(returnAnnotation);
264 msAttributeObject.setPolicyTempalate(isPolicyTemplate(root, className));
266 this.classMap.put(className, msAttributeObject);
269 private HashMap<String, String> getAnnotation(EPackage root, String className, String extendClass) {
270 TreeIterator<EObject> treeItr = root.eAllContents();
271 boolean requiredAttribute = false;
272 boolean requiredMatchAttribute = false;
273 HashMap<String, String> annotationSet = new HashMap<>();
276 String annotationDict;
278 // Pulling out dependency from file
279 while (treeItr.hasNext()) {
280 EObject obj = treeItr.next();
281 if (obj instanceof EClassifier) {
282 requiredAttribute = isRequiredAttribute(obj, className );
283 requiredMatchAttribute = isRequiredAttribute(obj, extendClass );
286 if (requiredAttribute){
287 if (obj instanceof EStructuralFeature) {
288 EStructuralFeature eStrucClassifier = (EStructuralFeature) obj;
289 if (!eStrucClassifier.getEAnnotations().isEmpty()) {
290 matching = annotationValue(eStrucClassifier, ANNOTATION_TYPE.MATCHING, policy);
292 annotationSet.put(eStrucClassifier.getName(), matching);
294 range = annotationValue(eStrucClassifier, ANNOTATION_TYPE.VALIDATION, policy);
296 annotationSet.put(eStrucClassifier.getName(), range);
298 annotationDict = annotationValue(eStrucClassifier, ANNOTATION_TYPE.DICTIONARY, policy);
299 if (annotationDict!=null){
300 annotationSet.put(eStrucClassifier.getName(), annotationDict);
304 } else if (requiredMatchAttribute && (obj instanceof EStructuralFeature)) {
305 EStructuralFeature eStrucClassifier = (EStructuralFeature) obj;
306 if (!eStrucClassifier.getEAnnotations().isEmpty()) {
307 matching = annotationValue(eStrucClassifier, ANNOTATION_TYPE.MATCHING, policy);
309 if (obj instanceof EReference){
310 EClass refType = ((EReference) obj).getEReferenceType();
311 annotationSet.put(refType.getName(), matching);
312 matchingClass.put(refType.getName(), matching);
314 annotationSet.put(eStrucClassifier.getName(), matching);
320 return annotationSet;
323 private Map<String, Object> getSubAttributeList(EPackage root, String className , String superClass) {
324 TreeIterator<EObject> treeItr = root.eAllContents();
325 boolean requiredAttribute = false;
326 Map<String, Object> subAttribute = new HashMap<>();
327 int rollingCount = 0;
328 int processClass = 0;
331 // Pulling out dependency from file
332 while (treeItr.hasNext() && rollingCount < 2) {
334 EObject obj = treeItr.next();
335 if (obj instanceof EClassifier) {
336 if (isRequiredAttribute(obj, className ) || isRequiredAttribute(obj, superClass )){
337 requiredAttribute = true;
339 requiredAttribute = false;
341 if (requiredAttribute){
344 rollingCount = rollingCount+processClass;
347 if (requiredAttribute && (obj instanceof EStructuralFeature)) {
348 EStructuralFeature eStrucClassifier = (EStructuralFeature) obj;
349 if (!eStrucClassifier.getEAnnotations().isEmpty()) {
350 annotation = annotationTest(eStrucClassifier, configuration, onap);
351 if (annotation && obj instanceof EReference) {
352 EClass refType = ((EReference) obj).getEReferenceType();
353 if(!refType.toString().contains(eProxyURI)){
354 String required = REQUIREDFALSE;
355 if(eStrucClassifier.getLowerBound() == 1){
356 required = REQUIREDTRUE;
358 subAttribute.put(eStrucClassifier.getName(), refType.getName() + required);
367 public String checkDefultValue(String defultValue) {
368 if (defultValue!=null){
369 return DEFAULTVALUE+ defultValue;
371 return ":defaultValue-NA";
375 public String checkRequiredPattern(int upper, int lower) {
377 String pattern = XACMLProperties.getProperty(XACMLRestProperties.PROP_XCORE_REQUIRED_PATTERN);
380 if (upper == Integer.parseInt(pattern.split(",")[1]) && lower==Integer.parseInt(pattern.split(",")[0])){
385 return REQUIREDFALSE;
388 public JSONObject buildJavaObject(Map<String, String> map){
390 return new JSONObject(map);
393 public Map<String, String> getRefAttributeList(EPackage root, String className, String superClass){
395 TreeIterator<EObject> treeItr = root.eAllContents();
396 boolean requiredAttribute = false;
397 HashMap<String, String> refAttribute = new HashMap<>();
398 int rollingCount = 0;
399 int processClass = 0;
401 // Pulling out dependency from file
402 while (treeItr.hasNext()) {
403 EObject obj = treeItr.next();
404 if (obj instanceof EClassifier) {
405 if (isRequiredAttribute(obj, className ) || isRequiredAttribute(obj, superClass )){
406 requiredAttribute = true;
408 requiredAttribute = false;
410 if (requiredAttribute){
413 rollingCount = rollingCount+processClass;
416 if (requiredAttribute && (obj instanceof EStructuralFeature)) {
417 EStructuralFeature eStrucClassifier = (EStructuralFeature) obj;
418 if (!eStrucClassifier.getEAnnotations().isEmpty()) {
419 annotation = annotationTest(eStrucClassifier, configuration, onap);
420 if ( annotation && obj instanceof EReference) {
421 EClass refType = ((EReference) obj).getEReferenceType();
422 if(refType.toString().contains(eProxyURI)){
423 String one = refType.toString().split(eProxyURI)[1];
424 String refValue = StringUtils.replaceEach(one.split("#")[1], new String[]{"//", ")"}, new String[]{"", ""});
425 refAttribute.put(eStrucClassifier.getName(), refValue);
427 String array = arrayCheck(((EStructuralFeature) obj).getUpperBound());
428 String required = REQUIREDFALSE;
429 if(((EStructuralFeature) obj).getLowerBound() == 1){
430 required = REQUIREDTRUE;
432 refAttribute.put(eStrucClassifier.getName(), refType.getName() + array + required);
434 } else if (annotation && obj instanceof EAttributeImpl){
435 EClassifier refType = ((EAttributeImpl) obj).getEType();
436 if (refType instanceof EEnumImpl){
437 String array = arrayCheck(((EStructuralFeature) obj).getUpperBound());
438 String required = REQUIREDFALSE;
439 if(((EStructuralFeature) obj).getLowerBound() == 1){
440 required = REQUIREDTRUE;
442 refAttribute.put(eStrucClassifier.getName(), refType.getName() + array + required);
452 private boolean annotationTest(EStructuralFeature eStrucClassifier, String annotation, String type) {
453 String annotationType;
454 EAnnotation eAnnotation;
458 EList<EAnnotation> value = eStrucClassifier.getEAnnotations();
460 for (int i = 0; i < value.size(); i++){
461 annotationType = value.get(i).getSource();
462 eAnnotation = eStrucClassifier.getEAnnotations().get(i);
463 onapType = eAnnotation.getDetails().get(0).getValue();
464 onapValue = eAnnotation.getDetails().get(0).getKey();
466 if (annotationType.contains(type) && onapType.contains(annotation)){
470 if (annotationType.contains(type) && onapValue.contains(annotation)){
479 private String annotationValue(EStructuralFeature eStrucClassifier, ANNOTATION_TYPE annotation, String type) {
480 String annotationType;
481 EAnnotation eAnnotation;
483 String onapValue = null;
485 EList<EAnnotation> value = eStrucClassifier.getEAnnotations();
487 for (int i = 0; i < value.size(); i++){
488 annotationType = value.get(i).getSource();
489 eAnnotation = eStrucClassifier.getEAnnotations().get(i);
490 onapType = eAnnotation.getDetails().get(0).getKey();
491 if (annotationType.contains(type) && onapType.compareToIgnoreCase(annotation.toString())==0){
492 onapValue = eAnnotation.getDetails().get(0).getValue();
493 if (annotation == ANNOTATION_TYPE.VALIDATION){
496 return onapType + "-" + onapValue;
503 public boolean isRequiredAttribute(EObject obj, String className){
504 EClassifier eClassifier = (EClassifier) obj;
505 String workingClass = eClassifier.getName().trim();
506 if (workingClass.equalsIgnoreCase(className)){
513 private boolean isPolicyTemplate(EPackage root, String className){
515 for (EClassifier classifier : root.getEClassifiers()){
516 if (classifier instanceof EClass) {
517 EClass eClass = (EClass)classifier;
518 if (eClass.getName().contentEquals(className)){
519 EList<EAnnotation> value = eClass.getEAnnotations();
520 for (EAnnotation workingValue : value){
521 EMap<String, String> keyMap = workingValue.getDetails();
522 if (keyMap.containsKey("policyTemplate")){
531 private String getSubTypes(EPackage root, String className) {
532 String returnSubTypes = null;
533 for (EClassifier classifier : root.getEClassifiers()){
534 if (classifier instanceof EClass) {
535 EClass eClass = (EClass)classifier;
537 for (EClass eSuperType : eClass.getEAllSuperTypes())
539 if (eClass.getName().contentEquals(className)){
540 returnSubTypes = eSuperType.getName();
545 return returnSubTypes;
548 public Map<String, String> getAttributeList(EPackage root, String className, String superClass){
550 TreeIterator<EObject> treeItr = root.eAllContents();
551 boolean requiredAttribute = false;
552 HashMap<String, String> refAttribute = new HashMap<>();
554 boolean dictionaryTest;
558 // Pulling out dependency from file
559 while (treeItr.hasNext()) {
560 EObject obj = treeItr.next();
561 if (obj instanceof EClassifier) {
562 if (isRequiredAttribute(obj, className ) || isRequiredAttribute(obj, superClass )){
563 requiredAttribute = true;
565 requiredAttribute = false;
570 if (requiredAttribute && (obj instanceof EStructuralFeature)) {
571 EStructuralFeature eStrucClassifier = (EStructuralFeature) obj;
572 if (!eStrucClassifier.getEAnnotations().isEmpty()) {
573 annotation = annotationTest(eStrucClassifier, configuration, onap);
574 dictionaryTest = annotationTest(eStrucClassifier, dictionary, policy);
575 EClassifier refType = ((EStructuralFeature) obj).getEType();
576 if (annotation && !(obj instanceof EReference) && !(refType instanceof EEnumImpl)) {
577 String name = eStrucClassifier.getName();
579 eType = annotationValue(eStrucClassifier, ANNOTATION_TYPE.DICTIONARY, policy);
581 eType = eStrucClassifier.getEType().getInstanceClassName();
583 defaultValue = checkDefultValue(((EStructuralFeature) obj).getDefaultValueLiteral());
585 String array = arrayCheck(((EStructuralFeature) obj).getUpperBound());
586 String required = checkRequiredPattern(((EStructuralFeature) obj).getUpperBound(), ((EStructuralFeature) obj).getLowerBound());
587 String attributeValue = eType + defaultValue + required + array;
588 refAttribute.put(name, attributeValue);
597 public String arrayCheck(int upperBound) {
599 if (upperBound == -1){
606 public List<String> getDependencyList(EClassifier eClassifier){
607 List<String> returnValue = new ArrayList<>();;
608 EList<EClass> somelist = ((EClass) eClassifier).getEAllSuperTypes();
609 if (somelist.isEmpty()){
612 for(EClass depend: somelist){
613 if (depend.toString().contains(eProxyURI)){
614 String one = depend.toString().split(eProxyURI)[1];
615 String value = StringUtils.replaceEach(one.split("#")[1], new String[]{"//", ")"}, new String[]{"", ""});
616 returnValue.add(value);
623 public Map<String, String> buildSubList(Map<String, String> subClassAttributes, Map<String, MSAttributeObject> classMap, String className){
624 Map<String, String> missingValues = new HashMap<>();
625 Map<String, String> workingMap;
628 for ( Entry<String, String> map : classMap.get(className).getRefAttribute().entrySet()){
629 String value = map.getValue().split(":")[0];
631 classMap.get(className).getEnumType();
632 enumType = classMap.get(className).getEnumType().containsKey(value);
634 workingMap = classMap.get(value).getRefAttribute();
635 for ( Entry<String, String> subMab : workingMap.entrySet()){
636 String value2 = subMab.getValue().split(":")[0];
637 if (!subClassAttributes.containsValue(value2)){
638 missingValues.put(subMab.getKey(), subMab.getValue());
646 return missingValues;
649 public Map<String, Map<String, String>> recursiveReference(Map<String, MSAttributeObject> classMap, String className){
651 Map<String, Map<String, String>> returnObject = new HashMap<>();
652 Map<String, String> returnClass = getRefclass(classMap, className);
653 returnObject.put(className, returnClass);
654 for (Entry<String, String> reAttribute :returnClass.entrySet()){
655 if (reAttribute.getValue().split(":")[1].contains("MANY") &&
656 classMap.get(reAttribute.getValue().split(":")[0]) != null){
657 returnObject.putAll(recursiveReference(classMap, reAttribute.getValue().split(":")[0]));
666 public String createJson(Map<String, MSAttributeObject> classMap, String className) {
668 Map<String, Map<String, String>> myObject = new HashMap<>();
669 for ( Entry<String, String> map : classMap.get(className).getRefAttribute().entrySet()){
670 String value = map.getValue().split(":")[0];
672 enumType = classMap.get(className).getEnumType().containsKey(value);
673 if (!enumType && map.getValue().split(":")[1].contains("MANY")){
674 Map<String, Map<String, String>> testRecursive = recursiveReference(classMap, map.getValue().split(":")[0] );
675 myObject.putAll(testRecursive);
680 Gson gson = new Gson();
681 return gson.toJson(myObject);
684 public Map<String, String> getRefclass(Map<String, MSAttributeObject> classMap, String className){
685 HashMap<String, String> missingValues = new HashMap<>();
687 if (classMap.get(className).getAttribute()!=null || !classMap.get(className).getAttribute().isEmpty()){
688 missingValues.putAll(classMap.get(className).getAttribute());
691 if (classMap.get(className).getRefAttribute()!=null || !classMap.get(className).getRefAttribute().isEmpty()){
692 missingValues.putAll(classMap.get(className).getRefAttribute());
695 return missingValues;
698 public String createSubAttributes(List<String> dependency, Map<String, MSAttributeObject> classMap, String modelName) {
700 HashMap <String, Object> workingMap = new HashMap<>();
701 MSAttributeObject tempObject;
702 if (dependency!=null){
703 if (dependency.isEmpty()){
706 dependency.add(modelName);
707 for (String element: dependency){
708 tempObject = classMap.get(element);
709 if (tempObject!=null){
710 workingMap.putAll(classMap.get(element).getSubClass());
715 return createJson(classMap, modelName);
718 public List<String> getFullDependencyList(List<String> dependency, Map<String,MSAttributeObject > classMap) {
719 ArrayList<String> returnList = new ArrayList<>();
720 ArrayList<String> workingList;
721 returnList.addAll(dependency);
722 for (String element : dependency ){
723 if (classMap.containsKey(element)){
724 MSAttributeObject value = classMap.get(element);
725 String rawValue = StringUtils.replaceEach(value.getDependency(), new String[]{"[", "]"}, new String[]{"", ""});
726 workingList = new ArrayList<>(Arrays.asList(rawValue.split(",")));
727 for(String depend : workingList){
728 if (!returnList.contains(depend) && !depend.isEmpty()){
729 returnList.add(depend.trim());
741 public void parseTosca (String fileName){
742 LinkedHashMap<String,String> map= new LinkedHashMap<>();
747 parseDataAndPolicyNodes(map);
749 LinkedHashMap<String,String> dataMapForJson=parseDataNodes(map);
751 constructJsonForDataFields(dataMapForJson);
753 LinkedHashMap<String,LinkedHashMap<String,String>> mapKey= parsePolicyNodes(map);
755 createAttributes(mapKey);
757 } catch (IOException e) {
763 @SuppressWarnings("unchecked")
764 public LinkedHashMap<String, String> load(String fileName) throws IOException {
765 File newConfiguration = new File(fileName);
766 StringBuilder orderInfo = new StringBuilder("[");
767 Yaml yaml = new Yaml();
768 LinkedHashMap<Object, Object> yamlMap = null;
769 try(InputStream is = new FileInputStream(newConfiguration)){
770 yamlMap = (LinkedHashMap<Object, Object>) yaml.load(is);
771 } catch (FileNotFoundException e) {
775 StringBuilder sb = new StringBuilder();
776 LinkedHashMap<String, String> settings = new LinkedHashMap<>();
777 if (yamlMap == null) {
783 orderedElements.stream().forEach((string) -> {
784 orderInfo.append(string);
785 orderInfo.append(",");
786 logger.info("Content: " + string);
789 orderInfo.append("]");
791 dataOrderInfo = orderInfo.toString();
792 dataOrderInfo = dataOrderInfo.replace(",]", "]");
794 logger.info("dataOrderInfo :" + dataOrderInfo);
796 List<String> path = new ArrayList <>();
797 serializeMap(settings, sb, path, yamlMap);
801 @SuppressWarnings({ "unchecked", "rawtypes" })
802 private void serializeMap(LinkedHashMap<String, String> settings, StringBuilder sb, List<String> path, Map<Object, Object> yamlMap) {
803 for (Map.Entry<Object, Object> entry : yamlMap.entrySet()) {
805 if (entry.getValue() instanceof Map) {
806 path.add((String) entry.getKey());
807 serializeMap(settings, sb, path, (Map<Object, Object>) entry.getValue());
808 path.remove(path.size() - 1);
809 } else if (entry.getValue() instanceof List) {
810 path.add((String) entry.getKey());
811 serializeList(settings, sb, path, (List) entry.getValue());
812 path.remove(path.size() - 1);
814 serializeValue(settings, sb, path, (String) entry.getKey(), entry.getValue());
819 @SuppressWarnings("unchecked")
820 private void serializeList(LinkedHashMap<String, String> settings, StringBuilder sb, List<String> path, List<String> yamlList) {
822 for (Object listEle : yamlList) {
823 if (listEle instanceof Map) {
824 path.add(Integer.toString(counter));
825 serializeMap(settings, sb, path, (Map<Object, Object>) listEle);
826 path.remove(path.size() - 1);
827 } else if (listEle instanceof List) {
828 path.add(Integer.toString(counter));
829 serializeList(settings, sb, path, (List<String>) listEle);
830 path.remove(path.size() - 1);
832 serializeValue(settings, sb, path, Integer.toString(counter), listEle);
838 private void serializeValue(LinkedHashMap<String, String> settings, StringBuilder sb, List<String> path, String name, Object value) {
843 for (String pathEle : path) {
844 sb.append(pathEle).append('.');
847 settings.put(sb.toString(), value.toString());
851 void parseDataAndPolicyNodes(LinkedHashMap<String,String> map){
852 for(String key:map.keySet()){
853 if(key.contains("policy.nodes.Root"))
857 else if(key.contains("policy.nodes")){
858 String wordToFind = "policy.nodes.";
859 int indexForPolicyNode=key.indexOf(wordToFind);
860 String subNodeString= key.substring(indexForPolicyNode+13, key.length());
862 stringBetweenDots(subNodeString);
864 else if(key.contains("policy.data")){
865 String wordToFind="policy.data.";
866 int indexForPolicyNode=key.indexOf(wordToFind);
867 String subNodeString= key.substring(indexForPolicyNode+12, key.length());
869 stringBetweenDotsForDataFields(subNodeString);
874 // Second index of dot should be returned.
875 public int stringBetweenDots(String str){
876 String stringToSearch=str;
877 String[]ss=stringToSearch.split("\\.");
881 uniqueKeys.add(ss[2]);
885 return uniqueKeys.size();
889 public void stringBetweenDotsForDataFields(String str){
890 String stringToSearch=str;
891 String[]ss=stringToSearch.split("\\.");
896 uniqueDataKeys.add(ss[0]+"%"+ss[2]);
901 void constructJsonForDataFields(LinkedHashMap<String,String> dataMapForJson){
902 LinkedHashMap<String,LinkedHashMap<String,String>> dataMapKey= new LinkedHashMap <>();
903 LinkedHashMap<String, String> hmSub;
904 for(Map.Entry<String, String> entry: dataMapForJson.entrySet()){
905 String uniqueDataKey= entry.getKey();
906 String[] uniqueDataKeySplit=uniqueDataKey.split("%");
907 String value= dataMapForJson.get(uniqueDataKey);
908 if(dataMapKey.containsKey(uniqueDataKeySplit[0])){
909 hmSub = dataMapKey.get(uniqueDataKeySplit[0]);
910 hmSub.put(uniqueDataKeySplit[1], value);
913 hmSub=new LinkedHashMap <>();
914 hmSub.put(uniqueDataKeySplit[1], value);
917 dataMapKey.put(uniqueDataKeySplit[0], hmSub);
920 JSONObject mainObject= new JSONObject();
922 for(Map.Entry<String,LinkedHashMap<String,String>> entry: dataMapKey.entrySet()){
923 String s=entry.getKey();
924 json= new JSONObject();
925 HashMap<String,String> jsonHm=dataMapKey.get(s);
926 for(Map.Entry<String,String> entryMap:jsonHm.entrySet()){
927 String key=entryMap.getKey();
928 json.put(key, jsonHm.get(key));
930 mainObject.put(s,json);
932 Iterator<String> keysItr = mainObject.keys();
933 while(keysItr.hasNext()) {
934 String key = keysItr.next();
935 String value = mainObject.get(key).toString();
936 retmap.put(key, value);
939 logger.info("#############################################################################");
940 logger.info(mainObject);
941 logger.info("###############################################################################");
944 LinkedHashMap<String,String> parseDataNodes(LinkedHashMap<String,String> map){
945 LinkedHashMap<String,String> dataMapForJson=new LinkedHashMap <>();
946 matchableValues = new HashMap <>();
947 for(String uniqueDataKey: uniqueDataKeys){
948 if(uniqueDataKey.contains("%")){
949 String[] uniqueDataKeySplit= uniqueDataKey.split("%");
950 String findType=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+TYPE;
951 String typeValue=map.get(findType);
952 logger.info(typeValue);
954 String findRequired=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+REQUIRED;
955 String requiredValue= map.get(findRequired);
957 String matchable =DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+MATCHABLE;
959 String matchableValue= map.get(matchable);
961 if(matchableValue != null && matchableValue.equalsIgnoreCase("true")){
962 if(uniqueDataKey.contains("%")){
963 String[] keys= uniqueDataKey.split("%");
964 String key=keys[keys.length -1];
965 matchableValues.put(key, MATCHINGTRUE);
967 matchableValues.put(uniqueDataKey, MATCHINGTRUE);
971 if(requiredValue == null || requiredValue.isEmpty()){
972 requiredValue = "false";
974 if(typeValue != null && (typeValue.equalsIgnoreCase(STRING)||
975 typeValue.equalsIgnoreCase(INTEGER))){
977 String findDefault=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+DEFAULT;
978 String defaultValue= map.get(findDefault);
979 logger.info("defaultValue is:"+ defaultValue);
980 logger.info("requiredValue is:"+ requiredValue);
982 StringBuilder attributeIndividualStringBuilder= new StringBuilder();
983 attributeIndividualStringBuilder.append(typeValue+DEFAULTVALUE);
984 attributeIndividualStringBuilder.append(defaultValue+REQUIREDVALUE);
985 attributeIndividualStringBuilder.append(requiredValue+MANYFALSE);
986 dataMapForJson.put(uniqueDataKey, attributeIndividualStringBuilder.toString());
988 else if(typeValue != null && typeValue.equalsIgnoreCase(LIST)){
989 logger.info("requiredValue is:"+ requiredValue);
990 String findList= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.type";
991 String listValue=map.get(findList);
993 logger.info("Type of list is:"+ listValue);
995 if(listValue.contains(".")){
996 String trimValue=listValue.substring(listValue.lastIndexOf('.')+1);
997 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
998 referenceIndividualStringBuilder.append(trimValue+REQUIREDVALUE);
999 referenceIndividualStringBuilder.append(requiredValue+MANYTRUE);
1000 dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString());
1003 StringBuilder stringListItems= new StringBuilder();
1004 stringListItems.append(uniqueDataKeySplit[1].toUpperCase()+REQUIREDVALUE+requiredValue +MANYFALSE);
1005 dataMapForJson.put(uniqueDataKey, stringListItems.toString());
1006 dataListBuffer.append(uniqueDataKeySplit[1].toUpperCase()+"=[");
1007 for(int i=0;i<10;i++){
1008 String findConstraints= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.constraints.0.valid_values."+i;
1009 logger.info("findConstraints => " + findConstraints);
1010 String constraintsValue=map.get(findConstraints);
1011 logger.info("constraintsValue => " + constraintsValue);
1012 if(constraintsValue==null){
1016 logger.info("constraintsValue => " + constraintsValue);
1017 if(constraintsValue.contains("=")){
1018 constraintsValue = constraintsValue.replace("=", "equal-sign");
1020 dataConstraints.add(constraintsValue);
1021 dataListBuffer.append(constraintsValue+",");
1024 dataListBuffer.append("]#");
1025 logger.info(dataListBuffer);
1030 String findUserDefined=DATATYPE+uniqueDataKeySplit[0]+"."+"properties"+"."+uniqueDataKeySplit[1]+TYPE;
1031 String userDefinedValue=map.get(findUserDefined);
1032 String trimValue=userDefinedValue.substring(userDefinedValue.lastIndexOf('.')+1);
1033 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
1034 referenceIndividualStringBuilder.append(trimValue+REQUIREDVALUE);
1035 referenceIndividualStringBuilder.append(requiredValue+MANYFALSE);
1036 dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString());
1042 return dataMapForJson;
1046 LinkedHashMap<String, LinkedHashMap<String, String>> parsePolicyNodes(Map<String,String> map){
1047 LinkedHashMap<String,LinkedHashMap<String,String>> mapKey= new LinkedHashMap <>();
1048 for(String uniqueKey: uniqueKeys){
1049 LinkedHashMap<String,String> hm;
1051 for(Map.Entry<String,String> entry:map.entrySet()){
1052 String key=entry.getKey();
1053 if(key.contains(uniqueKey) && key.contains("policy.nodes")){
1054 if(mapKey.containsKey(uniqueKey)){
1055 hm = mapKey.get(uniqueKey);
1056 String keyStr= key.substring(key.lastIndexOf('.')+1);
1057 String valueStr= map.get(key);
1058 if(("type").equals(keyStr)){
1059 if(!key.contains("entry_schema"))
1061 hm.put(keyStr,valueStr);
1064 hm.put(keyStr,valueStr);
1068 hm = new LinkedHashMap <>();
1069 String keyStr= key.substring(key.lastIndexOf('.')+1);
1070 String valueStr= map.get(key);
1071 if(("type").equals(keyStr)){
1072 if(!key.contains("entry_schema"))
1074 hm.put(keyStr,valueStr);
1077 hm.put(keyStr,valueStr);
1079 mapKey.put(uniqueKey, hm);
1087 void createAttributes(LinkedHashMap<String,LinkedHashMap<String,String>> mapKey){
1088 StringBuilder attributeStringBuilder= new StringBuilder();
1089 StringBuilder referenceStringBuilder= new StringBuilder();
1090 StringBuilder listBuffer= new StringBuilder();
1091 List<String> constraints= new ArrayList<>();
1092 for(Map.Entry<String,LinkedHashMap<String,String>> entry: mapKey.entrySet()){
1093 String keySetString= entry.getKey();
1094 LinkedHashMap<String,String> keyValues=mapKey.get(keySetString);
1095 if(STRING.equalsIgnoreCase(keyValues.get("type"))||
1096 INTEGER.equalsIgnoreCase(keyValues.get("type"))){
1097 StringBuilder attributeIndividualStringBuilder= new StringBuilder();
1098 attributeIndividualStringBuilder.append(keySetString+"=");
1099 attributeIndividualStringBuilder.append(keyValues.get("type")+DEFAULTVALUE);
1100 attributeIndividualStringBuilder.append(keyValues.get("default")+REQUIREDVALUE);
1101 attributeIndividualStringBuilder.append(keyValues.get("required")+MANYFALSE);
1102 attributeStringBuilder.append(attributeIndividualStringBuilder+",");
1103 if("true".equalsIgnoreCase(keyValues.get(MATCHABLEKEY))){
1104 matchableValues.put(keySetString, MATCHINGTRUE);
1107 else if(LIST.equalsIgnoreCase(keyValues.get("type"))){
1109 if(("true").equalsIgnoreCase(keyValues.get(MATCHABLEKEY))){
1110 matchableValues.put(keySetString, MATCHINGTRUE);
1113 Set<String> keys= keyValues.keySet();
1114 Iterator<String> itr=keys.iterator();
1115 boolean isDefinedType = false;
1116 while(itr.hasNext()){
1117 String key= itr.next();
1118 if((!("type").equals(key) ||("required").equals(key)))
1120 String value= keyValues.get(key);
1121 //The "." in the value determines if its a string or a user defined type.
1122 if (!value.contains(".")){
1124 if(StringUtils.isNumeric(key) ){ //only integer key for the value of Constrains
1125 constraints.add(keyValues.get(key));
1128 //This is user defined type
1129 String trimValue=value.substring(value.lastIndexOf('.')+1);
1130 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
1131 referenceIndividualStringBuilder.append(keySetString+"="+trimValue+MANYTRUE);
1132 referenceStringBuilder.append(referenceIndividualStringBuilder+",");
1133 isDefinedType = true;
1139 if(!isDefinedType && LIST.equalsIgnoreCase(keyValues.get("type"))){ //type is not user defined and is a list but no constraints defined.
1140 if(constraints == null || constraints.isEmpty()){
1141 referenceStringBuilder.append(keySetString+"=MANY-true"+",");
1145 //User defined Datatype.
1146 if("true".equalsIgnoreCase(keyValues.get(MATCHABLEKEY))){
1147 matchableValues.put(keySetString, MATCHINGTRUE);
1149 String value=keyValues.get("type");
1150 if(value != null && !value.isEmpty()){
1151 String trimValue=value.substring(value.lastIndexOf('.')+1);
1152 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
1153 referenceIndividualStringBuilder.append(keySetString+"="+trimValue+MANYFALSE);
1154 referenceStringBuilder.append(referenceIndividualStringBuilder+",");
1156 logger.info("keyValues.get(type) is null/empty");
1160 if(constraints!=null && !constraints.isEmpty()){
1162 listBuffer.append(keySetString.toUpperCase()+"=[");
1163 for(String str:constraints){
1164 listBuffer.append(str+",");
1166 listBuffer.append("]#");
1167 logger.info(listBuffer);
1170 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
1171 referenceIndividualStringBuilder.append(keySetString+"="+keySetString.toUpperCase()+MANYFALSE);
1172 referenceStringBuilder.append(referenceIndividualStringBuilder+",");
1173 constraints.clear();
1177 dataListBuffer.append(listBuffer);
1180 logger.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
1181 logger.info("Whole attribute String is:"+attributeStringBuilder);
1182 logger.info("Whole reference String is:"+referenceStringBuilder);
1183 logger.info("List String is:"+listBuffer);
1184 logger.info("Data list buffer is:"+dataListBuffer);
1185 logger.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
1187 this.listConstraints=dataListBuffer.toString();
1188 this.referenceAttributes=referenceStringBuilder.toString();
1189 this.attributeString=attributeStringBuilder.toString();
1192 @SuppressWarnings("unchecked")
1193 public void findNode(LinkedHashMap<Object, Object> map) {
1195 map.forEach((key,value) -> {
1196 // if the value is properties and its type is map object, then save all the keys
1197 if(key.equals("properties") && value instanceof Map){
1198 saveNodes((LinkedHashMap<?, ?>)value);
1201 if(!key.equals("policy.nodes.Root") && value instanceof Map){
1202 //value is a Map object, then make a recursive call
1203 findNode((LinkedHashMap<Object, Object>) value);
1209 public void saveNodes(LinkedHashMap<?, ?> map) {
1211 map.forEach((key,value) -> {
1213 orderedElements.add((String)key);
1219 public String getAttributeString() {
1220 return attributeString;
1222 public void setAttributeString(String attributeString) {
1223 this.attributeString = attributeString;
1226 public LinkedHashMap<String, Object> getRetmap() {
1230 public void setRetmap(LinkedHashMap<String, Object> retmap) {
1231 this.retmap = retmap;
1233 public Map<String, String> getMatchableValues() {
1234 return matchableValues;
1237 public void setMatchableValues(Map<String, String> matchableValues) {
1238 this.matchableValues = matchableValues;
1240 public String getReferenceAttributes() {
1241 return referenceAttributes;
1244 public void setReferenceAttributes(String referenceAttributes) {
1245 this.referenceAttributes = referenceAttributes;
1247 public String getListConstraints() {
1248 return listConstraints;
1251 public void setListConstraints(String listConstraints) {
1252 this.listConstraints = listConstraints;
1254 public String getDataOrderInfo() {
1255 return dataOrderInfo;
1258 public void setDataOrderInfo(String dataOrderInfo) {
1259 this.dataOrderInfo = dataOrderInfo;