From 779125e31adbcc59a9864843b523bd6ed2751cbb Mon Sep 17 00:00:00 2001 From: liamfallon Date: Mon, 18 Nov 2019 12:36:28 +0000 Subject: Unit/SONAR/Checkstyle in ONAP-REST Util package of ONAP-REST, with JUnit added and SONAR/Checkstyle issues addressed. In cases where a class name change caused an update in another package, the license header on files for those knock on changes are not updated. Issue-ID: POLICY-2131 Change-Id: Ic134408efe76b9838f5607a07f1735d12bd41032 Signed-off-by: liamfallon --- .../onap/policy/rest/util/LockdownListener.java | 12 +- .../onap/policy/rest/util/MSAttributeObject.java | 150 -- .../onap/policy/rest/util/MSAttributeValue.java | 60 - .../org/onap/policy/rest/util/MSModelUtils.java | 1485 ---------------- .../onap/policy/rest/util/MsAttributeObject.java | 76 + .../onap/policy/rest/util/MsAttributeValue.java | 35 + .../org/onap/policy/rest/util/MsModelUtils.java | 1804 ++++++++++++++++++++ .../onap/policy/rest/util/PDPPolicyContainer.java | 344 ---- .../org/onap/policy/rest/util/ParserException.java | 15 +- .../onap/policy/rest/util/PdpPolicyContainer.java | 487 ++++++ .../org/onap/policy/rest/util/PolicyContainer.java | 41 +- .../rest/util/PolicyItemSetChangeNotifier.java | 33 +- .../onap/policy/rest/util/PolicyValidation.java | 563 +++--- .../rest/util/PolicyValidationRequestWrapper.java | 260 +-- .../java/org/onap/policy/rest/XacmlRestTest.java | 17 +- .../policy/rest/jpa/GetterSetterToStringTest.java | 57 + .../java/org/onap/policy/rest/jpa/ModelsTest.java | 57 - .../policy/rest/util/DummyPolicyContainer.java | 77 + .../policy/rest/util/MSAttributeObjectTest.java | 76 - .../onap/policy/rest/util/MSModelUtilsTest.java | 160 -- .../policy/rest/util/MsAttributeObjectTest.java | 79 + .../onap/policy/rest/util/MsModelUtilsTest.java | 167 ++ .../policy/rest/util/PDPPolicyContainerTest.java | 138 -- .../onap/policy/rest/util/ParserExceptionTest.java | 34 + .../policy/rest/util/PdpPolicyContainerTest.java | 267 +++ .../rest/util/PolicyItemSetChangeNotifierTest.java | 69 +- .../policy/rest/util/PolicyValidationTest.java | 34 +- 27 files changed, 3629 insertions(+), 2968 deletions(-) delete mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/util/MSAttributeObject.java delete mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/util/MSAttributeValue.java delete mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/util/MSModelUtils.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/util/MsAttributeObject.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/util/MsAttributeValue.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/util/MsModelUtils.java delete mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/util/PDPPolicyContainer.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/util/PdpPolicyContainer.java create mode 100644 ONAP-REST/src/test/java/org/onap/policy/rest/jpa/GetterSetterToStringTest.java delete mode 100644 ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ModelsTest.java create mode 100644 ONAP-REST/src/test/java/org/onap/policy/rest/util/DummyPolicyContainer.java delete mode 100644 ONAP-REST/src/test/java/org/onap/policy/rest/util/MSAttributeObjectTest.java delete mode 100644 ONAP-REST/src/test/java/org/onap/policy/rest/util/MSModelUtilsTest.java create mode 100644 ONAP-REST/src/test/java/org/onap/policy/rest/util/MsAttributeObjectTest.java create mode 100644 ONAP-REST/src/test/java/org/onap/policy/rest/util/MsModelUtilsTest.java delete mode 100644 ONAP-REST/src/test/java/org/onap/policy/rest/util/PDPPolicyContainerTest.java create mode 100644 ONAP-REST/src/test/java/org/onap/policy/rest/util/ParserExceptionTest.java create mode 100644 ONAP-REST/src/test/java/org/onap/policy/rest/util/PdpPolicyContainerTest.java (limited to 'ONAP-REST') diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/LockdownListener.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/LockdownListener.java index 1111609d8..019e15db7 100644 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/util/LockdownListener.java +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/LockdownListener.java @@ -3,13 +3,14 @@ * ONAP-REST * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,19 +19,16 @@ * ============LICENSE_END========================================================= */ -/** - * - */ package org.onap.policy.rest.util; public interface LockdownListener { /** - * lockdown has been set in database + * lockdown has been set in database. */ public void lockdownSet(); /** - * lockdown has been unset in the database + * lockdown has been unset in the database. */ public void lockdownUnset(); } diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/MSAttributeObject.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/MSAttributeObject.java deleted file mode 100644 index 3d27499da..000000000 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/util/MSAttributeObject.java +++ /dev/null @@ -1,150 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP-REST - * ================================================================================ - * Copyright (C) 2017,2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.rest.util; - -import java.util.HashMap; -import java.util.Map; - -public class MSAttributeObject { - - private String className; - private Map attribute = new HashMap<>(); - private Map refAttribute = new HashMap<>(); - private Map subClass = new HashMap<>(); - private String dependency; - private Map enumType = new HashMap<>(); - private Map matchingSet = new HashMap<>(); - private boolean policyTempalate; - private String ruleFormation; - private String dataOrderInfo; - - public Map getRefAttribute() { - return refAttribute; - } - - public void setRefAttribute(Map refAttribute) { - this.refAttribute = refAttribute; - } - - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Map getAttribute() { - return attribute; - } - - public void setAttribute(Map attribute) { - this.attribute = attribute; - } - - public Map getEnumType() { - return enumType; - } - - public void setEnumType(Map enumType) { - this.enumType = enumType; - } - - public void addAttribute(String key, String value) { - this.attribute.put(key, value); - } - - public void addRefAttribute(String key, String value) { - this.refAttribute.put(key, value); - } - - public void addAllAttribute(Map map) { - this.attribute.putAll(map); - } - - public void addAllRefAttribute(Map map) { - this.refAttribute.putAll(map); - } - - public Map getSubClass() { - return subClass; - } - - public void setSubClass(Map subClass) { - this.subClass = subClass; - } - - public void addAllSubClass(Map subClass) { - this.subClass.putAll(subClass); - } - - public String getDependency() { - return dependency; - } - - public void setDependency(String dependency) { - this.dependency = dependency; - } - - public void addSingleEnum(String key, String value) { - this.enumType.put(key, value); - } - - public Map getMatchingSet() { - return matchingSet; - } - - public void setMatchingSet(Map matchingSet) { - this.matchingSet = matchingSet; - } - - public void addMatchingSet(String key, String value) { - this.matchingSet.put(key, value); - } - - public void addMatchingSet(Map matchingSet) { - this.matchingSet.putAll(matchingSet); - } - - public boolean isPolicyTempalate() { - return policyTempalate; - } - - public void setPolicyTempalate(boolean policyTempalate) { - this.policyTempalate = policyTempalate; - } - - public String getRuleFormation() { - return ruleFormation; - } - - public void setRuleFormation(String ruleFormation) { - this.ruleFormation = ruleFormation; - } - - public String getDataOrderInfo() { - return dataOrderInfo; - } - - public void setDataOrderInfo(String dataOrderInfo) { - this.dataOrderInfo = dataOrderInfo; - } -} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/MSAttributeValue.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/MSAttributeValue.java deleted file mode 100644 index c8a217d9f..000000000 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/util/MSAttributeValue.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP-REST - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.rest.util; - -public class MSAttributeValue{ - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - public Boolean getRequired() { - return required; - } - public void setRequired(Boolean required) { - this.required = required; - } - public Boolean getArrayValue() { - return arrayValue; - } - public void setArrayValue(Boolean arrayValue) { - this.arrayValue = arrayValue; - } - public String getDefaultValue() { - return defaultValue; - } - public void setDefaultValue(String defaultValue) { - this.defaultValue = defaultValue; - } - private String name; - private String type; - private Boolean required; - private Boolean arrayValue; - private String defaultValue; - -} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/MSModelUtils.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/MSModelUtils.java deleted file mode 100644 index 29fb635b2..000000000 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/util/MSModelUtils.java +++ /dev/null @@ -1,1485 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP-REST - * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. - * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. - * Modifications Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.rest.util; - -import com.att.research.xacml.util.XACMLProperties; -import com.google.gson.Gson; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.eclipse.emf.common.util.EList; -import org.eclipse.emf.common.util.EMap; -import org.eclipse.emf.common.util.Enumerator; -import org.eclipse.emf.common.util.TreeIterator; -import org.eclipse.emf.common.util.URI; -import org.eclipse.emf.ecore.EAnnotation; -import org.eclipse.emf.ecore.EClass; -import org.eclipse.emf.ecore.EClassifier; -import org.eclipse.emf.ecore.EEnum; -import org.eclipse.emf.ecore.EEnumLiteral; -import org.eclipse.emf.ecore.EObject; -import org.eclipse.emf.ecore.EPackage; -import org.eclipse.emf.ecore.EReference; -import org.eclipse.emf.ecore.EStructuralFeature; -import org.eclipse.emf.ecore.impl.EAttributeImpl; -import org.eclipse.emf.ecore.impl.EEnumImpl; -import org.eclipse.emf.ecore.resource.Resource; -import org.eclipse.emf.ecore.resource.ResourceSet; -import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; -import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl; -import org.json.JSONObject; -import org.onap.policy.rest.XacmlRestProperties; -import org.onap.policy.rest.dao.CommonClassDao; -import org.onap.policy.rest.jpa.DictionaryData; -import org.yaml.snakeyaml.Yaml; - - -public class MSModelUtils { - - private static final Log logger = LogFactory.getLog(MSModelUtils.class); - - private HashMap classMap = new HashMap<>(); - private HashMap enumMap = new HashMap<>(); - private HashMap matchingClass = new HashMap<>(); - private String configuration = "configuration"; - private String dictionary = "dictionary"; - private String onap = ""; - private String policy = ""; - private String eProxyURI = "eProxyURI:"; - private List orderedElements = new ArrayList<>(); - private String dataOrderInfo = ""; - private Set uniqueDataKeys = new HashSet<>(); - private Set uniqueKeys = new HashSet<>(); - private String listConstraints = null; - private String referenceAttributes; - private LinkedHashMap retmap = new LinkedHashMap<>(); - private Map matchableValues; - private static final String PROPERTIES = ".properties."; - private static final String DATATYPE = "data_types.policy.data."; - private static final String TYPE = ".type"; - private static final String REQUIRED = ".required"; - private static final String DICTIONARYNAME = "dictionaryName"; - private static final String DICTIONARY = "dictionary:"; - private static final String MATCHABLE = ".matchable"; - public static final String STRING = "string"; - public static final String INTEGER = "integer"; - private static final String BOOLEAN = "boolean"; - public static final String LIST = "list"; - public static final String MAP = "map"; - private static final String DEFAULT = ".default"; - private static final String MANYFALSE = ":MANY-false"; - private static final String DESCRIPTION = ".description"; - - private static final String MANYTRUE = ":MANY-true"; - private static final String DEFAULTVALUE = ":defaultValue-"; - private static final String REQUIREDVALUE = ":required-"; - private static final String MATCHABLEKEY = "matchable"; - private static final String REQUIREDFALSE = ":required-false"; - private static final String REQUIREDTRUE = ":required-true"; - private static final String MATCHINGTRUE = "matching-true"; - private static final String DESCRIPTION_KEY = "description"; - private static final String DESCRIPTION_TOKEN = ":description-"; - private static final String PROPERTIES_KEY = "properties"; - private static final String DATA_TYPE = "data_types"; - private static final String ERROR = "error"; - private static final String NODE_TYPE = "node_types"; - private static final String TOSCA_DEFINITION_VERSION = "tosca_definitions_version"; - private static final String TOSCA_SIMPLE_YAML_1_0_0 = "tosca_simple_yaml_1_0_0"; - private static final String JSON_MODEL = "JSON_MODEL"; - private StringBuilder dataListBuffer = new StringBuilder(); - private List dataConstraints = new ArrayList<>(); - private String attributeString = null; - private boolean isDuplicatedAttributes = false; - private String jsonRuleFormation = null; - - private static CommonClassDao commonClassDao; - - public MSModelUtils() { - // Default Constructor - } - - public MSModelUtils(CommonClassDao commonClassDao) { - MSModelUtils.commonClassDao = commonClassDao; - } - - public MSModelUtils(String onap, String policy) { - this.onap = onap; - this.policy = policy; - } - - private enum ANNOTATION_TYPE { - MATCHING, VALIDATION, DICTIONARY - }; - - public enum MODEL_TYPE { - XMI - }; - - public enum SearchType { - TOSCA_DEFINITION_VERSION, TOSCA_SIMPLE_YAML_1_0_0, NODE_TYPE, DATA_TYPE, JSON_MODEL - } - - public Map processEpackage(String file, MODEL_TYPE model) { - if (model == MODEL_TYPE.XMI) { - processXMIEpackage(file); - } - return classMap; - - } - - private void processXMIEpackage(String xmiFile) { - EPackage root = getEpackage(xmiFile); - TreeIterator treeItr = root.eAllContents(); - String className; - String returnValue; - - // Pulling out dependency from file - while (treeItr.hasNext()) { - EObject obj = treeItr.next(); - if (obj instanceof EClassifier) { - EClassifier eClassifier = (EClassifier) obj; - className = eClassifier.getName(); - - if (obj instanceof EEnum) { - enumMap.putAll(getEEnum(obj)); - } else if (obj instanceof EClass) { - String temp = getDependencyList(eClassifier).toString(); - returnValue = StringUtils.replaceEach(temp, new String[] {"[", "]"}, new String[] {"", ""}); - getAttributes(className, returnValue, root); - } - } - } - - if (!enumMap.isEmpty()) { - addEnumClassMap(); - } - if (!matchingClass.isEmpty()) { - checkForMatchingClass(); - } - } - - private void checkForMatchingClass() { - HashMap tempAttribute = new HashMap<>(); - - for (Entry set : matchingClass.entrySet()) { - String key = set.getKey(); - if (classMap.containsKey(key)) { - Map listAttributes = classMap.get(key).getAttribute(); - Map listRef = classMap.get(key).getRefAttribute(); - for (Entry eSet : listAttributes.entrySet()) { - String key2 = eSet.getKey(); - tempAttribute.put(key2, MATCHINGTRUE); - } - for (Entry eSet : listRef.entrySet()) { - String key3 = eSet.getKey(); - tempAttribute.put(key3, MATCHINGTRUE); - } - - } - updateMatching(tempAttribute, key); - } - - } - - - - private void updateMatching(HashMap tempAttribute, String key) { - Map newClass = classMap; - - for (Entry updateClass : newClass.entrySet()) { - Map valueMap = updateClass.getValue().getMatchingSet(); - String keymap = updateClass.getKey(); - if (valueMap.containsKey(key)) { - Map modifyMap = classMap.get(keymap).getMatchingSet(); - modifyMap.remove(key); - modifyMap.putAll(tempAttribute); - classMap.get(keymap).setMatchingSet(modifyMap); - } - - } - } - - private void addEnumClassMap() { - for (Entry value : classMap.entrySet()) { - value.getValue().setEnumType(enumMap); - } - } - - private EPackage getEpackage(String xmiFile) { - ResourceSet resSet = new ResourceSetImpl(); - Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE; - Map m = reg.getExtensionToFactoryMap(); - m.put("xmi", new XMIResourceFactoryImpl()); - Resource resource = resSet.getResource(URI.createFileURI(xmiFile), true); - try { - resource.load(Collections.emptyMap()); - } catch (IOException e) { - logger.error("Error loading Encore Resource for new Model" + e); - } - - return (EPackage) resource.getContents().get(0); - } - - private HashMap getEEnum(EObject obj) { - List valueList = new ArrayList<>(); - HashMap returnMap = new HashMap<>(); - EEnum eenum = (EEnum) obj; - - String name = eenum.getName(); - for (EEnumLiteral eEnumLiteral : eenum.getELiterals()) { - Enumerator instance = eEnumLiteral.getInstance(); - String value = instance.getLiteral(); - valueList.add(value); - } - returnMap.put(name, valueList.toString()); - return returnMap; - } - - public void getAttributes(String className, String dependency, EPackage root) { - List dpendList = new ArrayList<>(); - if (dependency != null) { - dpendList = new ArrayList<>(Arrays.asList(dependency.split(","))); - } - MSAttributeObject msAttributeObject = new MSAttributeObject(); - msAttributeObject.setClassName(className); - String extendClass = getSubTypes(root, className); - Map returnRefList = getRefAttributeList(root, className, extendClass); - Map returnAttributeList = getAttributeList(root, className, extendClass); - Map returnSubList = getSubAttributeList(root, className, extendClass); - HashMap returnAnnotation = getAnnotation(root, className, extendClass); - msAttributeObject.setAttribute(returnAttributeList); - msAttributeObject.setRefAttribute(returnRefList); - msAttributeObject.setSubClass(returnSubList); - msAttributeObject.setDependency(dpendList.toString()); - msAttributeObject.addMatchingSet(returnAnnotation); - msAttributeObject.setPolicyTempalate(isPolicyTemplate(root, className)); - - this.classMap.put(className, msAttributeObject); - } - - private HashMap getAnnotation(EPackage root, String className, String extendClass) { - TreeIterator treeItr = root.eAllContents(); - boolean requiredAttribute = false; - boolean requiredMatchAttribute = false; - HashMap annotationSet = new HashMap<>(); - - // Pulling out dependency from file - while (treeItr.hasNext()) { - EObject obj = treeItr.next(); - if (obj instanceof EClassifier) { - requiredAttribute = isRequiredAttribute(obj, className); - requiredMatchAttribute = isRequiredAttribute(obj, extendClass); - } - - if (requiredAttribute) { - if (obj instanceof EStructuralFeature) { - checkAnnotation(annotationSet, (EStructuralFeature) obj); - } - } else if (requiredMatchAttribute && (obj instanceof EStructuralFeature)) { - findMatchingAnnotation(annotationSet, obj); - } - } - return annotationSet; - } - - private void findMatchingAnnotation(HashMap annotationSet, EObject obj) { - EStructuralFeature eStrucClassifier = (EStructuralFeature) obj; - if (eStrucClassifier.getEAnnotations().isEmpty()) { - return; - } - String matching = annotationValue(eStrucClassifier, ANNOTATION_TYPE.MATCHING, policy); - if (matching != null) { - if (obj instanceof EReference) { - EClass refType = ((EReference) obj).getEReferenceType(); - annotationSet.put(refType.getName(), matching); - matchingClass.put(refType.getName(), matching); - } else { - annotationSet.put(eStrucClassifier.getName(), matching); - } - } - - } - - private void checkAnnotation(HashMap annotationSet, EStructuralFeature obj) { - EStructuralFeature eStrucClassifier = obj; - if (eStrucClassifier.getEAnnotations().isEmpty()) { - return; - } - String matching = annotationValue(eStrucClassifier, ANNOTATION_TYPE.MATCHING, policy); - if (matching != null) { - annotationSet.put(eStrucClassifier.getName(), matching); - } - String range = annotationValue(eStrucClassifier, ANNOTATION_TYPE.VALIDATION, policy); - if (range != null) { - annotationSet.put(eStrucClassifier.getName(), range); - } - String annotationDict = annotationValue(eStrucClassifier, ANNOTATION_TYPE.DICTIONARY, policy); - if (annotationDict != null) { - annotationSet.put(eStrucClassifier.getName(), annotationDict); - } - } - - private Map getSubAttributeList(EPackage root, String className, String superClass) { - TreeIterator treeItr = root.eAllContents(); - boolean requiredAttribute = false; - Map subAttribute = new HashMap<>(); - int rollingCount = 0; - int processClass = 0; - - // Pulling out dependency from file - while (treeItr.hasNext() && rollingCount < 2) { - - EObject obj = treeItr.next(); - if (obj instanceof EClassifier) { - requiredAttribute = isRequiredAttribute(obj, className) || isRequiredAttribute(obj, superClass); - if (requiredAttribute) { - processClass++; - } - rollingCount = rollingCount + processClass; - } - - if (requiredAttribute && (obj instanceof EStructuralFeature)) { - EStructuralFeature eStrucClassifier = (EStructuralFeature) obj; - if (!eStrucClassifier.getEAnnotations().isEmpty()) { - updateSubAttributes(subAttribute, obj, eStrucClassifier); - } - } - } - return subAttribute; - } - - private void updateSubAttributes(Map subAttribute, EObject obj, - EStructuralFeature eStrucClassifier) { - if (!(obj instanceof EReference)) { - return; - } - if (annotationTest(eStrucClassifier, configuration, onap)) { - EClass refType = ((EReference) obj).getEReferenceType(); - if (!refType.toString().contains(eProxyURI)) { - String required = REQUIREDFALSE; - if (eStrucClassifier.getLowerBound() == 1) { - required = REQUIREDTRUE; - } - subAttribute.put(eStrucClassifier.getName(), refType.getName() + required); - } - } - } - - public String checkDefultValue(String defultValue) { - if (defultValue != null) { - return DEFAULTVALUE + defultValue; - } - return ":defaultValue-NA"; - - } - - public String checkRequiredPattern(int upper, int lower) { - String pattern = XACMLProperties.getProperty(XacmlRestProperties.PROP_XCORE_REQUIRED_PATTERN); - if (pattern != null && upper == Integer.parseInt(pattern.split(",")[1]) - && lower == Integer.parseInt(pattern.split(",")[0])) { - return REQUIREDTRUE; - } - return REQUIREDFALSE; - } - - public JSONObject buildJavaObject(Map map) { - return new JSONObject(map); - } - - public Map getRefAttributeList(EPackage root, String className, String superClass) { - - TreeIterator treeItr = root.eAllContents(); - boolean requiredAttribute = false; - HashMap refAttribute = new HashMap<>(); - int rollingCount = 0; - int processClass = 0; - boolean annotation; - // Pulling out dependency from file - while (treeItr.hasNext()) { - EObject obj = treeItr.next(); - if (obj instanceof EClassifier) { - requiredAttribute = isRequiredAttribute(obj, className) || isRequiredAttribute(obj, superClass); - if (requiredAttribute) { - processClass++; - } - rollingCount = rollingCount + processClass; - } - - if (requiredAttribute && (obj instanceof EStructuralFeature)) { - EStructuralFeature eStrucClassifier = (EStructuralFeature) obj; - if (!eStrucClassifier.getEAnnotations().isEmpty()) { - annotation = annotationTest(eStrucClassifier, configuration, onap); - if (annotation && obj instanceof EReference) { - updRefAttributes(refAttribute, (EStructuralFeature) obj, eStrucClassifier); - } else if (annotation && obj instanceof EAttributeImpl) { - updEnumTypeRefAttrib(refAttribute, (EStructuralFeature) obj, eStrucClassifier); - } - } - } - } - - return refAttribute; - } - - private void updEnumTypeRefAttrib(HashMap refAttribute, EStructuralFeature obj, - EStructuralFeature eStrucClassifier) { - EClassifier refType = ((EAttributeImpl) obj).getEType(); - if (!(refType instanceof EEnumImpl)) { - return; - } - - String array = arrayCheck(obj.getUpperBound()); - String required = REQUIREDFALSE; - if (obj.getLowerBound() == 1) { - required = REQUIREDTRUE; - } - refAttribute.put(eStrucClassifier.getName(), refType.getName() + array + required); - } - - private void updRefAttributes(HashMap refAttribute, EStructuralFeature obj, - EStructuralFeature eStrucClassifier) { - EClass refType = ((EReference) obj).getEReferenceType(); - if (refType.toString().contains(eProxyURI)) { - String one = refType.toString().split(eProxyURI)[1]; - String refValue = - StringUtils.replaceEach(one.split("#")[1], new String[] {"//", ")"}, new String[] {"", ""}); - refAttribute.put(eStrucClassifier.getName(), refValue); - } else { - String required = REQUIREDFALSE; - if (obj.getLowerBound() == 1) { - required = REQUIREDTRUE; - } - refAttribute.put(eStrucClassifier.getName(), - refType.getName() + arrayCheck(obj.getUpperBound()) + required); - } - } - - private boolean annotationTest(EStructuralFeature eStrucClassifier, String annotation, String type) { - String annotationType; - EAnnotation eAnnotation; - String onapType; - String onapValue; - - EList value = eStrucClassifier.getEAnnotations(); - - for (int i = 0; i < value.size(); i++) { - annotationType = value.get(i).getSource(); - eAnnotation = eStrucClassifier.getEAnnotations().get(i); - onapType = eAnnotation.getDetails().get(0).getValue(); - onapValue = eAnnotation.getDetails().get(0).getKey(); - - if (annotationType.contains(type) && onapType.contains(annotation)) { - return true; - } - - if (annotationType.contains(type) && onapValue.contains(annotation)) { - return true; - } - } - - return false; - } - - - private String annotationValue(EStructuralFeature eStrucClassifier, ANNOTATION_TYPE annotation, String type) { - String annotationType; - EAnnotation eAnnotation; - String onapType; - String onapValue = null; - - EList value = eStrucClassifier.getEAnnotations(); - - for (int i = 0; i < value.size(); i++) { - annotationType = value.get(i).getSource(); - eAnnotation = eStrucClassifier.getEAnnotations().get(i); - onapType = eAnnotation.getDetails().get(0).getKey(); - if (annotationType.contains(type) && onapType.compareToIgnoreCase(annotation.toString()) == 0) { - onapValue = eAnnotation.getDetails().get(0).getValue(); - if (annotation == ANNOTATION_TYPE.VALIDATION) { - return onapValue; - } else { - return onapType + "-" + onapValue; - } - } - } - - return onapValue; - } - - public boolean isRequiredAttribute(EObject obj, String className) { - EClassifier eClassifier = (EClassifier) obj; - String workingClass = eClassifier.getName().trim(); - if (workingClass.equalsIgnoreCase(className)) { - return true; - } - - return false; - } - - private boolean isPolicyTemplate(EPackage root, String className) { - boolean result = false; - for (EClassifier classifier : root.getEClassifiers()) { - if (classifier instanceof EClass) { - EClass eClass = (EClass) classifier; - if (eClass.getName().contentEquals(className)) { - result = checkPolicyTemplate(eClass); - break; - } - } - } - return result; - } - - private boolean checkPolicyTemplate(EClass eClass) { - EList value = eClass.getEAnnotations(); - for (EAnnotation workingValue : value) { - EMap keyMap = workingValue.getDetails(); - if (keyMap.containsKey("policyTemplate")) { - return true; - } - } - return false; - } - - private String getSubTypes(EPackage root, String className) { - String returnSubTypes = null; - for (EClassifier classifier : root.getEClassifiers()) { - if (classifier instanceof EClass) { - returnSubTypes = findSubTypes(className, returnSubTypes, (EClass) classifier); - } - } - return returnSubTypes; - } - - private String findSubTypes(String className, String returnSubTypes, EClass classifier) { - EClass eClass = classifier; - - for (EClass eSuperType : eClass.getEAllSuperTypes()) { - if (eClass.getName().contentEquals(className)) { - returnSubTypes = eSuperType.getName(); - } - } - return returnSubTypes; - } - - public Map getAttributeList(EPackage root, String className, String superClass) { - - TreeIterator treeItr = root.eAllContents(); - boolean requiredAttribute = false; - HashMap refAttribute = new HashMap<>(); - - // Pulling out dependency from file - while (treeItr.hasNext()) { - EObject obj = treeItr.next(); - if (obj instanceof EClassifier) { - requiredAttribute = isRequiredAttribute(obj, className) || isRequiredAttribute(obj, superClass); - } - - if (requiredAttribute && (obj instanceof EStructuralFeature)) { - EStructuralFeature eStrucClassifier = (EStructuralFeature) obj; - if (!eStrucClassifier.getEAnnotations().isEmpty()) { - checkStrucClassifier(refAttribute, obj, eStrucClassifier); - } - } - } - return refAttribute; - - } - - private void checkStrucClassifier(HashMap refAttribute, EObject obj, - EStructuralFeature eStrucClassifier) { - EClassifier refType = ((EStructuralFeature) obj).getEType(); - boolean annotation = annotationTest(eStrucClassifier, configuration, onap); - boolean dictionaryTest = annotationTest(eStrucClassifier, dictionary, policy); - if (annotation && !(obj instanceof EReference) && !(refType instanceof EEnumImpl)) { - updEReferenceAttrib(refAttribute, dictionaryTest, (EStructuralFeature) obj, eStrucClassifier); - } - } - - private void updEReferenceAttrib(HashMap refAttribute, boolean dictionaryTest, - EStructuralFeature obj, EStructuralFeature eStrucClassifier) { - String eType; - String name = eStrucClassifier.getName(); - if (dictionaryTest) { - eType = annotationValue(eStrucClassifier, ANNOTATION_TYPE.DICTIONARY, policy); - } else { - eType = eStrucClassifier.getEType().getInstanceClassName(); - } - String defaultValue = checkDefultValue(obj.getDefaultValueLiteral()); - String array = arrayCheck(obj.getUpperBound()); - String required = checkRequiredPattern(obj.getUpperBound(), obj.getLowerBound()); - refAttribute.put(name, eType + defaultValue + required + array); - } - - public String arrayCheck(int upperBound) { - - if (upperBound == -1) { - return MANYTRUE; - } - - return MANYFALSE; - } - - public List getDependencyList(EClassifier eClassifier) { - List returnValue = new ArrayList<>();; - EList somelist = ((EClass) eClassifier).getEAllSuperTypes(); - if (somelist.isEmpty()) { - return returnValue; - } - for (EClass depend : somelist) { - if (depend.toString().contains(eProxyURI)) { - String one = depend.toString().split(eProxyURI)[1]; - String value = - StringUtils.replaceEach(one.split("#")[1], new String[] {"//", ")"}, new String[] {"", ""}); - returnValue.add(value); - } - } - - return returnValue; - } - - public Map buildSubList(Map subClassAttributes, - Map classMap, String className) { - Map missingValues = new HashMap<>(); - Map workingMap; - boolean enumType; - - for (Entry map : classMap.get(className).getRefAttribute().entrySet()) { - String value = map.getValue().split(":")[0]; - if (value != null) { - classMap.get(className).getEnumType(); - enumType = classMap.get(className).getEnumType().containsKey(value); - if (!enumType) { - workingMap = classMap.get(value).getRefAttribute(); - for (Entry subMab : workingMap.entrySet()) { - String value2 = subMab.getValue().split(":")[0]; - if (!subClassAttributes.containsValue(value2)) { - missingValues.put(subMab.getKey(), subMab.getValue()); - } - } - - } - } - } - - return missingValues; - } - - public Map> recursiveReference(Map classMap, - String className) { - - Map> returnObject = new HashMap<>(); - Map returnClass = getRefclass(classMap, className); - returnObject.put(className, returnClass); - for (Entry reAttribute : returnClass.entrySet()) { - if (reAttribute.getValue().split(":")[1].contains("MANY") - && classMap.get(reAttribute.getValue().split(":")[0]) != null) { - returnObject.putAll(recursiveReference(classMap, reAttribute.getValue().split(":")[0])); - } - - } - - return returnObject; - - } - - public String createJson(Map classMap, String className) { - boolean enumType; - Map> myObject = new HashMap<>(); - for (Entry map : classMap.get(className).getRefAttribute().entrySet()) { - String value = map.getValue().split(":")[0]; - if (value != null) { - enumType = classMap.get(className).getEnumType().containsKey(value); - if (!enumType && map.getValue().split(":")[1].contains("MANY")) { - Map> testRecursive = - recursiveReference(classMap, map.getValue().split(":")[0]); - myObject.putAll(testRecursive); - } - } - } - - Gson gson = new Gson(); - return gson.toJson(myObject); - } - - public Map getRefclass(Map classMap, String className) { - HashMap missingValues = new HashMap<>(); - - if (classMap.get(className).getAttribute() != null || !classMap.get(className).getAttribute().isEmpty()) { - missingValues.putAll(classMap.get(className).getAttribute()); - } - - if (classMap.get(className).getRefAttribute() != null || !classMap.get(className).getRefAttribute().isEmpty()) { - missingValues.putAll(classMap.get(className).getRefAttribute()); - } - - return missingValues; - } - - public String createSubAttributes(List dependency, Map classMap, - String modelName) { - - HashMap workingMap = new HashMap<>(); - MSAttributeObject tempObject; - if (dependency != null) { - if (dependency.isEmpty()) { - return "{}"; - } - dependency.add(modelName); - for (String element : dependency) { - tempObject = classMap.get(element); - if (tempObject != null) { - workingMap.putAll(classMap.get(element).getSubClass()); - } - } - } - - return createJson(classMap, modelName); - } - - public List getFullDependencyList(List dependency, Map classMap) { - ArrayList returnList = new ArrayList<>(); - ArrayList workingList; - returnList.addAll(dependency); - for (String element : dependency) { - if (classMap.containsKey(element)) { - MSAttributeObject value = classMap.get(element); - String rawValue = - StringUtils.replaceEach(value.getDependency(), new String[] {"[", "]"}, new String[] {"", ""}); - workingList = new ArrayList<>(Arrays.asList(rawValue.split(","))); - for (String depend : workingList) { - updDependencyList(returnList, depend); - } - } - } - - return returnList; - } - - private void updDependencyList(ArrayList returnList, String depend) { - if (!returnList.contains(depend) && !depend.isEmpty()) { - returnList.add(depend.trim()); - } - } - - /* - * For TOSCA Model - */ - public String parseTosca(String fileName) { - Map map = new LinkedHashMap<>(); - try { - map = load(fileName); - if (map != null && map.get(ERROR) != null) { - return map.get(ERROR); - } - parseDataAndPolicyNodes(map); - LinkedHashMap dataMapForJson = parseDataNodes(map); - constructJsonForDataFields(dataMapForJson); - LinkedHashMap> mapKey = parsePolicyNodes(map); - createAttributes(mapKey); - - } catch (IOException e) { - logger.error(e); - } catch (ParserException e) { - logger.error(e); - return e.getMessage(); - } - - return null; - } - - @SuppressWarnings("unchecked") - public Map load(String fileName) throws IOException, ParserException { - File newConfiguration = new File(fileName); - StringBuilder orderInfo = new StringBuilder("["); - Yaml yaml = new Yaml(); - LinkedHashMap yamlMap = null; - try (InputStream is = new FileInputStream(newConfiguration)) { - yamlMap = (LinkedHashMap) yaml.load(is); - } catch (FileNotFoundException e) { - logger.error(e); - } catch (Exception e) { - logger.error(e); - throw new ParserException("Invalid TOSCA Model format. Please make sure it is a valid YAML file"); - } - - StringBuilder sb = new StringBuilder(); - LinkedHashMap settings = new LinkedHashMap<>(); - if (yamlMap == null) { - return settings; - } - - String message = validations(yamlMap); - - if (message != null) { - settings.put(ERROR, message); - return settings; - } - - findNode(yamlMap); - - if (!isDuplicatedAttributes && orderedElements != null && !orderedElements.isEmpty()) { - orderedElements.stream().forEach(string -> { - orderInfo.append(string); - orderInfo.append(","); - logger.info("Content: " + string); - }); - - orderInfo.append("]"); - - dataOrderInfo = orderInfo.toString(); - dataOrderInfo = dataOrderInfo.replace(",]", "]"); - - logger.info("dataOrderInfo :" + dataOrderInfo); - } - - List path = new ArrayList<>(); - serializeMap(settings, sb, path, yamlMap); - return settings; - } - - @SuppressWarnings("unchecked") - private String validations(@SuppressWarnings("rawtypes") Map yamlMap) { - - boolean isNoteTypeFound = false; - boolean isDataTypeFound = false; - boolean isToscaVersionKeyFound = false; - boolean isToscaVersionValueFound = false; - @SuppressWarnings("rawtypes") - Map m1 = new HashMap(); - short order = 0; - if (yamlMap != null) { - // Get a set of the entries - @SuppressWarnings("rawtypes") - Set entries = yamlMap.entrySet(); - for (@SuppressWarnings("rawtypes") - Map.Entry me : entries) { - if (TOSCA_SIMPLE_YAML_1_0_0.equals(me.getValue())) { - isToscaVersionValueFound = true; - } - - switch (me.getKey().toString()) { - case TOSCA_DEFINITION_VERSION: - isToscaVersionKeyFound = true; - order++; - m1.put(TOSCA_DEFINITION_VERSION, order); - break; - case NODE_TYPE: - isNoteTypeFound = true; - order++; - m1.put(NODE_TYPE, order); - break; - case DATA_TYPE: - isDataTypeFound = true; - order++; - m1.put(DATA_TYPE, order); - break; - case JSON_MODEL: - setJsonRuleFormation(me.getValue().toString()); - break; - default: - break; - } - } - if (!isDataTypeFound) { - return "data_types are missing or invalid."; - } - if (!isToscaVersionKeyFound || !isToscaVersionValueFound) { - return "tosca_definitions_version is missing or invalid."; - } - - if (!isNoteTypeFound) { - return "node_types are missing or invalid."; - } - - short version = (short) m1.get(TOSCA_DEFINITION_VERSION); - - if (version > 1) { - return "tosca_definitions_version should be defined first."; - } - - short data = (short) m1.get(DATA_TYPE); - short node = (short) m1.get(NODE_TYPE); - if (isDataTypeFound && node > data) { - return "node_types should be defined before data_types."; - } - - } - - return null; - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - private void serializeMap(LinkedHashMap settings, StringBuilder sb, List path, - Map yamlMap) { - for (Map.Entry entry : yamlMap.entrySet()) { - - if (entry.getValue() instanceof Map) { - path.add((String) entry.getKey()); - serializeMap(settings, sb, path, (Map) entry.getValue()); - path.remove(path.size() - 1); - } else if (entry.getValue() instanceof List) { - path.add((String) entry.getKey()); - serializeList(settings, sb, path, (List) entry.getValue()); - path.remove(path.size() - 1); - } else { - serializeValue(settings, sb, path, (String) entry.getKey(), entry.getValue()); - } - } - } - - @SuppressWarnings("unchecked") - private void serializeList(LinkedHashMap settings, StringBuilder sb, List path, - List yamlList) { - int counter = 0; - for (Object listEle : yamlList) { - if (listEle instanceof Map) { - path.add(Integer.toString(counter)); - serializeMap(settings, sb, path, (Map) listEle); - path.remove(path.size() - 1); - } else if (listEle instanceof List) { - path.add(Integer.toString(counter)); - serializeList(settings, sb, path, (List) listEle); - path.remove(path.size() - 1); - } else { - serializeValue(settings, sb, path, Integer.toString(counter), listEle); - } - counter++; - } - } - - private void serializeValue(LinkedHashMap settings, StringBuilder sb, List path, - String name, Object value) { - if (value == null) { - return; - } - sb.setLength(0); - for (String pathEle : path) { - sb.append(pathEle).append('.'); - } - sb.append(name); - settings.put(sb.toString(), value.toString()); - } - - - void parseDataAndPolicyNodes(Map map) { - for (String key : map.keySet()) { - if (key.contains("policy.nodes.Root")) { - continue; - } else if (key.contains("policy.nodes")) { - String wordToFind = "policy.nodes."; - int indexForPolicyNode = key.indexOf(wordToFind); - String subNodeString = key.substring(indexForPolicyNode + 13, key.length()); - - stringBetweenDots(subNodeString); - } else if (key.contains("policy.data")) { - String wordToFind = "policy.data."; - int indexForPolicyNode = key.indexOf(wordToFind); - String subNodeString = key.substring(indexForPolicyNode + 12, key.length()); - - stringBetweenDotsForDataFields(subNodeString); - } - } - } - - // Second index of dot should be returned. - public int stringBetweenDots(String str) { - String stringToSearch = str; - String[] ss = stringToSearch.split("\\."); - if (ss != null) { - int len = ss.length; - if (len > 2) { - uniqueKeys.add(ss[2]); - } - } - - return uniqueKeys.size(); - } - - - public void stringBetweenDotsForDataFields(String str) { - String stringToSearch = str; - String[] ss = stringToSearch.split("\\."); - if (ss != null) { - int len = ss.length; - - if (len > 2) { - uniqueDataKeys.add(ss[0] + "%" + ss[2]); - } - } - } - - void constructJsonForDataFields(LinkedHashMap dataMapForJson) { - LinkedHashMap> dataMapKey = new LinkedHashMap<>(); - LinkedHashMap hmSub; - for (Map.Entry entry : dataMapForJson.entrySet()) { - String uniqueDataKey = entry.getKey(); - String[] uniqueDataKeySplit = uniqueDataKey.split("%"); - String value = dataMapForJson.get(uniqueDataKey); - if (dataMapKey.containsKey(uniqueDataKeySplit[0])) { - hmSub = dataMapKey.get(uniqueDataKeySplit[0]); - hmSub.put(uniqueDataKeySplit[1], value); - } else { - hmSub = new LinkedHashMap<>(); - hmSub.put(uniqueDataKeySplit[1], value); - } - - dataMapKey.put(uniqueDataKeySplit[0], hmSub); - } - - JSONObject mainObject = new JSONObject(); - JSONObject json; - for (Map.Entry> entry : dataMapKey.entrySet()) { - String s = entry.getKey(); - json = new JSONObject(); - HashMap jsonHm = dataMapKey.get(s); - for (Map.Entry entryMap : jsonHm.entrySet()) { - String key = entryMap.getKey(); - json.put(key, jsonHm.get(key)); - } - mainObject.put(s, json); - } - Iterator keysItr = mainObject.keys(); - while (keysItr.hasNext()) { - String key = keysItr.next(); - String value = mainObject.get(key).toString(); - retmap.put(key, value); - } - - logger.info("#############################################################################"); - logger.info(mainObject); - logger.info("###############################################################################"); - } - - LinkedHashMap parseDataNodes(Map map) { - LinkedHashMap dataMapForJson = new LinkedHashMap<>(); - matchableValues = new HashMap<>(); - for (String uniqueDataKey : uniqueDataKeys) { - if (uniqueDataKey.contains("%")) { - String[] uniqueDataKeySplit = uniqueDataKey.split("%"); - String findType = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] + TYPE; - String typeValue = map.get(findType); - logger.info(typeValue); - - String findRequired = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] + REQUIRED; - String requiredValue = map.get(findRequired); - - String matchable = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] + MATCHABLE; - - String matchableValue = map.get(matchable); - - if ("true".equalsIgnoreCase(matchableValue)) { - String key = uniqueDataKeySplit[uniqueDataKeySplit.length - 1]; - matchableValues.put(key, MATCHINGTRUE); - } - - if (requiredValue == null || requiredValue.isEmpty()) { - requiredValue = "false"; - } - if (INTEGER.equalsIgnoreCase(typeValue) || STRING.equalsIgnoreCase(typeValue) - || typeValue.equalsIgnoreCase(BOOLEAN)) { - String findDefault = - DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] + DEFAULT; - String findDescription = - DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] + DESCRIPTION; - String defaultValue = map.get(findDefault); - String descriptionDefined = map.get(findDescription); - logger.info("defaultValue is:" + defaultValue); - logger.info("requiredValue is:" + requiredValue); - - StringBuilder attributeIndividualStringBuilder = new StringBuilder(); - attributeIndividualStringBuilder.append(typeValue + DEFAULTVALUE); - attributeIndividualStringBuilder.append(defaultValue + REQUIREDVALUE); - attributeIndividualStringBuilder.append(requiredValue + MANYFALSE); - attributeIndividualStringBuilder.append(DESCRIPTION_TOKEN + descriptionDefined); - dataMapForJson.put(uniqueDataKey, attributeIndividualStringBuilder.toString()); - } else if (LIST.equalsIgnoreCase(typeValue) || MAP.equalsIgnoreCase(typeValue)) { - logger.info("requiredValue is:" + requiredValue); - String findList = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] - + ".entry_schema.type"; - String findDefaultValue = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] - + ".entry_schema.default"; - String findDescription = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] - + ".entry_schema.description"; - String listValue = map.get(findList); - String defaultValue = map.get(findDefaultValue); - String description = map.get(findDescription); - if (listValue != null) { - logger.info("Type of list is:" + listValue); - // Its userdefined - if (listValue.contains(".")) { - String trimValue = listValue.substring(listValue.lastIndexOf('.') + 1); - StringBuilder referenceIndividualStringBuilder = new StringBuilder(); - referenceIndividualStringBuilder.append(trimValue + REQUIREDVALUE); - referenceIndividualStringBuilder.append(requiredValue + MANYTRUE); - referenceIndividualStringBuilder.append(DESCRIPTION_TOKEN + description); - dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString()); - } else { // Its string - StringBuilder stringListItems = new StringBuilder(); - if (LIST.equalsIgnoreCase(typeValue)) { - stringListItems.append(uniqueDataKeySplit[1].toUpperCase() + DEFAULTVALUE + defaultValue - + REQUIREDVALUE + requiredValue + MANYFALSE + DESCRIPTION_TOKEN + description); - } else if (MAP.equalsIgnoreCase(typeValue)) { - stringListItems.append(uniqueDataKeySplit[1].toUpperCase() + DEFAULTVALUE + defaultValue - + REQUIREDVALUE + requiredValue + MANYTRUE + DESCRIPTION_TOKEN + description); - } - dataMapForJson.put(uniqueDataKey, stringListItems.toString()); - dataListBuffer.append(uniqueDataKeySplit[1].toUpperCase() + "=["); - for (int i = 0; i < 10; i++) { - String findConstraints = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES - + uniqueDataKeySplit[1] + ".entry_schema.constraints.0.valid_values." + i; - String constraintsValue = map.get(findConstraints); - logger.info(constraintsValue); - boolean ruleCheck = false; - if (constraintsValue == null) { - break; - } else if (constraintsValue.startsWith(DICTIONARY)) { - List dictFromDB = null; - String[] dictionaryNameValRule; - String[] dictionaryName = constraintsValue.split(":"); - String dictionaryNameVal = dictionaryName[1]; - if (dictionaryNameVal.contains("#Rules")) { - ruleCheck = true; - dictionaryNameValRule = dictionaryNameVal.split("#"); - dictFromDB = commonClassDao.getDataById(DictionaryData.class, DICTIONARYNAME, - dictionaryNameValRule[0]); - } else { - dictFromDB = commonClassDao.getDataById(DictionaryData.class, DICTIONARYNAME, - dictionaryName[1]); - } - if (dictFromDB != null && !dictFromDB.isEmpty()) { - DictionaryData data = (DictionaryData) dictFromDB.get(0); - if (ruleCheck) { - constraintsValue = DICTIONARY + data.getDictionaryUrl() + "@" - + data.getDictionaryDataByName() + "&Rule"; - } else { - constraintsValue = DICTIONARY + data.getDictionaryUrl() + "@" - + data.getDictionaryDataByName(); - } - } - dataListBuffer.append(constraintsValue + ","); - } else { - logger.info("constraintsValue => " + constraintsValue); - if (constraintsValue.contains("=")) { - constraintsValue = constraintsValue.replace("=", "equal-sign"); - } - dataConstraints.add(constraintsValue); - dataListBuffer.append(constraintsValue + ","); - } - } - dataListBuffer.append("]#"); - logger.info(dataListBuffer); - } - } - } else { - String findUserDefined = DATATYPE + uniqueDataKeySplit[0] + "." + PROPERTIES_KEY + "." - + uniqueDataKeySplit[1] + TYPE; - String findDescription = DATATYPE + uniqueDataKeySplit[0] + "." + PROPERTIES_KEY + "." - + uniqueDataKeySplit[1] + DESCRIPTION; - String userDefinedValue = map.get(findUserDefined); - String description = map.get(findDescription); - String trimValue = userDefinedValue.substring(userDefinedValue.lastIndexOf('.') + 1); - StringBuilder referenceIndividualStringBuilder = new StringBuilder(); - referenceIndividualStringBuilder.append(trimValue + REQUIREDVALUE); - referenceIndividualStringBuilder.append(requiredValue + MANYFALSE); - referenceIndividualStringBuilder.append(DESCRIPTION_TOKEN + description); - dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString()); - - } - } else { - matchableValues.put(uniqueDataKey, MATCHINGTRUE); - } - } - - return dataMapForJson; - } - - LinkedHashMap> parsePolicyNodes(Map map) - throws ParserException { - LinkedHashMap> mapKey = new LinkedHashMap<>(); - for (String uniqueKey : uniqueKeys) { - LinkedHashMap hm; - - for (Entry entry : map.entrySet()) { - String key = entry.getKey(); - if (key.contains(uniqueKey) && key.contains("policy.nodes")) { - if (mapKey.containsKey(uniqueKey)) { - hm = mapKey.get(uniqueKey); - String keyStr = key.substring(key.lastIndexOf('.') + 1); - String valueStr = map.get(key); - if ("type".equalsIgnoreCase(keyStr) && key.contains("entry_schema.0.type") - || key.contains("entry_schema.type") && valueStr.contains("policy.data.")) { - throw new ParserException( - "For user defined object type, Please make sure no space between 'type:' and object " - + valueStr); - - } - if ("type".equals(keyStr)) { - if (!key.contains("entry_schema")) { - hm.put(keyStr, valueStr); - } - } else { - hm.put(keyStr, valueStr); - } - - } else { - hm = new LinkedHashMap<>(); - String keyStr = key.substring(key.lastIndexOf('.') + 1); - String valueStr = map.get(key); - - if (("type").equals(keyStr)) { - if (!key.contains("entry_schema")) { - hm.put(keyStr, valueStr); - } - } else { - hm.put(keyStr, valueStr); - } - mapKey.put(uniqueKey, hm); - } - } - } - } - return mapKey; - } - - private void createAttributes(LinkedHashMap> mapKey) { - StringBuilder attributeStringBuilder = new StringBuilder(); - StringBuilder referenceStringBuilder = new StringBuilder(); - StringBuilder listBuffer = new StringBuilder(); - List constraints = new ArrayList<>(); - for (Map.Entry> entry : mapKey.entrySet()) { - String keySetString = entry.getKey(); - LinkedHashMap keyValues = mapKey.get(keySetString); - if (keyValues.get("type") != null && (STRING.equalsIgnoreCase(keyValues.get("type")) - || INTEGER.equalsIgnoreCase(keyValues.get("type")) - || BOOLEAN.equalsIgnoreCase(keyValues.get("type")))) { - StringBuilder attributeIndividualStringBuilder = new StringBuilder(); - attributeIndividualStringBuilder.append(keySetString + "="); - attributeIndividualStringBuilder.append(keyValues.get("type") + DEFAULTVALUE); - attributeIndividualStringBuilder.append(keyValues.get("default") + REQUIREDVALUE); - attributeIndividualStringBuilder.append(keyValues.get("required") + MANYFALSE); - attributeIndividualStringBuilder.append(DESCRIPTION_TOKEN + keyValues.get(DESCRIPTION_KEY)); - attributeStringBuilder.append(attributeIndividualStringBuilder + ","); - if (keyValues.get(MATCHABLEKEY) != null && "true".equalsIgnoreCase(keyValues.get(MATCHABLEKEY))) { - matchableValues.put(keySetString, MATCHINGTRUE); - } - } else if (LIST.equalsIgnoreCase(keyValues.get("type"))) { - if ("true".equalsIgnoreCase(keyValues.get(MATCHABLEKEY))) { - matchableValues.put(keySetString, MATCHINGTRUE); - } - // List Data type - Set keys = keyValues.keySet(); - Iterator itr = keys.iterator(); - boolean isDefinedType = false; - while (itr.hasNext()) { - String key = itr.next(); - if ((!("type").equals(key) || ("required").equals(key))) { - String value = keyValues.get(key); - // The "." in the value determines if its a string or a user defined type. - if (!value.contains(".")) { - // This is string - if (StringUtils.isNumeric(key)) { // only integer key for the value of Constrains - constraints.add(keyValues.get(key)); - } - } else { - // This is user defined type - String trimValue = value.substring(value.lastIndexOf('.') + 1); - StringBuilder referenceIndividualStringBuilder = new StringBuilder(); - referenceIndividualStringBuilder.append(keySetString + "=" + trimValue + MANYTRUE - + DESCRIPTION_TOKEN + keyValues.get(DESCRIPTION_KEY)); - referenceStringBuilder.append(referenceIndividualStringBuilder + ","); - isDefinedType = true; - } - } - - } - - if (!isDefinedType && LIST.equalsIgnoreCase(keyValues.get("type")) - && (constraints == null || constraints.isEmpty())) { - referenceStringBuilder.append(keySetString + "=MANY-true" + ","); - } - } else { - // User defined Datatype. - if ("true".equalsIgnoreCase(keyValues.get(MATCHABLEKEY))) { - matchableValues.put(keySetString, MATCHINGTRUE); - } - String value = keyValues.get("type"); - if (value != null && !value.isEmpty()) { - String trimValue = value.substring(value.lastIndexOf('.') + 1); - StringBuilder referenceIndividualStringBuilder = new StringBuilder(); - referenceIndividualStringBuilder.append(keySetString + "=" + trimValue + MANYFALSE - + DESCRIPTION_TOKEN + keyValues.get(DESCRIPTION_KEY)); - referenceStringBuilder.append(referenceIndividualStringBuilder + ","); - } else { - logger.info("keyValues.get(type) is null/empty"); - } - - } - if (constraints != null && !constraints.isEmpty()) { - // List handling. - listBuffer.append(keySetString.toUpperCase() + "=["); - for (String str : constraints) { - if (str.contains(DICTIONARY)) { - String[] dictionaryName = str.split(":"); - List dictFromDB = - commonClassDao.getDataById(DictionaryData.class, DICTIONARYNAME, dictionaryName[1]); - if (dictFromDB != null && !dictFromDB.isEmpty()) { - DictionaryData data = (DictionaryData) dictFromDB.get(0); - str = DICTIONARY + data.getDictionaryUrl() + "@" + data.getDictionaryDataByName(); - } - } - listBuffer.append(str + ","); - } - listBuffer.append("]#"); - logger.info(listBuffer); - - - StringBuilder referenceIndividualStringBuilder = new StringBuilder(); - referenceIndividualStringBuilder.append(keySetString + "=" + keySetString.toUpperCase() + MANYFALSE); - referenceStringBuilder.append(referenceIndividualStringBuilder + ","); - constraints.clear(); - } - } - - dataListBuffer.append(listBuffer); - - - logger.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); - logger.info("Whole attribute String is:" + attributeStringBuilder); - logger.info("Whole reference String is:" + referenceStringBuilder); - logger.info("List String is:" + listBuffer); - logger.info("Data list buffer is:" + dataListBuffer); - logger.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); - - this.listConstraints = dataListBuffer.toString(); - this.referenceAttributes = referenceStringBuilder.toString(); - this.attributeString = attributeStringBuilder.toString(); - } - - @SuppressWarnings("unchecked") - private void findNode(LinkedHashMap map) { - - map.forEach((key, value) -> { - // if the value is properties and its type is map object, then save all the keys - if (key.equals(PROPERTIES_KEY) && value instanceof Map) { - saveNodes((LinkedHashMap) value); - if (isDuplicatedAttributes) { - orderedElements = new ArrayList<>(); - return; - } - } - - if (!"policy.nodes.Root".equals(key) && value instanceof Map) { - // value is a Map object, then make a recursive call - findNode((LinkedHashMap) value); - } - }); - - } - - private void saveNodes(LinkedHashMap map) { - - for (Entry entry : map.entrySet()) { - - if (orderedElements.indexOf(entry.getKey()) >= 0) { // duplicated attribute names - isDuplicatedAttributes = true; - return; - } else { - orderedElements.add((String) entry.getKey()); - } - } - } - - public String getAttributeString() { - return attributeString; - } - - public void setAttributeString(String attributeString) { - this.attributeString = attributeString; - } - - public LinkedHashMap getRetmap() { - return retmap; - } - - public void setRetmap(LinkedHashMap retmap) { - this.retmap = retmap; - } - - public Map getMatchableValues() { - return matchableValues; - } - - public void setMatchableValues(Map matchableValues) { - this.matchableValues = matchableValues; - } - - public String getReferenceAttributes() { - return referenceAttributes; - } - - public void setReferenceAttributes(String referenceAttributes) { - this.referenceAttributes = referenceAttributes; - } - - public String getListConstraints() { - return listConstraints; - } - - public void setListConstraints(String listConstraints) { - this.listConstraints = listConstraints; - } - - public String getDataOrderInfo() { - return dataOrderInfo; - } - - public void setDataOrderInfo(String dataOrderInfo) { - this.dataOrderInfo = dataOrderInfo; - } - - public String getJsonRuleFormation() { - return jsonRuleFormation; - } - - public void setJsonRuleFormation(String jsonRuleFormation) { - this.jsonRuleFormation = jsonRuleFormation; - } - -} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/MsAttributeObject.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/MsAttributeObject.java new file mode 100644 index 000000000..a022f58fa --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/MsAttributeObject.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * Copyright (C) 2017,2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.rest.util; + +import java.util.HashMap; +import java.util.Map; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class MsAttributeObject { + + private String className; + private Map attribute = new HashMap<>(); + private Map refAttribute = new HashMap<>(); + private Map subClass = new HashMap<>(); + private String dependency; + private Map enumType = new HashMap<>(); + private Map matchingSet = new HashMap<>(); + private boolean policyTempalate; + private String ruleFormation; + private String dataOrderInfo; + + public void addAttribute(String key, String value) { + this.attribute.put(key, value); + } + + public void addRefAttribute(String key, String value) { + this.refAttribute.put(key, value); + } + + public void addAllAttribute(Map map) { + this.attribute.putAll(map); + } + + public void addAllRefAttribute(Map map) { + this.refAttribute.putAll(map); + } + + public void addAllSubClass(Map subClass) { + this.subClass.putAll(subClass); + } + + public void addSingleEnum(String key, String value) { + this.enumType.put(key, value); + } + + public void addMatchingSet(String key, String value) { + this.matchingSet.put(key, value); + } + + public void addMatchingSet(Map matchingSet) { + this.matchingSet.putAll(matchingSet); + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/MsAttributeValue.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/MsAttributeValue.java new file mode 100644 index 000000000..0d550e45a --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/MsAttributeValue.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.rest.util; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class MsAttributeValue { + private String name; + private String type; + private Boolean required; + private Boolean arrayValue; + private String defaultValue; +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/MsModelUtils.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/MsModelUtils.java new file mode 100644 index 000000000..5b596be45 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/MsModelUtils.java @@ -0,0 +1,1804 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.rest.util; + +import com.att.research.xacml.util.XACMLProperties; +import com.google.gson.Gson; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import lombok.Getter; +import lombok.Setter; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.eclipse.emf.common.util.EList; +import org.eclipse.emf.common.util.EMap; +import org.eclipse.emf.common.util.Enumerator; +import org.eclipse.emf.common.util.TreeIterator; +import org.eclipse.emf.common.util.URI; +import org.eclipse.emf.ecore.EAnnotation; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EClassifier; +import org.eclipse.emf.ecore.EEnum; +import org.eclipse.emf.ecore.EEnumLiteral; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EPackage; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.emf.ecore.impl.EAttributeImpl; +import org.eclipse.emf.ecore.impl.EEnumImpl; +import org.eclipse.emf.ecore.resource.Resource; +import org.eclipse.emf.ecore.resource.ResourceSet; +import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; +import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl; +import org.json.JSONObject; +import org.onap.policy.rest.XacmlRestProperties; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.DictionaryData; +import org.yaml.snakeyaml.Yaml; + +@Getter +@Setter +public class MsModelUtils { + + private static final Log logger = LogFactory.getLog(MsModelUtils.class); + + // String constants + private static final String BOOLEAN = "boolean"; + private static final String CONFIGURATION = "configuration"; + private static final String DATATYPE = "data_types.policy.data."; + private static final String DATA_TYPE = "data_types"; + private static final String DEFAULT = ".default"; + private static final String DEFAULTVALUE = ":defaultValue-"; + private static final String DESCRIPTION = ".description"; + private static final String DESCRIPTION_KEY = "description"; + private static final String DESCRIPTION_TOKEN = ":description-"; + private static final String DICTIONARY = "dictionary:"; + private static final String DICTIONARYNAME = "dictionaryName"; + private static final String ERROR = "error"; + private static final String E_PROXY_URI = "eProxyURI:"; + private static final String INTEGER = "integer"; + private static final String JSON_MODEL = "JSON_MODEL"; + private static final String LIST = "list"; + private static final String MANYFALSE = ":MANY-false"; + private static final String MANYTRUE = ":MANY-true"; + private static final String MAP = "map"; + private static final String MATCHABLE = ".matchable"; + private static final String MATCHABLEKEY = "matchable"; + private static final String MATCHINGTRUE = "matching-true"; + private static final String NODE_TYPE = "node_types"; + private static final String PROPERTIES = ".properties."; + private static final String PROPERTIES_KEY = "properties"; + private static final String REQUIRED = ".required"; + private static final String REQUIREDFALSE = ":required-false"; + private static final String REQUIREDTRUE = ":required-true"; + private static final String REQUIREDVALUE = ":required-"; + private static final String STRING = "string"; + private static final String TOSCA_DEFINITION_VERSION = "tosca_definitions_version"; + private static final String TOSCA_SIMPLE_YAML_1_0_0 = "tosca_simple_yaml_1_0_0"; + private static final String TYPE = ".type"; + + private static CommonClassDao commonClassDao; + + private HashMap classMap = new HashMap<>(); + private HashMap enumMap = new HashMap<>(); + private HashMap matchingClass = new HashMap<>(); + private String onap = ""; + private String policy = ""; + private List orderedElements = new ArrayList<>(); + private String dataOrderInfo = ""; + private Set uniqueDataKeys = new HashSet<>(); + private Set uniqueKeys = new HashSet<>(); + private String listConstraints = null; + private String referenceAttributes; + private LinkedHashMap retmap = new LinkedHashMap<>(); + private Map matchableValues; + private StringBuilder dataListBuffer = new StringBuilder(); + private List dataConstraints = new ArrayList<>(); + private String attributeString = null; + private boolean isDuplicatedAttributes = false; + private String jsonRuleFormation = null; + + /** + * The Enum AnnotationType. + */ + private enum AnnotationType { + MATCHING, + VALIDATION, + DICTIONARY + } + + /** + * The Enum ModelType. + */ + public enum ModelType { + XMI + } + + /** + * The Enum SearchType. + */ + public enum SearchType { + TOSCA_DEFINITION_VERSION, + TOSCA_SIMPLE_YAML_1_0_0, + NODE_TYPE, + DATA_TYPE, + JSON_MODEL + } + + /** + * Instantiates a new ms model utils. + */ + public MsModelUtils() { + // Default Constructor + } + + /** + * Instantiates a new ms model utils. + * + * @param commonClassDao the common class dao + */ + public MsModelUtils(CommonClassDao commonClassDao) { + MsModelUtils.commonClassDao = commonClassDao; + } + + /** + * Instantiates a new ms model utils. + * + * @param onap the onap + * @param policy the policy + */ + public MsModelUtils(String onap, String policy) { + this.onap = onap; + this.policy = policy; + } + + /** + * Process epackage. + * + * @param file the file + * @param model the model + * @return the map + */ + public Map processEpackage(String file, ModelType model) { + if (model == ModelType.XMI) { + processXmiEpackage(file); + } + return classMap; + + } + + /** + * Process XMI epackage. + * + * @param xmiFile the xmi file + */ + private void processXmiEpackage(String xmiFile) { + EPackage root = getEpackage(xmiFile); + TreeIterator treeItr = root.eAllContents(); + String className; + String returnValue; + + // Pulling out dependency from file + while (treeItr.hasNext()) { + EObject obj = treeItr.next(); + if (obj instanceof EClassifier) { + EClassifier eclassifier = (EClassifier) obj; + className = eclassifier.getName(); + + if (obj instanceof EEnum) { + enumMap.putAll(getEEnum(obj)); + } else if (obj instanceof EClass) { + String temp = getDependencyList(eclassifier).toString(); + returnValue = StringUtils.replaceEach(temp, new String[] + { "[", "]" }, new String[] + { "", "" }); + getAttributes(className, returnValue, root); + } + } + } + + if (!enumMap.isEmpty()) { + addEnumClassMap(); + } + if (!matchingClass.isEmpty()) { + checkForMatchingClass(); + } + } + + /** + * Check for matching class. + */ + private void checkForMatchingClass() { + HashMap tempAttribute = new HashMap<>(); + + for (Entry set : matchingClass.entrySet()) { + String key = set.getKey(); + if (classMap.containsKey(key)) { + Map listAttributes = classMap.get(key).getAttribute(); + Map listRef = classMap.get(key).getRefAttribute(); + for (Entry eset : listAttributes.entrySet()) { + String key2 = eset.getKey(); + tempAttribute.put(key2, MATCHINGTRUE); + } + for (Entry eset : listRef.entrySet()) { + String key3 = eset.getKey(); + tempAttribute.put(key3, MATCHINGTRUE); + } + + } + updateMatching(tempAttribute, key); + } + + } + + /** + * Update matching. + * + * @param tempAttribute the temp attribute + * @param key the key + */ + private void updateMatching(HashMap tempAttribute, String key) { + Map newClass = classMap; + + for (Entry updateClass : newClass.entrySet()) { + Map valueMap = updateClass.getValue().getMatchingSet(); + String keymap = updateClass.getKey(); + if (valueMap.containsKey(key)) { + Map modifyMap = classMap.get(keymap).getMatchingSet(); + modifyMap.remove(key); + modifyMap.putAll(tempAttribute); + classMap.get(keymap).setMatchingSet(modifyMap); + } + + } + } + + /** + * Adds the enum class map. + */ + private void addEnumClassMap() { + for (Entry value : classMap.entrySet()) { + value.getValue().setEnumType(enumMap); + } + } + + /** + * Gets the epackage. + * + * @param xmiFile the xmi file + * @return the epackage + */ + private EPackage getEpackage(String xmiFile) { + ResourceSet resSet = new ResourceSetImpl(); + Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE; + Map objectMap = reg.getExtensionToFactoryMap(); + objectMap.put("xmi", new XMIResourceFactoryImpl()); + Resource resource = resSet.getResource(URI.createFileURI(xmiFile), true); + try { + resource.load(Collections.emptyMap()); + } catch (IOException e) { + logger.error("Error loading Encore Resource for new Model" + e); + } + + return (EPackage) resource.getContents().get(0); + } + + /** + * Gets the e enum. + * + * @param obj the obj + * @return the e enum + */ + private HashMap getEEnum(EObject obj) { + List valueList = new ArrayList<>(); + HashMap returnMap = new HashMap<>(); + EEnum eenum = (EEnum) obj; + + String name = eenum.getName(); + for (EEnumLiteral enumLiteral : eenum.getELiterals()) { + Enumerator instance = enumLiteral.getInstance(); + String value = instance.getLiteral(); + valueList.add(value); + } + returnMap.put(name, valueList.toString()); + return returnMap; + } + + /** + * Gets the attributes. + * + * @param className the class name + * @param dependency the dependency + * @param root the root + */ + public void getAttributes(String className, String dependency, EPackage root) { + List dpendList = new ArrayList<>(); + if (dependency != null) { + dpendList = new ArrayList<>(Arrays.asList(dependency.split(","))); + } + MsAttributeObject msAttributeObject = new MsAttributeObject(); + msAttributeObject.setClassName(className); + String extendClass = getSubTypes(root, className); + Map returnRefList = getRefAttributeList(root, className, extendClass); + Map returnAttributeList = getAttributeList(root, className, extendClass); + Map returnSubList = getSubAttributeList(root, className, extendClass); + HashMap returnAnnotation = getAnnotation(root, className, extendClass); + msAttributeObject.setAttribute(returnAttributeList); + msAttributeObject.setRefAttribute(returnRefList); + msAttributeObject.setSubClass(returnSubList); + msAttributeObject.setDependency(dpendList.toString()); + msAttributeObject.addMatchingSet(returnAnnotation); + msAttributeObject.setPolicyTempalate(isPolicyTemplate(root, className)); + + this.classMap.put(className, msAttributeObject); + } + + /** + * Gets the annotation. + * + * @param root the root + * @param className the class name + * @param extendClass the extend class + * @return the annotation + */ + private HashMap getAnnotation(EPackage root, String className, String extendClass) { + TreeIterator treeItr = root.eAllContents(); + boolean requiredAttribute = false; + boolean requiredMatchAttribute = false; + HashMap annotationSet = new HashMap<>(); + + // Pulling out dependency from file + while (treeItr.hasNext()) { + EObject obj = treeItr.next(); + if (obj instanceof EClassifier) { + requiredAttribute = isRequiredAttribute(obj, className); + requiredMatchAttribute = isRequiredAttribute(obj, extendClass); + } + + if (requiredAttribute) { + if (obj instanceof EStructuralFeature) { + checkAnnotation(annotationSet, (EStructuralFeature) obj); + } + } else if (requiredMatchAttribute && (obj instanceof EStructuralFeature)) { + findMatchingAnnotation(annotationSet, obj); + } + } + return annotationSet; + } + + /** + * Find matching annotation. + * + * @param annotationSet the annotation set + * @param obj the obj + */ + private void findMatchingAnnotation(HashMap annotationSet, EObject obj) { + EStructuralFeature estrucClassifier = (EStructuralFeature) obj; + if (estrucClassifier.getEAnnotations().isEmpty()) { + return; + } + String matching = annotationValue(estrucClassifier, AnnotationType.MATCHING, policy); + if (matching != null) { + if (obj instanceof EReference) { + EClass refType = ((EReference) obj).getEReferenceType(); + annotationSet.put(refType.getName(), matching); + matchingClass.put(refType.getName(), matching); + } else { + annotationSet.put(estrucClassifier.getName(), matching); + } + } + + } + + /** + * Check annotation. + * + * @param annotationSet the annotation set + * @param obj the obj + */ + private void checkAnnotation(HashMap annotationSet, EStructuralFeature obj) { + EStructuralFeature estrucClassifier = obj; + if (estrucClassifier.getEAnnotations().isEmpty()) { + return; + } + String matching = annotationValue(estrucClassifier, AnnotationType.MATCHING, policy); + if (matching != null) { + annotationSet.put(estrucClassifier.getName(), matching); + } + String range = annotationValue(estrucClassifier, AnnotationType.VALIDATION, policy); + if (range != null) { + annotationSet.put(estrucClassifier.getName(), range); + } + String annotationDict = annotationValue(estrucClassifier, AnnotationType.DICTIONARY, policy); + if (annotationDict != null) { + annotationSet.put(estrucClassifier.getName(), annotationDict); + } + } + + /** + * Gets the sub attribute list. + * + * @param root the root + * @param className the class name + * @param superClass the super class + * @return the sub attribute list + */ + private Map getSubAttributeList(EPackage root, String className, String superClass) { + TreeIterator treeItr = root.eAllContents(); + boolean requiredAttribute = false; + Map subAttribute = new HashMap<>(); + int rollingCount = 0; + int processClass = 0; + + // Pulling out dependency from file + while (treeItr.hasNext() && rollingCount < 2) { + + EObject obj = treeItr.next(); + if (obj instanceof EClassifier) { + requiredAttribute = isRequiredAttribute(obj, className) || isRequiredAttribute(obj, superClass); + if (requiredAttribute) { + processClass++; + } + rollingCount = rollingCount + processClass; + } + + if (requiredAttribute && (obj instanceof EStructuralFeature)) { + EStructuralFeature estrucClassifier = (EStructuralFeature) obj; + if (!estrucClassifier.getEAnnotations().isEmpty()) { + updateSubAttributes(subAttribute, obj, estrucClassifier); + } + } + } + return subAttribute; + } + + /** + * Update sub attributes. + * + * @param subAttribute the sub attribute + * @param obj the obj + * @param estrucClassifier the e struc classifier + */ + private void updateSubAttributes(Map subAttribute, EObject obj, + EStructuralFeature estrucClassifier) { + if (!(obj instanceof EReference)) { + return; + } + if (annotationTest(estrucClassifier, CONFIGURATION, onap)) { + EClass refType = ((EReference) obj).getEReferenceType(); + if (!refType.toString().contains(E_PROXY_URI)) { + String required = REQUIREDFALSE; + if (estrucClassifier.getLowerBound() == 1) { + required = REQUIREDTRUE; + } + subAttribute.put(estrucClassifier.getName(), refType.getName() + required); + } + } + } + + /** + * Check defult value. + * + * @param defultValue the defult value + * @return the string + */ + public String checkDefultValue(String defultValue) { + if (defultValue != null) { + return DEFAULTVALUE + defultValue; + } + return ":defaultValue-NA"; + + } + + /** + * Check required pattern. + * + * @param upper the upper + * @param lower the lower + * @return the string + */ + public String checkRequiredPattern(int upper, int lower) { + String pattern = XACMLProperties.getProperty(XacmlRestProperties.PROP_XCORE_REQUIRED_PATTERN); + if (pattern != null && upper == Integer.parseInt(pattern.split(",")[1]) + && lower == Integer.parseInt(pattern.split(",")[0])) { + return REQUIREDTRUE; + } + return REQUIREDFALSE; + } + + /** + * Builds the java object. + * + * @param map the map + * @return the JSON object + */ + public JSONObject buildJavaObject(Map map) { + return new JSONObject(map); + } + + /** + * Gets the ref attribute list. + * + * @param root the root + * @param className the class name + * @param superClass the super class + * @return the ref attribute list + */ + public Map getRefAttributeList(EPackage root, String className, String superClass) { + + TreeIterator treeItr = root.eAllContents(); + boolean requiredAttribute = false; + HashMap refAttribute = new HashMap<>(); + int rollingCount = 0; + int processClass = 0; + boolean annotation; + // Pulling out dependency from file + while (treeItr.hasNext()) { + EObject obj = treeItr.next(); + if (obj instanceof EClassifier) { + requiredAttribute = isRequiredAttribute(obj, className) || isRequiredAttribute(obj, superClass); + if (requiredAttribute) { + processClass++; + } + rollingCount = rollingCount + processClass; + } + + if (requiredAttribute && (obj instanceof EStructuralFeature)) { + EStructuralFeature estrucClassifier = (EStructuralFeature) obj; + if (!estrucClassifier.getEAnnotations().isEmpty()) { + annotation = annotationTest(estrucClassifier, CONFIGURATION, onap); + if (annotation && obj instanceof EReference) { + updRefAttributes(refAttribute, (EStructuralFeature) obj, estrucClassifier); + } else if (annotation && obj instanceof EAttributeImpl) { + updEnumTypeRefAttrib(refAttribute, (EStructuralFeature) obj, estrucClassifier); + } + } + } + } + + return refAttribute; + } + + /** + * Upd enum type ref attrib. + * + * @param refAttribute the ref attribute + * @param obj the obj + * @param estrucClassifier the e struc classifier + */ + private void updEnumTypeRefAttrib(HashMap refAttribute, EStructuralFeature obj, + EStructuralFeature estrucClassifier) { + EClassifier refType = ((EAttributeImpl) obj).getEType(); + if (!(refType instanceof EEnumImpl)) { + return; + } + + String array = arrayCheck(obj.getUpperBound()); + String required = REQUIREDFALSE; + if (obj.getLowerBound() == 1) { + required = REQUIREDTRUE; + } + refAttribute.put(estrucClassifier.getName(), refType.getName() + array + required); + } + + /** + * Upd ref attributes. + * + * @param refAttribute the ref attribute + * @param obj the obj + * @param estrucClassifier the e struc classifier + */ + private void updRefAttributes(HashMap refAttribute, EStructuralFeature obj, + EStructuralFeature estrucClassifier) { + EClass refType = ((EReference) obj).getEReferenceType(); + if (refType.toString().contains(E_PROXY_URI)) { + String one = refType.toString().split(E_PROXY_URI)[1]; + String refValue = StringUtils.replaceEach(one.split("#")[1], new String[] + { "//", ")" }, new String[] + { "", "" }); + refAttribute.put(estrucClassifier.getName(), refValue); + } else { + String required = REQUIREDFALSE; + if (obj.getLowerBound() == 1) { + required = REQUIREDTRUE; + } + refAttribute.put(estrucClassifier.getName(), + refType.getName() + arrayCheck(obj.getUpperBound()) + required); + } + } + + /** + * Annotation test. + * + * @param estrucClassifier the e struc classifier + * @param annotation the annotation + * @param type the type + * @return true, if successful + */ + private boolean annotationTest(EStructuralFeature estrucClassifier, String annotation, String type) { + String annotationType; + EAnnotation eannotation; + String onapType; + String onapValue; + + EList value = estrucClassifier.getEAnnotations(); + + for (int i = 0; i < value.size(); i++) { + annotationType = value.get(i).getSource(); + eannotation = estrucClassifier.getEAnnotations().get(i); + onapType = eannotation.getDetails().get(0).getValue(); + onapValue = eannotation.getDetails().get(0).getKey(); + + if (annotationType.contains(type) && onapType.contains(annotation)) { + return true; + } + + if (annotationType.contains(type) && onapValue.contains(annotation)) { + return true; + } + } + + return false; + } + + /** + * Annotation value. + * + * @param estrucClassifier the e struc classifier + * @param annotation the annotation + * @param type the type + * @return the string + */ + private String annotationValue(EStructuralFeature estrucClassifier, AnnotationType annotation, String type) { + String annotationType; + EAnnotation eannotation; + String onapType; + String onapValue = null; + + EList value = estrucClassifier.getEAnnotations(); + + for (int i = 0; i < value.size(); i++) { + annotationType = value.get(i).getSource(); + eannotation = estrucClassifier.getEAnnotations().get(i); + onapType = eannotation.getDetails().get(0).getKey(); + if (annotationType.contains(type) && onapType.compareToIgnoreCase(annotation.toString()) == 0) { + onapValue = eannotation.getDetails().get(0).getValue(); + if (annotation == AnnotationType.VALIDATION) { + return onapValue; + } else { + return onapType + "-" + onapValue; + } + } + } + + return onapValue; + } + + /** + * Checks if is required attribute. + * + * @param obj the obj + * @param className the class name + * @return true, if is required attribute + */ + public boolean isRequiredAttribute(EObject obj, String className) { + EClassifier eclassifier = (EClassifier) obj; + String workingClass = eclassifier.getName().trim(); + return workingClass.equalsIgnoreCase(className); + } + + /** + * Checks if is policy template. + * + * @param root the root + * @param className the class name + * @return true, if is policy template + */ + private boolean isPolicyTemplate(EPackage root, String className) { + boolean result = false; + for (EClassifier classifier : root.getEClassifiers()) { + if (classifier instanceof EClass) { + EClass eclass = (EClass) classifier; + if (eclass.getName().contentEquals(className)) { + result = checkPolicyTemplate(eclass); + break; + } + } + } + return result; + } + + /** + * Check policy template. + * + * @param eclass the e class + * @return true, if successful + */ + private boolean checkPolicyTemplate(EClass eclass) { + EList value = eclass.getEAnnotations(); + for (EAnnotation workingValue : value) { + EMap keyMap = workingValue.getDetails(); + if (keyMap.containsKey("policyTemplate")) { + return true; + } + } + return false; + } + + /** + * Gets the sub types. + * + * @param root the root + * @param className the class name + * @return the sub types + */ + private String getSubTypes(EPackage root, String className) { + String returnSubTypes = null; + for (EClassifier classifier : root.getEClassifiers()) { + if (classifier instanceof EClass) { + returnSubTypes = findSubTypes(className, returnSubTypes, (EClass) classifier); + } + } + return returnSubTypes; + } + + /** + * Find sub types. + * + * @param className the class name + * @param returnSubTypes the return sub types + * @param classifier the classifier + * @return the string + */ + private String findSubTypes(String className, String returnSubTypes, EClass classifier) { + EClass eclass = classifier; + + for (EClass esuperType : eclass.getEAllSuperTypes()) { + if (eclass.getName().contentEquals(className)) { + returnSubTypes = esuperType.getName(); + } + } + return returnSubTypes; + } + + /** + * Gets the attribute list. + * + * @param root the root + * @param className the class name + * @param superClass the super class + * @return the attribute list + */ + public Map getAttributeList(EPackage root, String className, String superClass) { + + TreeIterator treeItr = root.eAllContents(); + boolean requiredAttribute = false; + HashMap refAttribute = new HashMap<>(); + + // Pulling out dependency from file + while (treeItr.hasNext()) { + EObject obj = treeItr.next(); + if (obj instanceof EClassifier) { + requiredAttribute = isRequiredAttribute(obj, className) || isRequiredAttribute(obj, superClass); + } + + if (requiredAttribute && (obj instanceof EStructuralFeature)) { + EStructuralFeature estrucClassifier = (EStructuralFeature) obj; + if (!estrucClassifier.getEAnnotations().isEmpty()) { + checkStrucClassifier(refAttribute, obj, estrucClassifier); + } + } + } + return refAttribute; + + } + + /** + * Check struc classifier. + * + * @param refAttribute the ref attribute + * @param obj the obj + * @param estrucClassifier the e struc classifier + */ + private void checkStrucClassifier(HashMap refAttribute, EObject obj, + EStructuralFeature estrucClassifier) { + EClassifier refType = ((EStructuralFeature) obj).getEType(); + boolean annotation = annotationTest(estrucClassifier, CONFIGURATION, onap); + boolean dictionaryTest = annotationTest(estrucClassifier, DICTIONARY, policy); + if (annotation && !(obj instanceof EReference) && !(refType instanceof EEnumImpl)) { + updEReferenceAttrib(refAttribute, dictionaryTest, (EStructuralFeature) obj, estrucClassifier); + } + } + + /** + * Upd E reference attrib. + * + * @param refAttribute the ref attribute + * @param dictionaryTest the dictionary test + * @param obj the obj + * @param estrucClassifier the e struc classifier + */ + private void updEReferenceAttrib(HashMap refAttribute, boolean dictionaryTest, + EStructuralFeature obj, EStructuralFeature estrucClassifier) { + String etype; + String name = estrucClassifier.getName(); + if (dictionaryTest) { + etype = annotationValue(estrucClassifier, AnnotationType.DICTIONARY, policy); + } else { + etype = estrucClassifier.getEType().getInstanceClassName(); + } + String defaultValue = checkDefultValue(obj.getDefaultValueLiteral()); + String array = arrayCheck(obj.getUpperBound()); + String required = checkRequiredPattern(obj.getUpperBound(), obj.getLowerBound()); + refAttribute.put(name, etype + defaultValue + required + array); + } + + /** + * Array check. + * + * @param upperBound the upper bound + * @return the string + */ + public String arrayCheck(int upperBound) { + + if (upperBound == -1) { + return MANYTRUE; + } + + return MANYFALSE; + } + + /** + * Gets the dependency list. + * + * @param eclassifier the e classifier + * @return the dependency list + */ + public List getDependencyList(EClassifier eclassifier) { + List returnValue = new ArrayList<>(); + ; + EList somelist = ((EClass) eclassifier).getEAllSuperTypes(); + if (somelist.isEmpty()) { + return returnValue; + } + for (EClass depend : somelist) { + if (depend.toString().contains(E_PROXY_URI)) { + String one = depend.toString().split(E_PROXY_URI)[1]; + String value = StringUtils.replaceEach(one.split("#")[1], new String[] + { "//", ")" }, new String[] + { "", "" }); + returnValue.add(value); + } + } + + return returnValue; + } + + /** + * Builds the sub list. + * + * @param subClassAttributes the sub class attributes + * @param classMap the class map + * @param className the class name + * @return the map + */ + public Map buildSubList(Map subClassAttributes, + Map classMap, String className) { + Map missingValues = new HashMap<>(); + Map workingMap; + boolean enumType; + + for (Entry map : classMap.get(className).getRefAttribute().entrySet()) { + String value = map.getValue().split(":")[0]; + if (value != null) { + classMap.get(className).getEnumType(); + enumType = classMap.get(className).getEnumType().containsKey(value); + if (!enumType) { + workingMap = classMap.get(value).getRefAttribute(); + for (Entry subMab : workingMap.entrySet()) { + String value2 = subMab.getValue().split(":")[0]; + if (!subClassAttributes.containsValue(value2)) { + missingValues.put(subMab.getKey(), subMab.getValue()); + } + } + + } + } + } + + return missingValues; + } + + /** + * Recursive reference. + * + * @param classMap the class map + * @param className the class name + * @return the map + */ + public Map> recursiveReference(Map classMap, + String className) { + + Map> returnObject = new HashMap<>(); + Map returnClass = getRefclass(classMap, className); + returnObject.put(className, returnClass); + for (Entry reAttribute : returnClass.entrySet()) { + if (reAttribute.getValue().split(":")[1].contains("MANY") + && classMap.get(reAttribute.getValue().split(":")[0]) != null) { + returnObject.putAll(recursiveReference(classMap, reAttribute.getValue().split(":")[0])); + } + + } + + return returnObject; + + } + + /** + * Creates the json. + * + * @param classMap the class map + * @param className the class name + * @return the string + */ + public String createJson(Map classMap, String className) { + boolean enumType; + Map> myObject = new HashMap<>(); + for (Entry map : classMap.get(className).getRefAttribute().entrySet()) { + String value = map.getValue().split(":")[0]; + if (value != null) { + enumType = classMap.get(className).getEnumType().containsKey(value); + if (!enumType && map.getValue().split(":")[1].contains("MANY")) { + Map> testRecursive = recursiveReference(classMap, + map.getValue().split(":")[0]); + myObject.putAll(testRecursive); + } + } + } + + Gson gson = new Gson(); + return gson.toJson(myObject); + } + + /** + * Gets the refclass. + * + * @param classMap the class map + * @param className the class name + * @return the refclass + */ + public Map getRefclass(Map classMap, String className) { + HashMap missingValues = new HashMap<>(); + + if (classMap.get(className).getAttribute() != null || !classMap.get(className).getAttribute().isEmpty()) { + missingValues.putAll(classMap.get(className).getAttribute()); + } + + if (classMap.get(className).getRefAttribute() != null || !classMap.get(className).getRefAttribute().isEmpty()) { + missingValues.putAll(classMap.get(className).getRefAttribute()); + } + + return missingValues; + } + + /** + * Creates the sub attributes. + * + * @param dependency the dependency + * @param classMap the class map + * @param modelName the model name + * @return the string + */ + public String createSubAttributes(List dependency, Map classMap, + String modelName) { + + HashMap workingMap = new HashMap<>(); + MsAttributeObject tempObject; + if (dependency != null) { + if (dependency.isEmpty()) { + return "{}"; + } + dependency.add(modelName); + for (String element : dependency) { + tempObject = classMap.get(element); + if (tempObject != null) { + workingMap.putAll(classMap.get(element).getSubClass()); + } + } + } + + return createJson(classMap, modelName); + } + + /** + * Gets the full dependency list. + * + * @param dependency the dependency + * @param classMap the class map + * @return the full dependency list + */ + public List getFullDependencyList(List dependency, Map classMap) { + ArrayList returnList = new ArrayList<>(); + ArrayList workingList; + returnList.addAll(dependency); + for (String element : dependency) { + if (classMap.containsKey(element)) { + MsAttributeObject value = classMap.get(element); + String rawValue = StringUtils.replaceEach(value.getDependency(), new String[] + { "[", "]" }, new String[] + { "", "" }); + workingList = new ArrayList<>(Arrays.asList(rawValue.split(","))); + for (String depend : workingList) { + updDependencyList(returnList, depend); + } + } + } + + return returnList; + } + + /** + * Upd dependency list. + * + * @param returnList the return list + * @param depend the depend + */ + private void updDependencyList(ArrayList returnList, String depend) { + if (!returnList.contains(depend) && !depend.isEmpty()) { + returnList.add(depend.trim()); + } + } + + /** + * Parses the TOSCA model. + * + * @param fileName the file name + * @return the string + */ + public String parseTosca(String fileName) { + Map map = new LinkedHashMap<>(); + try { + map = load(fileName); + if (map != null && map.get(ERROR) != null) { + return map.get(ERROR); + } + parseDataAndPolicyNodes(map); + LinkedHashMap dataMapForJson = parseDataNodes(map); + constructJsonForDataFields(dataMapForJson); + LinkedHashMap> mapKey = parsePolicyNodes(map); + createAttributes(mapKey); + + } catch (IOException e) { + logger.error(e); + } catch (ParserException e) { + logger.error(e); + return e.getMessage(); + } + + return null; + } + + /** + * Load. + * + * @param fileName the file name + * @return the map + * @throws IOException Signals that an I/O exception has occurred. + * @throws ParserException the parser exception + */ + public Map load(String fileName) throws IOException, ParserException { + File newConfiguration = new File(fileName); + StringBuilder orderInfo = new StringBuilder("["); + Yaml yaml = new Yaml(); + LinkedHashMap yamlMap = null; + try (InputStream is = new FileInputStream(newConfiguration)) { + yamlMap = yaml.load(is); + } catch (FileNotFoundException e) { + logger.error(e); + } catch (Exception e) { + logger.error(e); + throw new ParserException("Invalid TOSCA Model format. Please make sure it is a valid YAML file"); + } + + LinkedHashMap settings = new LinkedHashMap<>(); + if (yamlMap == null) { + return settings; + } + + String message = validations(yamlMap); + + if (message != null) { + settings.put(ERROR, message); + return settings; + } + + findNode(yamlMap); + + if (!isDuplicatedAttributes && orderedElements != null && !orderedElements.isEmpty()) { + orderedElements.stream().forEach(string -> { + orderInfo.append(string); + orderInfo.append(","); + logger.info("Content: " + string); + }); + + orderInfo.append("]"); + + dataOrderInfo = orderInfo.toString(); + dataOrderInfo = dataOrderInfo.replace(",]", "]"); + + logger.info("dataOrderInfo :" + dataOrderInfo); + } + + List path = new ArrayList<>(); + serializeMap(settings, new StringBuilder(), path, yamlMap); + return settings; + } + + /** + * Validations. + * + * @param yamlMap the yaml map + * @return the string + */ + @SuppressWarnings("unchecked") + private String validations(@SuppressWarnings("rawtypes") Map yamlMap) { + + boolean isNoteTypeFound = false; + boolean isDataTypeFound = false; + boolean isToscaVersionKeyFound = false; + boolean isToscaVersionValueFound = false; + @SuppressWarnings("rawtypes") + Map m1 = new HashMap(); + short order = 0; + if (yamlMap != null) { + // Get a set of the entries + @SuppressWarnings("rawtypes") + Set entries = yamlMap.entrySet(); + for (Map.Entry me : entries) { + if (TOSCA_SIMPLE_YAML_1_0_0.equals(me.getValue())) { + isToscaVersionValueFound = true; + } + + switch (me.getKey().toString()) { + case TOSCA_DEFINITION_VERSION: + isToscaVersionKeyFound = true; + order++; + m1.put(TOSCA_DEFINITION_VERSION, order); + break; + case NODE_TYPE: + isNoteTypeFound = true; + order++; + m1.put(NODE_TYPE, order); + break; + case DATA_TYPE: + isDataTypeFound = true; + order++; + m1.put(DATA_TYPE, order); + break; + case JSON_MODEL: + setJsonRuleFormation(me.getValue().toString()); + break; + default: + break; + } + } + if (!isDataTypeFound) { + return "data_types are missing or invalid."; + } + if (!isToscaVersionKeyFound || !isToscaVersionValueFound) { + return "tosca_definitions_version is missing or invalid."; + } + + if (!isNoteTypeFound) { + return "node_types are missing or invalid."; + } + + short version = (short) m1.get(TOSCA_DEFINITION_VERSION); + + if (version > 1) { + return "tosca_definitions_version should be defined first."; + } + + short data = (short) m1.get(DATA_TYPE); + short node = (short) m1.get(NODE_TYPE); + if (isDataTypeFound && node > data) { + return "node_types should be defined before data_types."; + } + + } + + return null; + } + + /** + * Serialize map. + * + * @param settings the settings + * @param sb the sb + * @param path the path + * @param yamlMap the yaml map + */ + @SuppressWarnings( + { "unchecked", "rawtypes" }) + private void serializeMap(LinkedHashMap settings, StringBuilder sb, List path, + Map yamlMap) { + for (Map.Entry entry : yamlMap.entrySet()) { + + if (entry.getValue() instanceof Map) { + path.add((String) entry.getKey()); + serializeMap(settings, sb, path, (Map) entry.getValue()); + path.remove(path.size() - 1); + } else if (entry.getValue() instanceof List) { + path.add((String) entry.getKey()); + serializeList(settings, sb, path, (List) entry.getValue()); + path.remove(path.size() - 1); + } else { + serializeValue(settings, sb, path, (String) entry.getKey(), entry.getValue()); + } + } + } + + /** + * Serialize list. + * + * @param settings the settings + * @param sb the sb + * @param path the path + * @param yamlList the yaml list + */ + @SuppressWarnings("unchecked") + private void serializeList(LinkedHashMap settings, StringBuilder sb, List path, + List yamlList) { + int counter = 0; + for (Object listEle : yamlList) { + if (listEle instanceof Map) { + path.add(Integer.toString(counter)); + serializeMap(settings, sb, path, (Map) listEle); + path.remove(path.size() - 1); + } else if (listEle instanceof List) { + path.add(Integer.toString(counter)); + serializeList(settings, sb, path, (List) listEle); + path.remove(path.size() - 1); + } else { + serializeValue(settings, sb, path, Integer.toString(counter), listEle); + } + counter++; + } + } + + /** + * Serialize value. + * + * @param settings the settings + * @param sb the sb + * @param path the path + * @param name the name + * @param value the value + */ + private void serializeValue(LinkedHashMap settings, StringBuilder sb, List path, + String name, Object value) { + if (value == null) { + return; + } + sb.setLength(0); + for (String pathEle : path) { + sb.append(pathEle).append('.'); + } + sb.append(name); + settings.put(sb.toString(), value.toString()); + } + + /** + * Parses the data and policy nodes. + * + * @param map the map + */ + void parseDataAndPolicyNodes(Map map) { + for (String key : map.keySet()) { + if (key.contains("policy.nodes.Root")) { + continue; + } else if (key.contains("policy.nodes")) { + String wordToFind = "policy.nodes."; + int indexForPolicyNode = key.indexOf(wordToFind); + String subNodeString = key.substring(indexForPolicyNode + 13, key.length()); + + stringBetweenDots(subNodeString); + } else if (key.contains("policy.data")) { + String wordToFind = "policy.data."; + int indexForPolicyNode = key.indexOf(wordToFind); + String subNodeString = key.substring(indexForPolicyNode + 12, key.length()); + + stringBetweenDotsForDataFields(subNodeString); + } + } + } + + /** + * String between dots. + * + * @param str the str + * @return the int + */ + // Second index of dot should be returned. + public int stringBetweenDots(String str) { + String stringToSearch = str; + String[] ss = stringToSearch.split("\\."); + if (ss != null) { + int len = ss.length; + if (len > 2) { + uniqueKeys.add(ss[2]); + } + } + + return uniqueKeys.size(); + } + + /** + * String between dots for data fields. + * + * @param str the str + */ + public void stringBetweenDotsForDataFields(String str) { + String stringToSearch = str; + String[] ss = stringToSearch.split("\\."); + if (ss != null) { + int len = ss.length; + + if (len > 2) { + uniqueDataKeys.add(ss[0] + "%" + ss[2]); + } + } + } + + /** + * Construct json for data fields. + * + * @param dataMapForJson the data map for json + */ + void constructJsonForDataFields(LinkedHashMap dataMapForJson) { + LinkedHashMap> dataMapKey = new LinkedHashMap<>(); + LinkedHashMap hmSub; + for (Map.Entry entry : dataMapForJson.entrySet()) { + String uniqueDataKey = entry.getKey(); + String[] uniqueDataKeySplit = uniqueDataKey.split("%"); + String value = dataMapForJson.get(uniqueDataKey); + if (dataMapKey.containsKey(uniqueDataKeySplit[0])) { + hmSub = dataMapKey.get(uniqueDataKeySplit[0]); + hmSub.put(uniqueDataKeySplit[1], value); + } else { + hmSub = new LinkedHashMap<>(); + hmSub.put(uniqueDataKeySplit[1], value); + } + + dataMapKey.put(uniqueDataKeySplit[0], hmSub); + } + + JSONObject mainObject = new JSONObject(); + JSONObject json; + for (Map.Entry> entry : dataMapKey.entrySet()) { + String keyString = entry.getKey(); + json = new JSONObject(); + HashMap jsonHm = dataMapKey.get(keyString); + for (Map.Entry entryMap : jsonHm.entrySet()) { + String key = entryMap.getKey(); + json.put(key, jsonHm.get(key)); + } + mainObject.put(keyString, json); + } + Iterator keysItr = mainObject.keys(); + while (keysItr.hasNext()) { + String key = keysItr.next(); + String value = mainObject.get(key).toString(); + retmap.put(key, value); + } + + logger.info("#############################################################################"); + logger.info(mainObject); + logger.info("###############################################################################"); + } + + /** + * Parses the data nodes. + * + * @param map the map + * @return the linked hash map + */ + LinkedHashMap parseDataNodes(Map map) { + LinkedHashMap dataMapForJson = new LinkedHashMap<>(); + matchableValues = new HashMap<>(); + for (String uniqueDataKey : uniqueDataKeys) { + if (uniqueDataKey.contains("%")) { + String[] uniqueDataKeySplit = uniqueDataKey.split("%"); + String findType = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] + TYPE; + String typeValue = map.get(findType); + logger.info(typeValue); + + String findRequired = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] + REQUIRED; + String requiredValue = map.get(findRequired); + + String matchable = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] + MATCHABLE; + + String matchableValue = map.get(matchable); + + if ("true".equalsIgnoreCase(matchableValue)) { + String key = uniqueDataKeySplit[uniqueDataKeySplit.length - 1]; + matchableValues.put(key, MATCHINGTRUE); + } + + if (requiredValue == null || requiredValue.isEmpty()) { + requiredValue = "false"; + } + if (INTEGER.equalsIgnoreCase(typeValue) || STRING.equalsIgnoreCase(typeValue) + || typeValue.equalsIgnoreCase(BOOLEAN)) { + String findDefault = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] + + DEFAULT; + String defaultValue = map.get(findDefault); + logger.info("defaultValue is:" + defaultValue); + logger.info("requiredValue is:" + requiredValue); + + StringBuilder attributeIndividualStringBuilder = new StringBuilder(); + attributeIndividualStringBuilder.append(typeValue + DEFAULTVALUE); + attributeIndividualStringBuilder.append(defaultValue + REQUIREDVALUE); + attributeIndividualStringBuilder.append(requiredValue + MANYFALSE); + + String findDescription = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] + + DESCRIPTION; + attributeIndividualStringBuilder.append(DESCRIPTION_TOKEN + map.get(findDescription)); + dataMapForJson.put(uniqueDataKey, attributeIndividualStringBuilder.toString()); + } else if (LIST.equalsIgnoreCase(typeValue) || MAP.equalsIgnoreCase(typeValue)) { + logger.info("requiredValue is:" + requiredValue); + String findList = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] + + ".entry_schema.type"; + String findDefaultValue = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] + + ".entry_schema.default"; + String findDescription = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] + + ".entry_schema.description"; + String listValue = map.get(findList); + String defaultValue = map.get(findDefaultValue); + String description = map.get(findDescription); + if (listValue != null) { + logger.info("Type of list is:" + listValue); + // Its userdefined + if (listValue.contains(".")) { + String trimValue = listValue.substring(listValue.lastIndexOf('.') + 1); + StringBuilder referenceIndividualStringBuilder = new StringBuilder(); + referenceIndividualStringBuilder.append(trimValue + REQUIREDVALUE); + referenceIndividualStringBuilder.append(requiredValue + MANYTRUE); + referenceIndividualStringBuilder.append(DESCRIPTION_TOKEN + description); + dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString()); + } else { // Its string + StringBuilder stringListItems = new StringBuilder(); + if (LIST.equalsIgnoreCase(typeValue)) { + stringListItems.append(uniqueDataKeySplit[1].toUpperCase() + DEFAULTVALUE + defaultValue + + REQUIREDVALUE + requiredValue + MANYFALSE + DESCRIPTION_TOKEN + + description); + } else if (MAP.equalsIgnoreCase(typeValue)) { + stringListItems.append(uniqueDataKeySplit[1].toUpperCase() + DEFAULTVALUE + defaultValue + + REQUIREDVALUE + requiredValue + MANYTRUE + DESCRIPTION_TOKEN + + description); + } + dataMapForJson.put(uniqueDataKey, stringListItems.toString()); + dataListBuffer.append(uniqueDataKeySplit[1].toUpperCase() + "=["); + for (int i = 0; i < 10; i++) { + String findConstraints = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + + uniqueDataKeySplit[1] + ".entry_schema.constraints.0.valid_values." + + i; + String constraintsValue = map.get(findConstraints); + logger.info(constraintsValue); + boolean ruleCheck = false; + if (constraintsValue == null) { + break; + } else if (constraintsValue.startsWith(DICTIONARY)) { + List dictFromDB = null; + String[] dictionaryNameValRule; + String[] dictionaryName = constraintsValue.split(":"); + String dictionaryNameVal = dictionaryName[1]; + if (dictionaryNameVal.contains("#Rules")) { + ruleCheck = true; + dictionaryNameValRule = dictionaryNameVal.split("#"); + dictFromDB = commonClassDao.getDataById(DictionaryData.class, DICTIONARYNAME, + dictionaryNameValRule[0]); + } else { + dictFromDB = commonClassDao.getDataById(DictionaryData.class, DICTIONARYNAME, + dictionaryName[1]); + } + if (dictFromDB != null && !dictFromDB.isEmpty()) { + DictionaryData data = (DictionaryData) dictFromDB.get(0); + if (ruleCheck) { + constraintsValue = DICTIONARY + data.getDictionaryUrl() + "@" + + data.getDictionaryDataByName() + "&Rule"; + } else { + constraintsValue = DICTIONARY + data.getDictionaryUrl() + "@" + + data.getDictionaryDataByName(); + } + } + dataListBuffer.append(constraintsValue + ","); + } else { + logger.info("constraintsValue => " + constraintsValue); + if (constraintsValue.contains("=")) { + constraintsValue = constraintsValue.replace("=", "equal-sign"); + } + dataConstraints.add(constraintsValue); + dataListBuffer.append(constraintsValue + ","); + } + } + dataListBuffer.append("]#"); + logger.info(dataListBuffer); + } + } + } else { + String findUserDefined = DATATYPE + uniqueDataKeySplit[0] + "." + PROPERTIES_KEY + "." + + uniqueDataKeySplit[1] + TYPE; + String findDescription = DATATYPE + uniqueDataKeySplit[0] + "." + PROPERTIES_KEY + "." + + uniqueDataKeySplit[1] + DESCRIPTION; + String userDefinedValue = map.get(findUserDefined); + String description = map.get(findDescription); + String trimValue = userDefinedValue.substring(userDefinedValue.lastIndexOf('.') + 1); + StringBuilder referenceIndividualStringBuilder = new StringBuilder(); + referenceIndividualStringBuilder.append(trimValue + REQUIREDVALUE); + referenceIndividualStringBuilder.append(requiredValue + MANYFALSE); + referenceIndividualStringBuilder.append(DESCRIPTION_TOKEN + description); + dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString()); + + } + } else { + matchableValues.put(uniqueDataKey, MATCHINGTRUE); + } + } + + return dataMapForJson; + } + + /** + * Parses the policy nodes. + * + * @param map the map + * @return the linked hash map + * @throws ParserException the parser exception + */ + LinkedHashMap> parsePolicyNodes(Map map) + throws ParserException { + LinkedHashMap> mapKey = new LinkedHashMap<>(); + for (String uniqueKey : uniqueKeys) { + LinkedHashMap hm; + + for (Entry entry : map.entrySet()) { + String key = entry.getKey(); + if (key.contains(uniqueKey) && key.contains("policy.nodes")) { + if (mapKey.containsKey(uniqueKey)) { + hm = mapKey.get(uniqueKey); + String keyStr = key.substring(key.lastIndexOf('.') + 1); + String valueStr = map.get(key); + if ("type".equalsIgnoreCase(keyStr) && key.contains("entry_schema.0.type") + || key.contains("entry_schema.type") && valueStr.contains("policy.data.")) { + throw new ParserException("For user defined object type," + + " Please make sure no space between 'type:' and object " + valueStr); + + } + if ("type".equals(keyStr)) { + if (!key.contains("entry_schema")) { + hm.put(keyStr, valueStr); + } + } else { + hm.put(keyStr, valueStr); + } + + } else { + hm = new LinkedHashMap<>(); + String keyStr = key.substring(key.lastIndexOf('.') + 1); + String valueStr = map.get(key); + + if (("type").equals(keyStr)) { + if (!key.contains("entry_schema")) { + hm.put(keyStr, valueStr); + } + } else { + hm.put(keyStr, valueStr); + } + mapKey.put(uniqueKey, hm); + } + } + } + } + return mapKey; + } + + /** + * Creates the attributes. + * + * @param mapKey the map key + */ + private void createAttributes(LinkedHashMap> mapKey) { + StringBuilder attributeStringBuilder = new StringBuilder(); + StringBuilder referenceStringBuilder = new StringBuilder(); + StringBuilder listBuffer = new StringBuilder(); + List constraints = new ArrayList<>(); + for (Map.Entry> entry : mapKey.entrySet()) { + String keySetString = entry.getKey(); + LinkedHashMap keyValues = mapKey.get(keySetString); + if (keyValues.get("type") != null && (STRING.equalsIgnoreCase(keyValues.get("type")) + || INTEGER.equalsIgnoreCase(keyValues.get("type")) + || BOOLEAN.equalsIgnoreCase(keyValues.get("type")))) { + StringBuilder attributeIndividualStringBuilder = new StringBuilder(); + attributeIndividualStringBuilder.append(keySetString + "="); + attributeIndividualStringBuilder.append(keyValues.get("type") + DEFAULTVALUE); + attributeIndividualStringBuilder.append(keyValues.get("default") + REQUIREDVALUE); + attributeIndividualStringBuilder.append(keyValues.get("required") + MANYFALSE); + attributeIndividualStringBuilder.append(DESCRIPTION_TOKEN + keyValues.get(DESCRIPTION_KEY)); + attributeStringBuilder.append(attributeIndividualStringBuilder + ","); + if (keyValues.get(MATCHABLEKEY) != null && "true".equalsIgnoreCase(keyValues.get(MATCHABLEKEY))) { + matchableValues.put(keySetString, MATCHINGTRUE); + } + } else if (LIST.equalsIgnoreCase(keyValues.get("type"))) { + if ("true".equalsIgnoreCase(keyValues.get(MATCHABLEKEY))) { + matchableValues.put(keySetString, MATCHINGTRUE); + } + // List Data type + Set keys = keyValues.keySet(); + Iterator itr = keys.iterator(); + boolean isDefinedType = false; + while (itr.hasNext()) { + String key = itr.next(); + if ((!("type").equals(key) || ("required").equals(key))) { + String value = keyValues.get(key); + // The "." in the value determines if its a string or a user defined type. + if (!value.contains(".")) { + // This is string + if (StringUtils.isNumeric(key)) { // only integer key for the value of Constrains + constraints.add(keyValues.get(key)); + } + } else { + // This is user defined type + String trimValue = value.substring(value.lastIndexOf('.') + 1); + StringBuilder referenceIndividualStringBuilder = new StringBuilder(); + referenceIndividualStringBuilder.append(keySetString + "=" + trimValue + MANYTRUE + + DESCRIPTION_TOKEN + keyValues.get(DESCRIPTION_KEY)); + referenceStringBuilder.append(referenceIndividualStringBuilder + ","); + isDefinedType = true; + } + } + + } + + if (!isDefinedType && LIST.equalsIgnoreCase(keyValues.get("type")) + && (constraints == null || constraints.isEmpty())) { + referenceStringBuilder.append(keySetString + "=MANY-true" + ","); + } + } else { + // User defined Datatype. + if ("true".equalsIgnoreCase(keyValues.get(MATCHABLEKEY))) { + matchableValues.put(keySetString, MATCHINGTRUE); + } + String value = keyValues.get("type"); + if (value != null && !value.isEmpty()) { + String trimValue = value.substring(value.lastIndexOf('.') + 1); + StringBuilder referenceIndividualStringBuilder = new StringBuilder(); + referenceIndividualStringBuilder.append(keySetString + "=" + trimValue + MANYFALSE + + DESCRIPTION_TOKEN + keyValues.get(DESCRIPTION_KEY)); + referenceStringBuilder.append(referenceIndividualStringBuilder + ","); + } else { + logger.info("keyValues.get(type) is null/empty"); + } + + } + if (constraints != null && !constraints.isEmpty()) { + // List handling. + listBuffer.append(keySetString.toUpperCase() + "=["); + for (String str : constraints) { + if (str.contains(DICTIONARY)) { + String[] dictionaryName = str.split(":"); + List dictFromDB = commonClassDao.getDataById(DictionaryData.class, DICTIONARYNAME, + dictionaryName[1]); + if (dictFromDB != null && !dictFromDB.isEmpty()) { + DictionaryData data = (DictionaryData) dictFromDB.get(0); + str = DICTIONARY + data.getDictionaryUrl() + "@" + data.getDictionaryDataByName(); + } + } + listBuffer.append(str + ","); + } + listBuffer.append("]#"); + logger.info(listBuffer); + + StringBuilder referenceIndividualStringBuilder = new StringBuilder(); + referenceIndividualStringBuilder.append(keySetString + "=" + keySetString.toUpperCase() + MANYFALSE); + referenceStringBuilder.append(referenceIndividualStringBuilder + ","); + constraints.clear(); + } + } + + dataListBuffer.append(listBuffer); + + logger.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); + logger.info("Whole attribute String is:" + attributeStringBuilder); + logger.info("Whole reference String is:" + referenceStringBuilder); + logger.info("List String is:" + listBuffer); + logger.info("Data list buffer is:" + dataListBuffer); + logger.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); + + this.listConstraints = dataListBuffer.toString(); + this.referenceAttributes = referenceStringBuilder.toString(); + this.attributeString = attributeStringBuilder.toString(); + } + + /** + * Find node. + * + * @param map the map + */ + @SuppressWarnings("unchecked") + private void findNode(LinkedHashMap map) { + + map.forEach((key, value) -> { + // if the value is properties and its type is map object, then save all the keys + if (key.equals(PROPERTIES_KEY) && value instanceof Map) { + saveNodes((LinkedHashMap) value); + if (isDuplicatedAttributes) { + orderedElements = new ArrayList<>(); + return; + } + } + + if (!"policy.nodes.Root".equals(key) && value instanceof Map) { + // value is a Map object, then make a recursive call + findNode((LinkedHashMap) value); + } + }); + + } + + /** + * Save nodes. + * + * @param map the map + */ + private void saveNodes(LinkedHashMap map) { + + for (Entry entry : map.entrySet()) { + + if (orderedElements.indexOf(entry.getKey()) >= 0) { // duplicated attribute names + isDuplicatedAttributes = true; + return; + } else { + orderedElements.add((String) entry.getKey()); + } + } + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PDPPolicyContainer.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PDPPolicyContainer.java deleted file mode 100644 index f5c4c3b38..000000000 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PDPPolicyContainer.java +++ /dev/null @@ -1,344 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.rest.util; - - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Set; - -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.xacml.api.XACMLErrorConstants; -import org.onap.policy.xacml.std.pap.StdPDPPolicy; - -import com.att.research.xacml.api.pap.PDP; -import com.att.research.xacml.api.pap.PDPGroup; -import com.att.research.xacml.api.pap.PDPPolicy; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements PolicyContainer.Indexed { - private static final long serialVersionUID = 1L; - private static final Logger LOGGER = FlexLogger.getLogger(PDPPolicyContainer.class); - - /** - * String identifier of a file's "Id" property. - */ - private static final String PROPERTY_ID = "Id"; - - /** - * String identifier of a file's "name" property. - */ - private static final String PROPERTY_NAME = "Name"; - - /** - * String identifier of a file's "name" property. - */ - private static final String PROPERTY_VERSION = "Version"; - - /** - * String identifier of a file's "Description" property. - */ - private static final String PROPERTY_DESCRIPTION = "Description"; - - /** - * String identifier of a file's "IsRoot" property. - */ - private static final String PROPERTY_ISROOT = "Root"; - - /** - * List of the string identifiers for the available properties. - */ - private static Collection pDPPolicyProperties; - - private final transient Object data; - private transient List policies; - - @SuppressWarnings("unchecked") - public PDPPolicyContainer(Object data) { - super(); - this.data = data; - if (this.data instanceof PDPGroup) { - policies = new ArrayList<> (((PDPGroup) this.data).getPolicies()); - } - if (this.data instanceof PDP) { - policies = new ArrayList<> (((PDP) this.data).getPolicies()); - } - if (this.data instanceof Set) { - policies = new ArrayList<> ((Set)data); - } - if (this.policies == null) { - LOGGER.info("NULL policies"); - throw new NullPointerException("PDPPolicyContainer created with unexpected Object type '" + data.getClass().getName() + "'"); - } - this.setContainer(this); - } - - @Override - public Object nextItemId(Object itemId) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("nextItemId: " + itemId); - } - int index = this.policies.indexOf(itemId); - if (index == -1 || ((index + 1) >= this.policies.size())) { - return null; - } - return new PDPPolicyItem(this.policies.get(index + 1)); - } - - @Override - public Object prevItemId(Object itemId) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("prevItemId: " + itemId); - } - int index = this.policies.indexOf(itemId); - if (index <= 0) { - return null; - } - return new PDPPolicyItem(this.policies.get(index - 1)); - } - - @Override - public Object firstItemId() { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("firstItemId: "); - } - if (this.policies.isEmpty()) { - return null; - } - return new PDPPolicyItem(this.policies.get(0)); - } - - @Override - public Object lastItemId() { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("lastItemid: "); - } - if (this.policies.isEmpty()) { - return null; - } - return new PDPPolicyItem(this.policies.get(this.policies.size() - 1)); - } - - @Override - public boolean isFirstId(Object itemId) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("isFirstId: " + itemId); - } - if (this.policies.isEmpty()) { - return false; - } - return itemId.equals(this.policies.get(0)); - } - - @Override - public boolean isLastId(Object itemId) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("isLastId: " + itemId); - } - if (this.policies.isEmpty()) { - return false; - } - return itemId.equals(this.policies.get(this.policies.size() - 1)); - } - - @Override - public Object addItemAfter(Object previousItemId) { - return null; - } - - @Override - public Collection getContainerPropertyIds() { - return pDPPolicyProperties; - } - - @Override - public Collection getItemIds() { - final Collection items = new ArrayList<>(); - items.addAll(this.policies); - return Collections.unmodifiableCollection(items); - } - - - @Override - public Class getType(Object propertyId) { - if (propertyId.equals(PROPERTY_ID)) { - return String.class; - } - if (propertyId.equals(PROPERTY_NAME)) { - return String.class; - } - if (propertyId.equals(PROPERTY_VERSION)) { - return String.class; - } - if (propertyId.equals(PROPERTY_DESCRIPTION)) { - return String.class; - } - if (propertyId.equals(PROPERTY_ISROOT)) { - return Boolean.class; - } - return null; - } - - @Override - public int size() { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("size: " + this.policies.size()); - } - return this.policies.size(); - } - - @Override - public boolean containsId(Object itemId) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("containsId: " + itemId); - } - return this.policies.contains(itemId); - } - - @Override - public Object addItem() { - throw new UnsupportedOperationException("Cannot add an empty policy."); - } - - @Override - public boolean removeItem(Object itemId) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("removeItem: " + itemId); - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - StdPDPPolicy pdpPolicy = null; - try { - pdpPolicy = mapper.readValue(itemId.toString() , StdPDPPolicy.class); - for(int i = 0; i< policies.size(); i++){ - if(policies.get(i).getId().equalsIgnoreCase(pdpPolicy.getId())){ - return this.policies.remove(this.policies.get(i)); - } - } - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Mapping the Removing Policy from PDP Group to Std Policy"+e); - } - return this.policies.remove(itemId); - } - - @Override - public boolean addContainerProperty(Object propertyId, Class type, - Object defaultValue) { - return false; - } - - @Override - public boolean removeContainerProperty(Object propertyId) { - return false; - } - - @Override - public boolean removeAllItems() { - return false; - } - - @Override - public int indexOfId(Object itemId) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("indexOfId: " + itemId); - } - return this.policies.indexOf(itemId); - } - - @Override - public Object getIdByIndex(int index) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("getIdByIndex: " + index); - } - return this.policies.get(index); - } - - @Override - public List getItemIds(int startIndex, int numberOfItems) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("getItemIds: " + startIndex + " " + numberOfItems); - } - if (numberOfItems < 0) { - throw new IllegalArgumentException(); - } - return this.policies.subList(startIndex, startIndex + numberOfItems); - } - - @Override - public Object addItemAt(int index) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("addItemAt: " + index); - } - return null; - } - - public class PDPPolicyItem { - private final PDPPolicy policy; - - public PDPPolicyItem(PDPPolicy itemId) { - this.policy = itemId; - } - - public String getId() { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("getId: " + this.policy); - } - return this.policy.getId(); - } - - public String getName() { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("getName: " + this.policy); - } - return this.policy.getName(); - } - - public String getVersion() { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("getVersion: " + this.policy); - } - return this.policy.getVersion(); - } - - public String getDescription() { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("getDescription: " + this.policy); - } - return this.policy.getDescription(); - } - - public boolean getRoot() { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("isRoot: " + this.policy); - } - return this.policy.isRoot(); - } - - public void setRoot(Boolean root) { - ((StdPDPPolicy)this.policy).setRoot(root); - } - - } -} \ No newline at end of file diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/ParserException.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/ParserException.java index f509abdbb..5e034d29b 100644 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/util/ParserException.java +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/ParserException.java @@ -3,6 +3,7 @@ * ONAP-REST * ================================================================================ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,19 +18,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.rest.util; -public class ParserException extends Exception { +public class ParserException extends Exception { private static final long serialVersionUID = -1166704711958410424L; - final String message; - - ParserException(String message) { - this.message = message; - } - - @Override - public String getMessage() { - return message; + public ParserException(String message) { + super(message); } } \ No newline at end of file diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PdpPolicyContainer.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PdpPolicyContainer.java new file mode 100644 index 000000000..d6bd3f831 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PdpPolicyContainer.java @@ -0,0 +1,487 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.rest.util; + +import com.att.research.xacml.api.pap.PDP; +import com.att.research.xacml.api.pap.PDPGroup; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPDPPolicy; + +public class PdpPolicyContainer extends PolicyItemSetChangeNotifier implements PolicyContainer.Indexed { + private static final long serialVersionUID = 1L; + private static final Logger LOGGER = FlexLogger.getLogger(PdpPolicyContainer.class); + + private static final String PROPERTY_ID = "Id"; + private static final String PROPERTY_NAME = "Name"; + private static final String PROPERTY_VERSION = "Version"; + private static final String PROPERTY_DESCRIPTION = "Description"; + private static final String PROPERTY_ISROOT = "Root"; + + /** + * List of the string identifiers for the available properties. + */ + private static Collection pDPPolicyProperties; + + private final transient Object data; + private transient List policies; + + /** + * Instantiates a new pdp policy container. + * + * @param data the data + */ + @SuppressWarnings("unchecked") + public PdpPolicyContainer(Object data) { + super(); + this.data = data; + if (this.data instanceof PDPGroup) { + policies = new ArrayList<>(((PDPGroup) this.data).getPolicies()); + } + if (this.data instanceof PDP) { + policies = new ArrayList<>(((PDP) this.data).getPolicies()); + } + if (this.data instanceof Set) { + policies = new ArrayList<>((Set) data); + } + if (this.policies == null) { + LOGGER.info("NULL policies"); + throw new NullPointerException("PDPPolicyContainer created with unexpected Object type '" + + data.getClass().getName() + "'"); + } + this.setContainer(this); + } + + /** + * Next item id. + * + * @param itemId the item id + * @return the object + */ + @Override + public Object nextItemId(Object itemId) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("nextItemId: " + itemId); + } + int index = this.policies.indexOf(itemId); + if (index == -1 || ((index + 1) >= this.policies.size())) { + return null; + } + return new PdpPolicyItem(this.policies.get(index + 1)); + } + + /** + * Prev item id. + * + * @param itemId the item id + * @return the object + */ + @Override + public Object prevItemId(Object itemId) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("prevItemId: " + itemId); + } + int index = this.policies.indexOf(itemId); + if (index <= 0) { + return null; + } + return new PdpPolicyItem(this.policies.get(index - 1)); + } + + /** + * First item id. + * + * @return the object + */ + @Override + public Object firstItemId() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("firstItemId: "); + } + if (this.policies.isEmpty()) { + return null; + } + return new PdpPolicyItem(this.policies.get(0)); + } + + /** + * Last item id. + * + * @return the object + */ + @Override + public Object lastItemId() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("lastItemid: "); + } + if (this.policies.isEmpty()) { + return null; + } + return new PdpPolicyItem(this.policies.get(this.policies.size() - 1)); + } + + /** + * Checks if is first id. + * + * @param itemId the item id + * @return true, if is first id + */ + @Override + public boolean isFirstId(Object itemId) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("isFirstId: " + itemId); + } + if (this.policies.isEmpty()) { + return false; + } + return itemId.equals(this.policies.get(0)); + } + + /** + * Checks if is last id. + * + * @param itemId the item id + * @return true, if is last id + */ + @Override + public boolean isLastId(Object itemId) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("isLastId: " + itemId); + } + if (this.policies.isEmpty()) { + return false; + } + return itemId.equals(this.policies.get(this.policies.size() - 1)); + } + + /** + * Adds the item after. + * + * @param previousItemId the previous item id + * @return the object + */ + @Override + public Object addItemAfter(Object previousItemId) { + return null; + } + + /** + * Gets the container property ids. + * + * @return the container property ids + */ + @Override + public Collection getContainerPropertyIds() { + return pDPPolicyProperties; + } + + /** + * Gets the item ids. + * + * @return the item ids + */ + @Override + public Collection getItemIds() { + final Collection items = new ArrayList<>(); + items.addAll(this.policies); + return Collections.unmodifiableCollection(items); + } + + /** + * Gets the item ids. + * + * @param startIndex the start index + * @param numberOfItems the number of items + * @return the item ids + */ + @Override + public List getItemIds(int startIndex, int numberOfItems) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getItemIds: " + startIndex + " " + numberOfItems); + } + if (numberOfItems < 0) { + throw new IllegalArgumentException(); + } + return this.policies.subList(startIndex, startIndex + numberOfItems); + } + + /** + * Gets the type. + * + * @param propertyId the property id + * @return the type + */ + @Override + public Class getType(Object propertyId) { + if (propertyId.equals(PROPERTY_ID)) { + return String.class; + } + if (propertyId.equals(PROPERTY_NAME)) { + return String.class; + } + if (propertyId.equals(PROPERTY_VERSION)) { + return String.class; + } + if (propertyId.equals(PROPERTY_DESCRIPTION)) { + return String.class; + } + if (propertyId.equals(PROPERTY_ISROOT)) { + return Boolean.class; + } + return null; + } + + /** + * Size. + * + * @return the int + */ + @Override + public int size() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("size: " + this.policies.size()); + } + return this.policies.size(); + } + + /** + * Contains id. + * + * @param itemId the item id + * @return true, if successful + */ + @Override + public boolean containsId(Object itemId) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("containsId: " + itemId); + } + return this.policies.contains(itemId); + } + + /** + * Adds the item. + * + * @return the object + */ + @Override + public Object addItem() { + throw new UnsupportedOperationException("Cannot add an empty policy."); + } + + /** + * Removes the item. + * + * @param itemId the item id + * @return true, if successful + */ + @Override + public boolean removeItem(Object itemId) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("removeItem: " + itemId); + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + StdPDPPolicy pdpPolicy = null; + try { + pdpPolicy = mapper.readValue(itemId.toString(), StdPDPPolicy.class); + for (int i = 0; i < policies.size(); i++) { + if (policies.get(i).getId().equalsIgnoreCase(pdpPolicy.getId())) { + return this.policies.remove(this.policies.get(i)); + } + } + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + + "Exception Occured While Mapping the Removing Policy from PDP Group to Std Policy" + e); + } + return this.policies.remove(itemId); + } + + /** + * Adds the container property. + * + * @param propertyId the property id + * @param type the type + * @param defaultValue the default value + * @return true, if successful + */ + @Override + public boolean addContainerProperty(Object propertyId, Class type, Object defaultValue) { + return false; + } + + /** + * Removes the container property. + * + * @param propertyId the property id + * @return true, if successful + */ + @Override + public boolean removeContainerProperty(Object propertyId) { + return false; + } + + /** + * Removes the all items. + * + * @return true, if successful + */ + @Override + public boolean removeAllItems() { + return false; + } + + /** + * Index of id. + * + * @param itemId the item id + * @return the int + */ + @Override + public int indexOfId(Object itemId) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("indexOfId: " + itemId); + } + return this.policies.indexOf(itemId); + } + + /** + * Gets the id by index. + * + * @param index the index + * @return the id by index + */ + @Override + public Object getIdByIndex(int index) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getIdByIndex: " + index); + } + return this.policies.get(index); + } + + /** + * Adds the item at. + * + * @param index the index + * @return the object + */ + @Override + public Object addItemAt(int index) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("addItemAt: " + index); + } + return null; + } + + public class PdpPolicyItem { + private final PDPPolicy policy; + + /** + * Instantiates a new PDP policy item. + * + * @param itemId the item id + */ + public PdpPolicyItem(PDPPolicy itemId) { + this.policy = itemId; + } + + /** + * Gets the id. + * + * @return the id + */ + public String getId() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getId: " + this.policy); + } + return this.policy.getId(); + } + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getName: " + this.policy); + } + return this.policy.getName(); + } + + /** + * Gets the version. + * + * @return the version + */ + public String getVersion() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getVersion: " + this.policy); + } + return this.policy.getVersion(); + } + + /** + * Gets the description. + * + * @return the description + */ + public String getDescription() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getDescription: " + this.policy); + } + return this.policy.getDescription(); + } + + /** + * Gets the root. + * + * @return the root + */ + public boolean getRoot() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("isRoot: " + this.policy); + } + return this.policy.isRoot(); + } + + /** + * Sets the root. + * + * @param root the new root + */ + public void setRoot(Boolean root) { + ((StdPDPPolicy) this.policy).setRoot(root); + } + + } +} \ No newline at end of file diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyContainer.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyContainer.java index 80bb16d54..42bee49b5 100644 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyContainer.java +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyContainer.java @@ -3,13 +3,14 @@ * ONAP Policy Engine * ================================================================================ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,26 +25,24 @@ import java.io.Serializable; import java.util.Collection; import java.util.List; - -public interface PolicyContainer extends Serializable{ +public interface PolicyContainer extends Serializable { public Collection getContainerPropertyIds(); - + public Collection getItemIds(); public Class getType(Object propertyId); public int size(); - + public boolean containsId(Object itemId); public Object addItem(); - + public boolean removeItem(Object itemId); - public boolean addContainerProperty(Object propertyId, Class type, - Object defaultValue); - + public boolean addContainerProperty(Object propertyId, Class type, Object defaultValue); + public boolean removeContainerProperty(Object propertyId); public boolean removeAllItems(); @@ -63,10 +62,9 @@ public interface PolicyContainer extends Serializable{ public boolean isLastId(Object itemId); public Object addItemAfter(Object previousItemId); - + } - public interface Indexed extends Ordered { public int indexOfId(Object itemId); @@ -74,7 +72,7 @@ public interface PolicyContainer extends Serializable{ public Object getIdByIndex(int index); public List getItemIds(int startIndex, int numberOfItems); - + public Object addItemAt(int index); public interface ItemAddEvent extends ItemSetChangeEvent { @@ -86,9 +84,8 @@ public interface PolicyContainer extends Serializable{ public int getAddedItemsCount(); } - public interface ItemRemoveEvent extends ItemSetChangeEvent { - + public Object getFirstItemId(); public int getFirstIndex(); @@ -96,23 +93,21 @@ public interface PolicyContainer extends Serializable{ public int getRemovedItemsCount(); } } - - public interface ItemSetChangeEvent extends Serializable { + @FunctionalInterface + public interface ItemSetChangeEvent { public PolicyContainer getContainer(); } - public interface ItemSetChangeListener extends Serializable { - + @FunctionalInterface + public interface ItemSetChangeListener { public void containerItemSetChange(PolicyContainer.ItemSetChangeEvent event); } public interface ItemSetChangeNotifier extends Serializable { - public void addItemSetChangeListener( - PolicyContainer.ItemSetChangeListener listener); + public void addItemSetChangeListener(PolicyContainer.ItemSetChangeListener listener); - public void removeItemSetChangeListener( - PolicyContainer.ItemSetChangeListener listener); + public void removeItemSetChangeListener(PolicyContainer.ItemSetChangeListener listener); } } diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyItemSetChangeNotifier.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyItemSetChangeNotifier.java index 16e467041..d70830118 100644 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyItemSetChangeNotifier.java +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyItemSetChangeNotifier.java @@ -3,13 +3,14 @@ * ONAP Policy Engine * ================================================================================ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,7 +21,6 @@ package org.onap.policy.rest.util; - import java.io.Serializable; import java.util.Collection; import java.util.EventObject; @@ -29,19 +29,18 @@ import java.util.LinkedList; import org.onap.policy.rest.util.PolicyContainer.ItemSetChangeEvent; import org.onap.policy.rest.util.PolicyContainer.ItemSetChangeListener; - - public class PolicyItemSetChangeNotifier implements PolicyContainer.ItemSetChangeNotifier { private static final long serialVersionUID = 1L; + private Collection itemSetChangeListeners = null; private PolicyContainer container = null; - + public PolicyItemSetChangeNotifier() { // Empty constructor } - - protected void setContainer(PolicyContainer c) { - this.container = c; + + protected void setContainer(PolicyContainer container) { + this.container = container; } @Override @@ -49,7 +48,8 @@ public class PolicyItemSetChangeNotifier implements PolicyContainer.ItemSetChang if (getItemSetChangeListeners() == null) { setItemSetChangeListeners(new LinkedList()); } - getItemSetChangeListeners().add(listener); } + getItemSetChangeListeners().add(listener); + } @Override public void removeItemSetChangeListener(ItemSetChangeListener listener) { @@ -58,8 +58,8 @@ public class PolicyItemSetChangeNotifier implements PolicyContainer.ItemSetChang } } - protected static class BaseItemSetChangeEvent extends EventObject implements - PolicyContainer.ItemSetChangeEvent, Serializable { + protected static class BaseItemSetChangeEvent extends EventObject + implements PolicyContainer.ItemSetChangeEvent, Serializable { private static final long serialVersionUID = 1L; protected BaseItemSetChangeEvent(PolicyContainer source) { @@ -72,14 +72,14 @@ public class PolicyItemSetChangeNotifier implements PolicyContainer.ItemSetChang } } - protected void setItemSetChangeListeners( - Collection itemSetChangeListeners) { + protected void setItemSetChangeListeners(Collection itemSetChangeListeners) { this.itemSetChangeListeners = itemSetChangeListeners; } + protected Collection getItemSetChangeListeners() { return itemSetChangeListeners; } - + protected void fireItemSetChange() { fireItemSetChange(new BaseItemSetChangeEvent(this.container)); } @@ -88,8 +88,7 @@ public class PolicyItemSetChangeNotifier implements PolicyContainer.ItemSetChang if (getItemSetChangeListeners() != null) { final Object[] l = getItemSetChangeListeners().toArray(); for (int i = 0; i < l.length; i++) { - ((PolicyContainer.ItemSetChangeListener) l[i]) - .containerItemSetChange(event); + ((PolicyContainer.ItemSetChangeListener) l[i]).containerItemSetChange(event); } } } diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidation.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidation.java index da54b05bd..6bab919ad 100644 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidation.java +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidation.java @@ -3,13 +3,14 @@ * ONAP Policy Engine * ================================================================================ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -26,9 +27,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Splitter; import com.google.common.base.Strings; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; - import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringReader; @@ -42,12 +40,16 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; + import javax.json.Json; import javax.json.JsonException; import javax.json.JsonObject; import javax.json.JsonReader; import javax.json.JsonValue; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; + import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.json.JSONArray; @@ -67,42 +69,55 @@ import org.onap.policy.xacml.util.XACMLPolicyScanner; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; - @Service public class PolicyValidation { - private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidation.class); - public static final String CONFIG_POLICY = "Config"; - public static final String ACTION_POLICY = "Action"; - public static final String DECISION_POLICY = "Decision"; - public static final String DECISION_POLICY_MS = "Decision_MS"; - public static final String CLOSEDLOOP_POLICY = "ClosedLoop_Fault"; - public static final String CLOSEDLOOP_PM = "ClosedLoop_PM"; - public static final String ENFORCER_CONFIG_POLICY = "Enforcer Config"; - public static final String MICROSERVICES = "Micro Service"; - public static final String FIREWALL = "Firewall Config"; - public static final String OPTIMIZATION="Optimization"; - public static final String BRMSPARAM = "BRMS_Param"; - public static final String BRMSRAW = "BRMS_Raw"; - public static final String HTML_ITALICS_LNBREAK = "
"; - public static final String SUCCESS = "success"; - public static final String EMPTY_COMPONENT_ATTR = - "Component Attributes: One or more Fields in Component Attributes is Empty."; - public static final String ISREQUIRED = " is required"; - public static final String SPACESINVALIDCHARS = " : value has spaces or invalid characters
"; - private static final String REQUIRED_ATTRIBUTE = "required-true"; + private static final String ACTION_POLICY = "Action"; + private static final String BOOLEAN = "boolean"; + private static final String BRMSPARAM = "BRMS_Param"; + private static final String BRMSRAW = "BRMS_Raw"; + private static final String CLOSEDLOOP_PM = "ClosedLoop_PM"; + private static final String CLOSEDLOOP_POLICY = "ClosedLoop_Fault"; + private static final String CONFIG_POLICY = "Config"; private static final String DECISION_MS_MODEL = "MicroService_Model"; + private static final String DECISION_POLICY = "Decision"; + private static final String DECISION_POLICY_MS = "Decision_MS"; + private static final String ENFORCER_CONFIG_POLICY = "Enforcer Config"; + private static final String FIREWALL = "Firewall Config"; + private static final String HTML_ITALICS_LNBREAK = "
"; + private static final String INTEGER = "integer"; + private static final String ISREQUIRED = " is required"; + private static final String JAVA = "java"; + private static final String LIST = "list"; + private static final String MAP = "map"; + private static final String MICROSERVICES = "Micro Service"; + private static final String MISSING_COMPONENT_ATTRIBUTE_VALUE = "Component Attributes:" + + " has one missing Component Attribute value
"; + private static final String MISSING_ATTRIBUTE_VALUE = "Rule Attributes:" + + " has one missing Attribute value
"; + private static final String MISSING_COMPONENT_ATTRIBUTE_KEY = "Component Attributes:" + + " has one missing Component Attribute key
"; + private static final String OPTIMIZATION = "Optimization"; private static final String RAW = "Raw"; + private static final String REQUIRED_ATTRIBUTE = "required-true"; + private static final String RULE_ALGORITHMS = "Rule Algorithms:"; + private static final String SELECT_AT_LEAST_ONE_D2_VIRTUALIZED_SERVICES = "D2/Virtualized Services: " + + "Select at least one D2/Virtualized Services"; + private static final String SPACESINVALIDCHARS = " : value has spaces or invalid characters
"; + private static final String STRING = "string"; + private static final String SUCCESS = "success"; + private static final String VALUE = "value"; private static Map mapAttribute = new HashMap<>(); private static Map jsonRequestMap = new HashMap<>(); private static List modelRequiredFieldsList = new ArrayList<>(); - private Set allReqTrueKeys = new HashSet<>(); - private Set allOptReqTrueKeys = new HashSet<>(); private static CommonClassDao commonClassDao; + private Set allReqTrueKeys = new HashSet<>(); + private Set allOptReqTrueKeys = new HashSet<>(); + @Autowired public PolicyValidation(CommonClassDao commonClassDao) { PolicyValidation.commonClassDao = commonClassDao; @@ -115,7 +130,6 @@ public class PolicyValidation { // Empty constructor } - /** * Validate policy. * @@ -148,68 +162,64 @@ public class PolicyValidation { } if (!"API".equals(policyData.getApiflag()) && policyData.getAttributes() != null - && !policyData.getAttributes().isEmpty()) { + && !policyData.getAttributes().isEmpty()) { for (Object attribute : policyData.getAttributes()) { if (attribute instanceof LinkedHashMap) { - String value = null; + String attValue = null; String key = null; if (((LinkedHashMap) attribute).get("key") != null) { key = ((LinkedHashMap) attribute).get("key").toString(); if (!PolicyUtils.policySpecialCharWithDashValidator(key).contains(SUCCESS)) { - responseString.append("Attributes or Component Attributes:" + value - + SPACESINVALIDCHARS); + responseString.append("Attributes or Component Attributes:" + attValue + + SPACESINVALIDCHARS); valid = false; } } else { if (CONFIG_POLICY.equals(policyData.getPolicyType())) { if ("Base".equals(policyData.getConfigPolicyType())) { - responseString - .append("Attributes: has one missing Attribute key
"); + responseString.append( + "Attributes: has one missing Attribute key
"); } if (BRMSPARAM.equals(policyData.getConfigPolicyType()) - || BRMSRAW.equals(policyData.getConfigPolicyType())) { - responseString - .append("Rule Attributes: has one missing Attribute key
"); + || BRMSRAW.equals(policyData.getConfigPolicyType())) { + responseString.append( + "Rule Attributes: has one missing Attribute key
"); } } else { - responseString.append( - "Component Attributes: has one missing Component Attribute key
"); + responseString.append(MISSING_COMPONENT_ATTRIBUTE_KEY); } valid = false; } - if (((LinkedHashMap) attribute).get("value") != null) { - value = ((LinkedHashMap) attribute).get("value").toString(); - if (!PolicyUtils.policySpecialCharWithDashValidator(value).contains(SUCCESS)) { + if (((LinkedHashMap) attribute).get(VALUE) != null) { + attValue = ((LinkedHashMap) attribute).get(VALUE).toString(); + if (!PolicyUtils.policySpecialCharWithDashValidator(attValue).contains(SUCCESS)) { if (CONFIG_POLICY.equals(policyData.getPolicyType())) { if ("Base".equals(policyData.getConfigPolicyType())) { - responseString.append("Attributes:" + value - + SPACESINVALIDCHARS); + responseString.append("Attributes:" + attValue + SPACESINVALIDCHARS); } if (BRMSPARAM.equals(policyData.getConfigPolicyType()) - || BRMSRAW.equals(policyData.getConfigPolicyType())) { - responseString.append("Rule Attributes:" + value - + SPACESINVALIDCHARS); + || BRMSRAW.equals(policyData.getConfigPolicyType())) { + responseString.append( + "Rule Attributes:" + attValue + SPACESINVALIDCHARS); } } else { - responseString.append("Component Attributes:" + value - + SPACESINVALIDCHARS); + responseString.append( + "Component Attributes:" + attValue + SPACESINVALIDCHARS); } valid = false; } } else { if (CONFIG_POLICY.equals(policyData.getPolicyType())) { if ("Base".equals(policyData.getConfigPolicyType())) { - responseString - .append("Attributes: has one missing Attribute value
"); + responseString.append( + "Attributes: has one missing Attribute value
"); } if (BRMSPARAM.equals(policyData.getConfigPolicyType()) - || BRMSRAW.equals(policyData.getConfigPolicyType())) { - responseString.append( - "Rule Attributes: has one missing Attribute value
"); + || BRMSRAW.equals(policyData.getConfigPolicyType())) { + responseString.append(MISSING_ATTRIBUTE_VALUE); } } else { - responseString.append( - "Component Attributes: has one missing Component Attribute value
"); + responseString.append(MISSING_COMPONENT_ATTRIBUTE_VALUE); } valid = false; } @@ -219,25 +229,24 @@ public class PolicyValidation { // Decision Policy Attributes Validation if (!"API".equals(policyData.getApiflag()) && policyData.getSettings() != null - && !policyData.getSettings().isEmpty()) { + && !policyData.getSettings().isEmpty()) { for (Object attribute : policyData.getAttributes()) { if (attribute instanceof LinkedHashMap) { String value = null; if (((LinkedHashMap) attribute).get("key") == null) { - responseString - .append("Settings Attributes: has one missing Attribute key
"); + responseString.append( + "Settings Attributes: has one missing Attribute key
"); valid = false; } - if (((LinkedHashMap) attribute).get("value") != null) { - value = ((LinkedHashMap) attribute).get("value").toString(); + if (((LinkedHashMap) attribute).get(VALUE) != null) { + value = ((LinkedHashMap) attribute).get(VALUE).toString(); if (!PolicyUtils.policySpecialCharValidator(value).contains(SUCCESS)) { - responseString.append("Settings Attributes:" + value - + SPACESINVALIDCHARS); + responseString.append("Settings Attributes:" + value + SPACESINVALIDCHARS); valid = false; } } else { - responseString - .append("Settings Attributes: has one missing Attribute Value
"); + responseString.append( + "Settings Attributes: has one missing Attribute Value
"); valid = false; } } @@ -245,31 +254,28 @@ public class PolicyValidation { } if (!"API".equals(policyData.getApiflag()) && policyData.getRuleAlgorithmschoices() != null - && !policyData.getRuleAlgorithmschoices().isEmpty()) { + && !policyData.getRuleAlgorithmschoices().isEmpty()) { for (Object attribute : policyData.getRuleAlgorithmschoices()) { if (attribute instanceof LinkedHashMap) { String label = ((LinkedHashMap) attribute).get("id").toString(); if (((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField1") == null) { - responseString.append( - "Rule Algorithms:" + label + " : Field 1 value is not selected
"); + responseString.append(RULE_ALGORITHMS + label + " : Field 1 value is not selected

"); valid = false; } if (((LinkedHashMap) attribute).get("dynamicRuleAlgorithmCombo") == null) { - responseString.append( - "Rule Algorithms:" + label + " : Field 2 value is not selected
"); + responseString.append(RULE_ALGORITHMS + label + " : Field 2 value is not selected

"); valid = false; } if (((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField2") != null) { - String value = - ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField2").toString(); + String value = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField2") + .toString(); if (!PolicyUtils.policySpecialCharValidator(value).contains(SUCCESS)) { - responseString.append("Rule Algorithms:" + label - + " : Field 3 value has special characters
"); + responseString.append(RULE_ALGORITHMS + label + + " : Field 3 value has special characters

"); valid = false; } } else { - responseString - .append("Rule Algorithms:" + label + " : Field 3 value is empty
"); + responseString.append(RULE_ALGORITHMS + label + " : Field 3 value is empty

"); valid = false; } } @@ -278,14 +284,15 @@ public class PolicyValidation { if (CONFIG_POLICY.equalsIgnoreCase(policyData.getPolicyType())) { if ("Base".equals(policyData.getConfigPolicyType()) - || CLOSEDLOOP_POLICY.equals(policyData.getConfigPolicyType()) - || CLOSEDLOOP_PM.equals(policyData.getConfigPolicyType()) - || ENFORCER_CONFIG_POLICY.equals(policyData.getConfigPolicyType()) - || MICROSERVICES.equals(policyData.getConfigPolicyType()) - || OPTIMIZATION.equals(policyData.getConfigPolicyType())) { + || CLOSEDLOOP_POLICY.equals(policyData.getConfigPolicyType()) + || CLOSEDLOOP_PM.equals(policyData.getConfigPolicyType()) + || ENFORCER_CONFIG_POLICY.equals(policyData.getConfigPolicyType()) + || MICROSERVICES.equals(policyData.getConfigPolicyType()) + || OPTIMIZATION.equals(policyData.getConfigPolicyType())) { if (!Strings.isNullOrEmpty(policyData.getOnapName())) { - String onapNameValidate = PolicyUtils.policySpecialCharWithDashValidator(policyData.getOnapName()); + String onapNameValidate = PolicyUtils + .policySpecialCharWithDashValidator(policyData.getOnapName()); if (!onapNameValidate.contains(SUCCESS)) { responseString.append("OnapName:" + onapNameValidate + HTML_ITALICS_LNBREAK); valid = false; @@ -357,25 +364,25 @@ public class PolicyValidation { if (configType != null) { if ("JSON".equals(configType)) { if (!PolicyUtils.isJSONValid(configBodyData)) { - responseString - .append("Config Body: JSON Content is not valid" + HTML_ITALICS_LNBREAK); + responseString.append( + "Config Body: JSON Content is not valid" + HTML_ITALICS_LNBREAK); valid = false; } } else if ("XML".equals(configType)) { if (!PolicyUtils.isXMLValid(configBodyData)) { - responseString.append( - "Config Body: XML Content data is not valid" + HTML_ITALICS_LNBREAK); + responseString.append("Config Body: XML Content data is not valid" + + HTML_ITALICS_LNBREAK); valid = false; } } else if ("PROPERTIES".equals(configType)) { if (!PolicyUtils.isPropValid(configBodyData) || "".equals(configBodyData)) { - responseString - .append("Config Body: Property data is not valid" + HTML_ITALICS_LNBREAK); + responseString.append( + "Config Body: Property data is not valid" + HTML_ITALICS_LNBREAK); valid = false; } } else if ("OTHER".equals(configType) && ("".equals(configBodyData))) { - responseString - .append("Config Body: Config Body Should not be Empty" + HTML_ITALICS_LNBREAK); + responseString.append( + "Config Body: Config Body Should not be Empty" + HTML_ITALICS_LNBREAK); valid = false; } } @@ -397,14 +404,14 @@ public class PolicyValidation { valid = false; } if (policyData.getSecurityZone() == null || policyData.getSecurityZone().isEmpty()) { - responseString - .append("Security Zone: Security Zone is required" + HTML_ITALICS_LNBREAK); + responseString.append( + "Security Zone: Security Zone is required" + HTML_ITALICS_LNBREAK); valid = false; } } // Validate BRMS_Param Policy Data if (BRMSPARAM.equalsIgnoreCase(policyData.getConfigPolicyType()) - && Strings.isNullOrEmpty(policyData.getRuleName())) { + && Strings.isNullOrEmpty(policyData.getRuleName())) { responseString.append("BRMS Template:BRMS Template is required" + HTML_ITALICS_LNBREAK); valid = false; } @@ -415,8 +422,8 @@ public class PolicyValidation { // If there are any error other than Annotations then this is not Valid if (message.contains("[ERR")) { - responseString.append( - "Raw Rule Validate:Raw Rule has error" + message + HTML_ITALICS_LNBREAK); + responseString.append("Raw Rule Validate:Raw Rule has error" + message + + HTML_ITALICS_LNBREAK); valid = false; } } else { @@ -427,17 +434,17 @@ public class PolicyValidation { // Validate ClosedLoop_PM Policy Data if (CLOSEDLOOP_PM.equalsIgnoreCase(policyData.getConfigPolicyType())) { try { - if (Strings.isNullOrEmpty( - policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString())) { + if (Strings.isNullOrEmpty(policyData.getServiceTypePolicyName().get("serviceTypePolicyName") + .toString())) { responseString.append("ServiceType PolicyName:ServiceType PolicyName is required" - + HTML_ITALICS_LNBREAK); + + HTML_ITALICS_LNBREAK); valid = false; } } catch (Exception e) { LOGGER.error("ERROR in ClosedLoop_PM PolicyName", e); responseString.append("ServiceType PolicyName:ServiceType PolicyName is required" - + HTML_ITALICS_LNBREAK); + + HTML_ITALICS_LNBREAK); valid = false; } @@ -451,11 +458,9 @@ public class PolicyValidation { valid = false; } } - if ((pmBody.isGamma() || pmBody.isMcr() || pmBody.isTrinity() || pmBody.isvDNS() - || pmBody.isvUSP()) != true) { - responseString - .append("D2/Virtualized Services: Select at least one D2/Virtualized Services" - + HTML_ITALICS_LNBREAK); + if (!pmBody.isGamma() && !pmBody.isMcr() && !pmBody.isTrinity() && !pmBody.isvDNS() + && !pmBody.isvUSP()) { + responseString.append(SELECT_AT_LEAST_ONE_D2_VIRTUALIZED_SERVICES + HTML_ITALICS_LNBREAK); valid = false; } if (pmBody.getGeoLink() != null && !pmBody.getGeoLink().isEmpty()) { @@ -473,16 +478,17 @@ public class PolicyValidation { String attributeValidate = PolicyUtils.policySpecialCharValidator(value); if (!attributeValidate.contains(SUCCESS)) { responseString.append("Attributes:" + key - + " : value has spaces or invalid characters" + HTML_ITALICS_LNBREAK); + + " : value has spaces or invalid characters" + + HTML_ITALICS_LNBREAK); valid = false; } } } } } else { - responseString - .append("D2/Virtualized Services:Select atleast one D2/Virtualized Services" - + HTML_ITALICS_LNBREAK); + responseString.append( + "D2/Virtualized Services:Select atleast one D2/Virtualized Services" + + HTML_ITALICS_LNBREAK); valid = false; } } @@ -497,38 +503,40 @@ public class PolicyValidation { String apiCondition = (String) json.get("conditions"); if (Strings.isNullOrEmpty(apiCondition)) { responseString.append("Conditions: Select At least one Condition" - + HTML_ITALICS_LNBREAK); + + HTML_ITALICS_LNBREAK); return responseString; } } else { - responseString - .append("Conditions: There were no conditions provided in configBody json" - + HTML_ITALICS_LNBREAK); + responseString.append("Conditions:" + + " There were no conditions provided in configBody json" + + HTML_ITALICS_LNBREAK); return responseString; } } else { if (policyData.getTrapDatas().getTrap1() != null) { if (policyData.getClearTimeOut() == null) { - responseString.append( - "Trigger Clear TimeOut: Trigger Clear TimeOut is required when atleast One Trigger Signature is enabled
"); + responseString.append("Trigger Clear TimeOut: " + + "Trigger Clear TimeOut is required when at " + + "least One Trigger Signature is enabled
"); valid = false; } if (policyData.getTrapMaxAge() == null) { - responseString.append( - "Trap Max Age: Trap Max Age is required when atleast One Trigger Signature is enabled
"); + responseString.append("Trap Max Age: Trap Max Age is required when at " + + "least One Trigger Signature is enabled
"); valid = false; } } if (policyData.getFaultDatas().getTrap1() != null - && policyData.getVerificationclearTimeOut() == null) { + && policyData.getVerificationclearTimeOut() == null) { responseString.append( - "Fault Clear TimeOut: Fault Clear TimeOut is required when atleast One Fault Signature is enabled
"); + "Fault Clear TimeOut: Fault Clear TimeOut is required when at" + + "least One Fault Signature is enabled
"); valid = false; } } - ClosedLoopFaultBody faultBody = - mapper.readValue(policyData.getJsonBody(), ClosedLoopFaultBody.class); + ClosedLoopFaultBody faultBody = mapper.readValue(policyData.getJsonBody(), + ClosedLoopFaultBody.class); if (faultBody.getEmailAddress() != null && !faultBody.getEmailAddress().isEmpty()) { String result = emailValidation(faultBody.getEmailAddress(), responseString.toString()); if (!SUCCESS.equals(result)) { @@ -537,26 +545,24 @@ public class PolicyValidation { } } if (!(faultBody.isGamma() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS() - || faultBody.isvUSP())) { - responseString - .append("D2/Virtualized Services: Select at least one D2/Virtualized Services" - + HTML_ITALICS_LNBREAK); + || faultBody.isvUSP())) { + responseString.append(SELECT_AT_LEAST_ONE_D2_VIRTUALIZED_SERVICES + HTML_ITALICS_LNBREAK); valid = false; } if (faultBody.getActions() == null || faultBody.getActions().isEmpty()) { - responseString - .append("vPRO Actions: vPRO Actions is required" + HTML_ITALICS_LNBREAK); + responseString.append( + "vPRO Actions: vPRO Actions is required" + HTML_ITALICS_LNBREAK); valid = false; } if (faultBody.getClosedLoopPolicyStatus() == null - || faultBody.getClosedLoopPolicyStatus().isEmpty()) { - responseString.append( - "Policy Status: Policy Status is required" + HTML_ITALICS_LNBREAK); + || faultBody.getClosedLoopPolicyStatus().isEmpty()) { + responseString.append("Policy Status: Policy Status is required" + + HTML_ITALICS_LNBREAK); valid = false; } if (faultBody.getConditions() == null) { - responseString.append( - "Conditions: Select At least one Condition" + HTML_ITALICS_LNBREAK); + responseString.append("Conditions: Select At least one Condition" + + HTML_ITALICS_LNBREAK); valid = false; } if (faultBody.getGeoLink() != null && !faultBody.getGeoLink().isEmpty()) { @@ -567,28 +573,28 @@ public class PolicyValidation { } } if (faultBody.getAgingWindow() == 0) { - responseString - .append("Aging Window: Aging Window is required" + HTML_ITALICS_LNBREAK); + responseString.append( + "Aging Window: Aging Window is required" + HTML_ITALICS_LNBREAK); valid = false; } if (faultBody.getTimeInterval() == 0) { - responseString.append( - "Time Interval: Time Interval is required" + HTML_ITALICS_LNBREAK); + responseString.append("Time Interval: Time Interval is required" + + HTML_ITALICS_LNBREAK); valid = false; } if (faultBody.getRetrys() == 0) { responseString.append("Number of Retries: Number of Retries is required" - + HTML_ITALICS_LNBREAK); + + HTML_ITALICS_LNBREAK); valid = false; } if (faultBody.getTimeOutvPRO() == 0) { - responseString.append( - "APP-C Timeout: APP-C Timeout is required" + HTML_ITALICS_LNBREAK); + responseString.append("APP-C Timeout: APP-C Timeout is required" + + HTML_ITALICS_LNBREAK); valid = false; } if (faultBody.getTimeOutRuby() == 0) { - responseString - .append("TimeOutRuby: TimeOutRuby is required" + HTML_ITALICS_LNBREAK); + responseString.append( + "TimeOutRuby: TimeOutRuby is required" + HTML_ITALICS_LNBREAK); valid = false; } if (faultBody.getVnfType() == null || faultBody.getVnfType().isEmpty()) { @@ -596,31 +602,31 @@ public class PolicyValidation { valid = false; } } else { - responseString - .append("D2/Virtualized Services: Select atleast one D2/Virtualized Services" - + HTML_ITALICS_LNBREAK); - responseString - .append("vPRO Actions: vPRO Actions is required" + HTML_ITALICS_LNBREAK); - responseString - .append("Aging Window: Aging Window is required" + HTML_ITALICS_LNBREAK); - responseString - .append("Policy Status: Policy Status is required" + HTML_ITALICS_LNBREAK); - responseString - .append("Conditions: Select Atleast one Condition" + HTML_ITALICS_LNBREAK); + responseString.append( + "D2/Virtualized Services: Select atleast one D2/Virtualized Services" + + HTML_ITALICS_LNBREAK); + responseString.append( + "vPRO Actions: vPRO Actions is required" + HTML_ITALICS_LNBREAK); + responseString.append( + "Aging Window: Aging Window is required" + HTML_ITALICS_LNBREAK); + responseString.append( + "Policy Status: Policy Status is required" + HTML_ITALICS_LNBREAK); + responseString.append( + "Conditions: Select Atleast one Condition" + HTML_ITALICS_LNBREAK); responseString.append("PEP Name: PEP Name is required" + HTML_ITALICS_LNBREAK); responseString.append("PEP Action: PEP Action is required" + HTML_ITALICS_LNBREAK); - responseString - .append("Time Interval: Time Interval is required" + HTML_ITALICS_LNBREAK); responseString.append( - "Number of Retries: Number of Retries is required" + HTML_ITALICS_LNBREAK); - responseString - .append("APP-C Timeout: APP-C Timeout is required" + HTML_ITALICS_LNBREAK); + "Time Interval: Time Interval is required" + HTML_ITALICS_LNBREAK); + responseString.append("Number of Retries: Number of Retries is required" + + HTML_ITALICS_LNBREAK); + responseString.append( + "APP-C Timeout: APP-C Timeout is required" + HTML_ITALICS_LNBREAK); responseString.append("TimeOutRuby: TimeOutRuby is required" + HTML_ITALICS_LNBREAK); responseString.append("Vnf Type: Vnf Type is required" + HTML_ITALICS_LNBREAK); valid = false; } } - + // Validate MicroService Policy Data if (MICROSERVICES.equals(policyData.getConfigPolicyType())) { boolean tmpValid = validateMsModel(policyData, responseString); @@ -630,7 +636,7 @@ public class PolicyValidation { } // Validate Optimization Policy Data - if (OPTIMIZATION.equals(policyData.getConfigPolicyType())){ + if (OPTIMIZATION.equals(policyData.getConfigPolicyType())) { boolean tmpValid = validateOptimization(policyData, responseString); if (!tmpValid) { valid = false; @@ -639,7 +645,7 @@ public class PolicyValidation { } if ((DECISION_POLICY.equalsIgnoreCase(policyData.getPolicyType())) - || (DECISION_POLICY_MS.equalsIgnoreCase(policyData.getPolicyType()))) { + || (DECISION_POLICY_MS.equalsIgnoreCase(policyData.getPolicyType()))) { if (!RAW.equalsIgnoreCase(policyData.getRuleProvider())) { if (!Strings.isNullOrEmpty(policyData.getOnapName())) { String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName()); @@ -653,7 +659,8 @@ public class PolicyValidation { } } if (RAW.equalsIgnoreCase(policyData.getRuleProvider())) { - Object policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(StringEscapeUtils.unescapeXml(policyData.getRawXacmlPolicy()).getBytes(StandardCharsets.UTF_8))); + Object policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(StringEscapeUtils + .unescapeXml(policyData.getRawXacmlPolicy()).getBytes(StandardCharsets.UTF_8))); if (!(policy instanceof PolicySetType || policy instanceof PolicyType)) { responseString.append("Raw XACML: The XACML Content is not valid" + HTML_ITALICS_LNBREAK); valid = false; @@ -690,7 +697,7 @@ public class PolicyValidation { valid = false; } if (!policyData.getRainyday().getTreatmentTableChoices().isEmpty() - && policyData.getRainyday().getTreatmentTableChoices() != null) { + && policyData.getRainyday().getTreatmentTableChoices() != null) { for (Object treatmentMap : policyData.getRainyday().getTreatmentTableChoices()) { String errorCode = null; @@ -706,20 +713,20 @@ public class PolicyValidation { } if (Strings.isNullOrEmpty(errorCode) && Strings.isNullOrEmpty(treatment)) { - responseString.append( - "Rainy Day Error Code and Desired Treatment cannot be empty
"); + responseString.append("Rainy Day Error Code and " + + "Desired Treatment cannot be empty
"); valid = false; break; } if (Strings.isNullOrEmpty(errorCode)) { - responseString.append( - "Rainy Day Error Code is Required for each Desired Treatment
"); + responseString.append("Rainy Day Error Code is Required " + + "for each Desired Treatment
"); valid = false; break; } if (Strings.isNullOrEmpty(treatment)) { - responseString.append( - "Rainy Day Desired Treatment is Required for each Error Code
"); + responseString.append("Rainy Day Desired Treatment" + + " is Required for each Error Code
"); valid = false; break; } @@ -733,8 +740,8 @@ public class PolicyValidation { } if ("GUARD_YAML".equals(policyData.getRuleProvider()) - || "GUARD_BL_YAML".equals(policyData.getRuleProvider()) - || "GUARD_MIN_MAX".equals(policyData.getRuleProvider())) { + || "GUARD_BL_YAML".equals(policyData.getRuleProvider()) + || "GUARD_MIN_MAX".equals(policyData.getRuleProvider())) { if (policyData.getYamlparams() == null) { responseString.append(" Guard Params are Required " + HTML_ITALICS_LNBREAK); valid = false; @@ -748,13 +755,13 @@ public class PolicyValidation { valid = false; } if (Strings.isNullOrEmpty(policyData.getYamlparams().getGuardActiveStart())) { - responseString.append( - "Guard Params Guard Active Start is Required " + HTML_ITALICS_LNBREAK); + responseString.append("Guard Params Guard Active Start is Required " + + HTML_ITALICS_LNBREAK); valid = false; } if (Strings.isNullOrEmpty(policyData.getYamlparams().getGuardActiveEnd())) { - responseString - .append("Guard Params Guard Active End is Required " + HTML_ITALICS_LNBREAK); + responseString.append( + "Guard Params Guard Active End is Required " + HTML_ITALICS_LNBREAK); valid = false; } if ("GUARD_YAML".equals(policyData.getRuleProvider())) { @@ -762,22 +769,22 @@ public class PolicyValidation { responseString.append(" Guard Params Limit is Required " + HTML_ITALICS_LNBREAK); valid = false; } else if (!PolicyUtils.isInteger(policyData.getYamlparams().getLimit())) { - responseString - .append(" Guard Params Limit Should be Integer " + HTML_ITALICS_LNBREAK); + responseString.append( + " Guard Params Limit Should be Integer " + HTML_ITALICS_LNBREAK); valid = false; } if (Strings.isNullOrEmpty(policyData.getYamlparams().getTimeWindow())) { - responseString - .append("Guard Params Time Window is Required" + HTML_ITALICS_LNBREAK); + responseString.append( + "Guard Params Time Window is Required" + HTML_ITALICS_LNBREAK); valid = false; } else if (!PolicyUtils.isInteger(policyData.getYamlparams().getTimeWindow())) { - responseString.append( - " Guard Params Time Window Should be Integer " + HTML_ITALICS_LNBREAK); + responseString.append(" Guard Params Time Window Should be Integer " + + HTML_ITALICS_LNBREAK); valid = false; } if (Strings.isNullOrEmpty(policyData.getYamlparams().getTimeUnits())) { - responseString - .append("Guard Params Time Units is Required" + HTML_ITALICS_LNBREAK); + responseString.append( + "Guard Params Time Units is Required" + HTML_ITALICS_LNBREAK); valid = false; } } else if ("GUARD_MIN_MAX".equals(policyData.getRuleProvider())) { @@ -785,32 +792,32 @@ public class PolicyValidation { responseString.append(" Guard Params Min is Required " + HTML_ITALICS_LNBREAK); valid = false; } else if (!PolicyUtils.isInteger(policyData.getYamlparams().getMin())) { - responseString - .append(" Guard Params Min Should be Integer " + HTML_ITALICS_LNBREAK); + responseString.append( + " Guard Params Min Should be Integer " + HTML_ITALICS_LNBREAK); valid = false; } if (Strings.isNullOrEmpty(policyData.getYamlparams().getMax())) { responseString.append(" Guard Params Max is Required " + HTML_ITALICS_LNBREAK); valid = false; } else if (!PolicyUtils.isInteger(policyData.getYamlparams().getMax())) { - responseString - .append(" Guard Params Max Should be Integer " + HTML_ITALICS_LNBREAK); + responseString.append( + " Guard Params Max Should be Integer " + HTML_ITALICS_LNBREAK); valid = false; } } else if ("GUARD_BL_YAML".equals(policyData.getRuleProvider()) - && "Use Manual Entry".equals(policyData.getBlackListEntryType())) { + && "Use Manual Entry".equals(policyData.getBlackListEntryType())) { if (policyData.getYamlparams().getBlackList() == null - || policyData.getYamlparams().getBlackList().isEmpty()) { - responseString - .append(" Guard Params BlackList is Required " + HTML_ITALICS_LNBREAK); + || policyData.getYamlparams().getBlackList().isEmpty()) { + responseString.append( + " Guard Params BlackList is Required " + HTML_ITALICS_LNBREAK); valid = false; } else { for (String blackList : policyData.getYamlparams().getBlackList()) { - if (blackList == null - || !(SUCCESS.equals(PolicyUtils.policySpecialCharValidator(blackList)))) { + if (blackList == null || !(SUCCESS + .equals(PolicyUtils.policySpecialCharValidator(blackList)))) { responseString.append(" Guard Params BlackList Should be valid String" - + HTML_ITALICS_LNBREAK); + + HTML_ITALICS_LNBREAK); valid = false; break; } @@ -829,21 +836,21 @@ public class PolicyValidation { valid = false; } } else { - responseString.append( - "ActionPerformer: ActionPerformer Should not be empty" + HTML_ITALICS_LNBREAK); + responseString.append("ActionPerformer: ActionPerformer Should not be empty" + + HTML_ITALICS_LNBREAK); valid = false; } if (!Strings.isNullOrEmpty(policyData.getActionAttributeValue())) { - String actionAttribute = - PolicyUtils.policySpecialCharValidator(policyData.getActionAttributeValue()); + String actionAttribute = PolicyUtils + .policySpecialCharValidator(policyData.getActionAttributeValue()); if (!actionAttribute.contains(SUCCESS)) { responseString.append("ActionAttribute:" + actionAttribute + HTML_ITALICS_LNBREAK); valid = false; } } else { - responseString.append( - "ActionAttribute: ActionAttribute Should not be empty" + HTML_ITALICS_LNBREAK); + responseString.append("ActionAttribute: ActionAttribute Should not be empty" + + HTML_ITALICS_LNBREAK); valid = false; } } @@ -853,7 +860,7 @@ public class PolicyValidation { if (valid) { if (commonClassDao != null) { List spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", - policyData.getRiskType()); + policyData.getRiskType()); if (!spData.isEmpty()) { SafePolicyWarning safePolicyWarningData = (SafePolicyWarning) spData.get(0); value = "Message:" + safePolicyWarningData.getMessage() + ""; @@ -890,14 +897,14 @@ public class PolicyValidation { private MicroServiceModels getAttributeObject(String name, String version) { MicroServiceModels workingModel = null; try { - List microServiceModelsData = - commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", name + ":" + version); + List microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, + "modelName:version", name + ":" + version); if (microServiceModelsData != null) { workingModel = (MicroServiceModels) microServiceModelsData.get(0); } } catch (Exception e) { String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, " + name - + " was not found in the dictionary: "; + + " was not found in the dictionary: "; LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message + e); return null; } @@ -905,16 +912,17 @@ public class PolicyValidation { return workingModel; } - private OptimizationModels getOptimizationModelData(String name, String version) { + private OptimizationModels getOptimizationModelData(String name, String version) { OptimizationModels workingModel = null; - try{ - List optimizationModelsData = commonClassDao.getDataById(OptimizationModels.class, "modelName:version", name+":"+version); - if(optimizationModelsData != null){ + try { + List optimizationModelsData = commonClassDao.getDataById(OptimizationModels.class, + "modelName:version", name + ":" + version); + if (optimizationModelsData != null) { workingModel = (OptimizationModels) optimizationModelsData.get(0); } - }catch(Exception e){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, " - + name + " was not found in the dictionary: "; + } catch (Exception e) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, " + name + + " was not found in the dictionary: "; LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message + e); return null; } @@ -933,8 +941,9 @@ public class PolicyValidation { pullJsonKeyPairs(value); // RECURSIVE CALL } else { if (value.isArray()) { - String newValue = StringUtils.replaceEach(value.toString(), new String[] {"[", "]", "\""}, - new String[] {"", "", ""}); + String newValue = StringUtils.replaceEach(value.toString(), new String[] + { "[", "]", "\"" }, new String[] + { "", "", "" }); mapAttribute.put(key, newValue); } else { mapAttribute.put(key, value.toString().trim()); @@ -958,11 +967,11 @@ public class PolicyValidation { try { String valueStr = value.toString(); String stringValue = valueStr.substring(valueStr.indexOf('[') + 1, valueStr.lastIndexOf(']')); - + if (stringValue.isEmpty()) { stringValue = "{\"test\":\"test\"}"; } - + ObjectMapper mapper = new ObjectMapper(); JsonNode newValue = mapper.readTree(stringValue); jsonRequestMap.put(key.trim(), value.toString().trim()); @@ -981,10 +990,9 @@ public class PolicyValidation { try (JsonReader jsonReader = Json.createReader(new StringReader(value))) { return jsonReader.readObject(); } catch (JsonException | IllegalStateException e) { - LOGGER.info( - XACMLErrorConstants.ERROR_DATA_ISSUE - + "Improper JSON format... may or may not cause issues in validating the policy: " + value, - e); + LOGGER.info(XACMLErrorConstants.ERROR_DATA_ISSUE + + "Improper JSON format... may or may not cause issues in validating the policy: " + value, + e); return null; } } @@ -1044,13 +1052,13 @@ public class PolicyValidation { if (obj instanceof String && ((String) obj).contains(REQUIRED_ATTRIBUTE)) { LOGGER.debug("key : " + key); LOGGER.debug("obj : " + obj); - allReqTrueKeys.add(key); //For MicroService policies - allOptReqTrueKeys.add(key); //For Optimization policies - + allReqTrueKeys.add(key); // For MicroService policies + allOptReqTrueKeys.add(key); // For Optimization policies + // get the type from value and add that one also String type = StringUtils.substringBefore((String) obj, ":"); - if (!StringUtils.isBlank(type) && !StringUtils.containsAny(type.toLowerCase(), MSModelUtils.STRING, - MSModelUtils.INTEGER, MSModelUtils.LIST, MSModelUtils.MAP, "java", "boolean")) { + if (!StringUtils.isBlank(type) && !StringUtils.containsAny(type.toLowerCase(), STRING, INTEGER, LIST, + MAP, JAVA, BOOLEAN)) { allReqTrueKeys.add(type); } } @@ -1066,7 +1074,7 @@ public class PolicyValidation { } private boolean validateMsModel(PolicyRestAdapter policyData, StringBuilder responseString) - throws JsonProcessingException { + throws JsonProcessingException { boolean valid = true; if (!Strings.isNullOrEmpty(policyData.getServiceType())) { @@ -1102,7 +1110,7 @@ public class PolicyValidation { int startNum = Integer.parseInt(tempString[0]); int endNum = Integer.parseInt(tempString[1]); String returnString = "InvalidreturnModel Range:" + raMap.getKey() + " must be between " - + startNum + " - " + endNum + ","; + + startNum + " - " + endNum + ","; if (value != null) { if (PolicyUtils.isInteger(value.replace("\"", ""))) { @@ -1117,8 +1125,8 @@ public class PolicyValidation { } } else { responseString.append("" + raMap.getKey() + ":" + raMap.getKey() - + " is required for the MicroService model " + service - + HTML_ITALICS_LNBREAK); + + " is required for the MicroService model " + service + + HTML_ITALICS_LNBREAK); valid = false; } @@ -1129,26 +1137,26 @@ public class PolicyValidation { // model if (Strings.isNullOrEmpty(policyData.getLocation())) { responseString.append("Micro Service Model: location is required for this model" - + HTML_ITALICS_LNBREAK); + + HTML_ITALICS_LNBREAK); valid = false; } if (Strings.isNullOrEmpty(policyData.getConfigName())) { responseString.append("Micro Service Model: configName is required for this model" - + HTML_ITALICS_LNBREAK); + + HTML_ITALICS_LNBREAK); valid = false; } if (Strings.isNullOrEmpty(policyData.getUuid())) { responseString.append("Micro Service Model: uuid is required for this model" - + HTML_ITALICS_LNBREAK); + + HTML_ITALICS_LNBREAK); valid = false; } - + if (Strings.isNullOrEmpty(policyData.getPolicyScope())) { - responseString - .append("Micro Service Model: policyScope is required for this model" - + HTML_ITALICS_LNBREAK); + responseString.append( + "Micro Service Model: policyScope is required for this model" + + HTML_ITALICS_LNBREAK); valid = false; } } @@ -1157,11 +1165,12 @@ public class PolicyValidation { // GUI request are already validated from the SDK-APP if ("API".equals(policyData.getApiflag())) { // first , get the complete set of required fields - populateReqFieldSet(new String[] {refAttributes, modelAttributes}, subAttributes); + populateReqFieldSet(new String[] + { refAttributes, modelAttributes }, subAttributes); // ignore req fields in which parent is not reqd - populateRequiredFields(new String[] {refAttributes, modelAttributes}, subAttributes, - modelAttributes); + populateRequiredFields(new String[] + { refAttributes, modelAttributes }, subAttributes, modelAttributes); if (modelRequiredFieldsList != null && !modelRequiredFieldsList.isEmpty()) { // create jsonRequestMap with all json keys and values from request @@ -1175,12 +1184,12 @@ public class PolicyValidation { String value = jsonRequestMap.get(requiredField); if (StringUtils.isBlank(value) || "\"\"".equals(value)) { responseString.append("Micro Service Model: " + requiredField - + ISREQUIRED + HTML_ITALICS_LNBREAK); + + ISREQUIRED + HTML_ITALICS_LNBREAK); valid = false; } } else { - responseString.append("Micro Service Model: " + requiredField - + ISREQUIRED + HTML_ITALICS_LNBREAK); + responseString.append("Micro Service Model: " + requiredField + ISREQUIRED + + HTML_ITALICS_LNBREAK); valid = false; } } @@ -1188,12 +1197,13 @@ public class PolicyValidation { } } else { responseString.append("Micro Service Model: Invalid Model. The model name, " + service - + " of version, " + version + " was not found in the dictionary" + HTML_ITALICS_LNBREAK); + + " of version, " + version + " was not found in the dictionary" + + HTML_ITALICS_LNBREAK); valid = false; } } else { - responseString.append( - "Micro Service Version: Micro Service Version is required" + HTML_ITALICS_LNBREAK); + responseString.append("Micro Service Version: Micro Service Version is required" + + HTML_ITALICS_LNBREAK); valid = false; } } else { @@ -1202,28 +1212,26 @@ public class PolicyValidation { } if (Strings.isNullOrEmpty(policyData.getPriority()) - && !DECISION_MS_MODEL.equals(policyData.getRuleProvider())) { + && !DECISION_MS_MODEL.equals(policyData.getRuleProvider())) { responseString.append("Priority: Priority is required" + HTML_ITALICS_LNBREAK); } - return valid; } - + private boolean validateOptimization(PolicyRestAdapter policyData, StringBuilder responseString) { boolean valid = true; - + // Checks for required policy data in request if (Strings.isNullOrEmpty(policyData.getServiceType())) { - responseString.append( - "Optimization Service: Optimization policy data is missing or invalid Json." + responseString.append("Optimization Service: Optimization policy data is missing or invalid Json." + HTML_ITALICS_LNBREAK); return false; } - + modelRequiredFieldsList.clear(); pullJsonKeyPairs((JsonNode) policyData.getPolicyJSON()); - + // parse the service and version from the policy data String service; String version; @@ -1234,22 +1242,20 @@ public class PolicyValidation { service = policyData.getServiceType(); version = policyData.getVersion(); } - + // Checks for required version in policy data if (Strings.isNullOrEmpty(version)) { - responseString.append( - "Optimization Service Version: Optimization Service Version is required" + responseString.append("Optimization Service Version: Optimization Service Version is required" + HTML_ITALICS_LNBREAK); return false; } - + OptimizationModels returnModel = getOptimizationModelData(service, version); - + // Checks if valid model exists in the database if (returnModel == null) { - responseString.append("Optimization Service Model: Invalid Model. The model name, " - + service + " of version, " + version - + " was not found in the dictionary" + HTML_ITALICS_LNBREAK); + responseString.append("Optimization Service Model: Invalid Model. The model name, " + service + + " of version, " + version + " was not found in the dictionary" + HTML_ITALICS_LNBREAK); return false; } @@ -1259,16 +1265,15 @@ public class PolicyValidation { String modelAttributes = returnModel.getAttributes(); if (!Strings.isNullOrEmpty(annotation)) { - Map rangeMap = Splitter.on(",").withKeyValueSeparator("=") - .split(annotation); - for (Entry rMap : rangeMap.entrySet()) { - if (rMap.getValue().contains("range::")) { - String value = mapAttribute.get(rMap.getKey().trim()); - String[] tempString = rMap.getValue().split("::")[1].split("-"); + Map rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annotation); + for (Entry rangeMapEntry : rangeMap.entrySet()) { + if (rangeMapEntry.getValue().contains("range::")) { + String value = mapAttribute.get(rangeMapEntry.getKey().trim()); + String[] tempString = rangeMapEntry.getValue().split("::")[1].split("-"); int startNum = Integer.parseInt(tempString[0]); int endNum = Integer.parseInt(tempString[1]); - String returnString = "InvalidreturnModel Range:" + rMap.getKey() - + " must be between " + startNum + " - " + endNum + ","; + String returnString = "InvalidreturnModel Range:" + rangeMapEntry.getKey() + " must be between " + + startNum + " - " + endNum + ","; if (value != null) { if (PolicyUtils.isInteger(value.replace("\"", ""))) { @@ -1282,9 +1287,8 @@ public class PolicyValidation { valid = false; } } else { - responseString.append("" + rMap.getKey() + ":" + rMap.getKey() - + " is required for the Optimization model " + service - + HTML_ITALICS_LNBREAK); + responseString.append("" + rangeMapEntry.getKey() + ":" + rangeMapEntry.getKey() + + " is required for the Optimization model " + service + HTML_ITALICS_LNBREAK); valid = false; } @@ -1296,12 +1300,13 @@ public class PolicyValidation { // GUI request are already validated from the SDK-APP if ("API".equals(policyData.getApiflag())) { // first , get the complete set of required fields - populateReqFieldSet(new String[] {refAttributes, modelAttributes}, subAttributes); + populateReqFieldSet(new String[] + { refAttributes, modelAttributes }, subAttributes); modelRequiredFieldsList.addAll(allOptReqTrueKeys); - + if (modelRequiredFieldsList != null && !modelRequiredFieldsList.isEmpty()) { - + // create jsonRequestMap with all json keys and values from request JsonNode rootNode = (JsonNode) policyData.getPolicyJSON(); jsonRequestMap.clear(); @@ -1312,13 +1317,13 @@ public class PolicyValidation { if (jsonRequestMap.containsKey(requiredField)) { String value = jsonRequestMap.get(requiredField); if (StringUtils.isBlank(value) || "\"\"".equals(value)) { - responseString.append("Optimization Service Model: " - + requiredField + ISREQUIRED + HTML_ITALICS_LNBREAK); + responseString.append("Optimization Service Model: " + requiredField + ISREQUIRED + + HTML_ITALICS_LNBREAK); valid = false; } } else { - responseString.append("Optimization Service Model: " - + requiredField + ISREQUIRED + HTML_ITALICS_LNBREAK); + responseString.append("Optimization Service Model: " + requiredField + ISREQUIRED + + HTML_ITALICS_LNBREAK); valid = false; } } @@ -1334,7 +1339,7 @@ public class PolicyValidation { } private void populateRequiredFields(String[] attrArr, String subAttributes, String modelAttributes) - throws JsonProcessingException { + throws JsonProcessingException { // get list of required fields from the ref_Attributes of the Model for (String attributes : attrArr) { if (!StringUtils.isBlank(attributes)) { @@ -1367,7 +1372,6 @@ public class PolicyValidation { // Get all keys with "required-true" defined in their value from subAttribute getAllKeys(jsonSub); - // parse refAttrbutes for (String attr : attrArr) { if (attr != null) { @@ -1383,5 +1387,4 @@ public class PolicyValidation { } } - } diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidationRequestWrapper.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidationRequestWrapper.java index 779c5227a..8fdc1e1d2 100644 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidationRequestWrapper.java +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidationRequestWrapper.java @@ -3,20 +3,28 @@ * ONAP Policy Engine * ================================================================================ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= - */package org.onap.policy.rest.util; + */ + +package org.onap.policy.rest.util; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Strings; import java.io.IOException; import java.io.StringReader; @@ -43,29 +51,29 @@ import org.onap.policy.rest.adapter.RainyDayParams; import org.onap.policy.rest.adapter.YAMLParams; import org.onap.policy.xacml.api.XACMLErrorConstants; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.base.Strings; - public class PolicyValidationRequestWrapper { - - private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationRequestWrapper.class); - public static final String CONFIG_NAME="configName"; - public static final String INVALIDJSON = " improper JSON format: "; - public static final String ONAPNAME = "onapname"; - public static final String CONTENT = "content"; - public static final String GUARD = "guard"; - public static final String LOCATION = "location"; - public static final String POLICYSCOPE = "policyScope"; - public static final String PRIORITY = "priority"; - public static final String RISKLEVEL = "riskLevel"; - public static final String RISKTYPE = "riskType"; - public static final String SERVICE = "service"; - public static final String VERSION = "version"; - - public static final String SERVICETYPE_POLICY_NAME = "serviceTypePolicyName"; - + private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationRequestWrapper.class); + + private static final String CONFIG_NAME = "configName"; + private static final String CONTENT = "content"; + private static final String GUARD = "guard"; + private static final String INVALIDJSON = " improper JSON format: "; + private static final String LOCATION = "location"; + private static final String ONAPNAME = "onapname"; + private static final String POLICYSCOPE = "policyScope"; + private static final String PRIORITY = "priority"; + private static final String RISKLEVEL = "riskLevel"; + private static final String RISKTYPE = "riskType"; + private static final String SERVICE = "service"; + private static final String SERVICETYPE_POLICY_NAME = "serviceTypePolicyName"; + private static final String VERSION = "version"; + + /** + * Populate request parameters. + * + * @param request the request + * @return the policy rest adapter + */ public PolicyRestAdapter populateRequestParameters(HttpServletRequest request) { PolicyRestAdapter policyData = null; @@ -76,11 +84,11 @@ public class PolicyValidationRequestWrapper { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); policyData = mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class); - if(root.get("trapData") != null){ + if (root.get("trapData") != null) { trapDatas = mapper.readValue(root.get("trapData").toString(), ClosedLoopFaultTrapDatas.class); policyData.setTrapDatas(trapDatas); } - if(root.get("faultData") != null){ + if (root.get("faultData") != null) { faultDatas = mapper.readValue(root.get("faultData").toString(), ClosedLoopFaultTrapDatas.class); policyData.setFaultDatas(faultDatas); } @@ -88,74 +96,80 @@ public class PolicyValidationRequestWrapper { JsonObject json; json = stringToJsonObject(root.toString()); - if(json != null){ - if(json.containsKey("policyJSON")){ + if (json != null) { + if (json.containsKey("policyJSON")) { policyData.setPolicyJSON(root.get("policyJSON")); - }else{ + } else { String jsonBodyData = json.getJsonObject("policyData").get("jsonBodyData").toString(); policyData.setJsonBody(jsonBodyData); } } } catch (Exception e) { - LOGGER.error("Exception Occured while populating request parameters: " +e); + LOGGER.error("Exception Occured while populating request parameters: " + e); } return policyData; } + /** + * Populate request parameters. + * + * @param parameters the parameters + * @return the policy rest adapter + */ public PolicyRestAdapter populateRequestParameters(PolicyParameters parameters) { PolicyRestAdapter policyData = new PolicyRestAdapter(); - + /* * set policy adapter values for Building JSON object containing policy data */ - //Common Policy Fields + // Common Policy Fields policyData.setPolicyName(parameters.getPolicyName()); policyData.setOnapName(parameters.getOnapName()); - policyData.setPriority(parameters.getPriority()); //Micro Service - policyData.setConfigName(parameters.getConfigName()); //Base and Firewall - policyData.setRiskType(parameters.getRiskType()); //Safe parameters Attributes - policyData.setRiskLevel(parameters.getRiskLevel());//Safe parameters Attributes - policyData.setGuard(String.valueOf(parameters.getGuard()));//Safe parameters Attributes - policyData.setTtlDate(convertDate(parameters.getTtlDate()));//Safe parameters Attributes + policyData.setPriority(parameters.getPriority()); // Micro Service + policyData.setConfigName(parameters.getConfigName()); // Base and Firewall + policyData.setRiskType(parameters.getRiskType()); // Safe parameters Attributes + policyData.setRiskLevel(parameters.getRiskLevel());// Safe parameters Attributes + policyData.setGuard(String.valueOf(parameters.getGuard()));// Safe parameters Attributes + policyData.setTtlDate(convertDate(parameters.getTtlDate()));// Safe parameters Attributes policyData.setApiflag("API"); - //Some policies require jsonObject conversion from String for configBody (i.e. MicroService and Firewall) + // Some policies require jsonObject conversion from String for configBody (i.e. MicroService and Firewall) JsonObject json = null; - try{ - if(parameters.getConfigBody()!= null){ + try { + if (parameters.getConfigBody() != null) { json = stringToJsonObject(parameters.getConfigBody()); } - } catch(JsonException| IllegalStateException e){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody(); + } catch (JsonException | IllegalStateException e) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + INVALIDJSON + parameters.getConfigBody(); LOGGER.error(message, e); return null; } - - if(parameters.getPolicyClass()!=null && !"Config".equals(parameters.getPolicyClass().toString())){ + + if (parameters.getPolicyClass() != null && !"Config".equals(parameters.getPolicyClass().toString())) { policyData.setPolicyType(parameters.getPolicyClass().toString()); - //Get Matching attribute values + // Get Matching attribute values Map> attributes = parameters.getAttributes(); Map matching = null; - if(attributes != null){ + if (attributes != null) { matching = attributes.get(AttributeType.MATCHING); } - if("Decision".equals(parameters.getPolicyClass().toString())){ + if ("Decision".equals(parameters.getPolicyClass().toString())) { String ruleProvider = parameters.getRuleProvider().toString(); policyData.setRuleProvider(ruleProvider); - if("Rainy_Day".equals(ruleProvider)){ + if ("Rainy_Day".equals(ruleProvider)) { // Set Matching attributes in RainyDayParams in adapter RainyDayParams rainyday = new RainyDayParams(); - if(matching != null) { + if (matching != null) { rainyday.setServiceType(matching.get("ServiceType")); rainyday.setVnfType(matching.get("VNFType")); rainyday.setBbid(matching.get("BB_ID")); @@ -177,7 +191,7 @@ public class PolicyValidationRequestWrapper { policyData.setRainyday(rainyday); } else if ("GUARD_YAML".equals(ruleProvider) || "GUARD_BL_YAML".equals(ruleProvider) - || "GUARD_MIN_MAX".equals(ruleProvider)) { + || "GUARD_MIN_MAX".equals(ruleProvider)) { // Set Matching attributes in YAMLParams in adapter YAMLParams yamlparams = new YAMLParams(); @@ -188,20 +202,20 @@ public class PolicyValidationRequestWrapper { yamlparams.setGuardActiveStart(matching.get("guardActiveStart")); yamlparams.setGuardActiveEnd(matching.get("guardActiveEnd")); - if("GUARD_YAML".equals(ruleProvider)){ + if ("GUARD_YAML".equals(ruleProvider)) { yamlparams.setLimit(matching.get("limit")); yamlparams.setTimeWindow(matching.get("timeWindow")); yamlparams.setTimeUnits(matching.get("timeUnits")); } else if ("GUARD_MIN_MAX".equals(ruleProvider)) { yamlparams.setMin(matching.get("min")); yamlparams.setMax(matching.get("max")); - }else{ + } else { List blackList = new ArrayList<>(); - if(!Strings.isNullOrEmpty(matching.get("blackList"))){ + if (!Strings.isNullOrEmpty(matching.get("blackList"))) { String[] blackListArray = matching.get("blackList").split(","); - for(String element : blackListArray){ + for (String element : blackListArray) { blackList.add(element); } } @@ -213,7 +227,7 @@ public class PolicyValidationRequestWrapper { policyData.setYamlparams(yamlparams); } - } else if("Action".equals(parameters.getPolicyClass().toString())){ + } else if ("Action".equals(parameters.getPolicyClass().toString())) { ArrayList ruleAlgorithmChoices = new ArrayList<>(); @@ -223,9 +237,8 @@ public class PolicyValidationRequestWrapper { List dyrnamicFieldTwoRuleAlgorithms = parameters.getDynamicRuleAlgorithmField2(); if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) { - int i = dynamicLabelRuleAlgorithms.size() - 1; - for (String labelAttr : dynamicLabelRuleAlgorithms) { + for (int i = dynamicLabelRuleAlgorithms.size() - 1; i >= 0; i--) { LinkedHashMap ruleAlgorithm = new LinkedHashMap<>(); String id = dynamicLabelRuleAlgorithms.get(i); @@ -239,9 +252,6 @@ public class PolicyValidationRequestWrapper { ruleAlgorithm.put("dynamicRuleAlgorithmField2", dynamicRuleAlgorithmField2); ruleAlgorithmChoices.add(ruleAlgorithm); - - i--; - } } @@ -264,189 +274,193 @@ public class PolicyValidationRequestWrapper { policyData.setActionPerformer(parameters.getActionPerformer()); } - }else { + } else { policyData.setPolicyType("Config"); policyData.setConfigPolicyType(parameters.getPolicyConfigType().toString()); - //Config Specific - policyData.setConfigBodyData(parameters.getConfigBody()); //Base - policyData.setConfigType((parameters.getConfigBodyType()!=null) ? parameters.getConfigBodyType().toString().toUpperCase(): null); //Base + // Config Specific + policyData.setConfigBodyData(parameters.getConfigBody()); // Base + policyData.setConfigType((parameters.getConfigBodyType() != null) + ? parameters.getConfigBodyType().toString().toUpperCase() + : null); // Base - if("FW".equalsIgnoreCase(parameters.getPolicyConfigType().toString())){ + if ("FW".equalsIgnoreCase(parameters.getPolicyConfigType().toString())) { policyData.setConfigPolicyType("Firewall Config"); // get values and attributes from the JsonObject - if(json != null){ - if (json.get("securityZoneId")!=null){ + if (json != null) { + if (json.get("securityZoneId") != null) { String securityZone = json.get("securityZoneId").toString().replace("\"", ""); policyData.setSecurityZone(securityZone); } - if (json.get(CONFIG_NAME)!=null){ + if (json.get(CONFIG_NAME) != null) { String configName = json.get(CONFIG_NAME).toString().replace("\"", ""); policyData.setConfigName(configName); } } - }else if("MS".equals(parameters.getPolicyConfigType().toString())){ + } else if ("MS".equals(parameters.getPolicyConfigType().toString())) { policyData.setConfigPolicyType("Micro Service"); // get values and attributes from the JsonObject - if(json != null){ - if (json.containsKey(CONTENT)){ + if (json != null) { + if (json.containsKey(CONTENT)) { String content = json.get(CONTENT).toString(); ObjectMapper mapper = new ObjectMapper(); - JsonNode policyJSON = null; + JsonNode policyJson = null; try { - policyJSON = mapper.readTree(content); + policyJson = mapper.readTree(content); } catch (IOException e) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody(); + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + INVALIDJSON + + parameters.getConfigBody(); LOGGER.error(message, e); return null; } - policyData.setPolicyJSON(policyJSON); + policyData.setPolicyJSON(policyJson); } - if (json.containsKey(SERVICE)){ + if (json.containsKey(SERVICE)) { String serviceType = json.get(SERVICE).toString().replace("\"", ""); policyData.setServiceType(serviceType); } - if (json.containsKey("uuid")){ + if (json.containsKey("uuid")) { String uuid = json.get("uuid").toString().replace("\"", ""); policyData.setUuid(uuid); } - if (json.containsKey(LOCATION)){ + if (json.containsKey(LOCATION)) { String msLocation = json.get(LOCATION).toString().replace("\"", ""); policyData.setLocation(msLocation); } - if (json.containsKey(CONFIG_NAME)){ + if (json.containsKey(CONFIG_NAME)) { String configName = json.get(CONFIG_NAME).toString().replace("\"", ""); policyData.setConfigName(configName); } - if(json.containsKey(PRIORITY)){ + if (json.containsKey(PRIORITY)) { String priority = json.get(PRIORITY).toString().replace("\"", ""); policyData.setPriority(priority); } - if(json.containsKey(VERSION)){ + if (json.containsKey(VERSION)) { String version = json.get(VERSION).toString().replace("\"", ""); policyData.setVersion(version); } - if(json.containsKey(POLICYSCOPE)){ + if (json.containsKey(POLICYSCOPE)) { String policyScope = json.get(POLICYSCOPE).toString().replace("\"", ""); policyData.setPolicyScope(policyScope); } - if(json.containsKey(RISKTYPE)){ + if (json.containsKey(RISKTYPE)) { String riskType = json.get(RISKTYPE).toString().replace("\"", ""); policyData.setRiskType(riskType); } - if(json.containsKey(RISKLEVEL)){ + if (json.containsKey(RISKLEVEL)) { String riskLevel = json.get(RISKLEVEL).toString().replace("\"", ""); policyData.setRiskLevel(riskLevel); } - if(json.containsKey(GUARD)){ + if (json.containsKey(GUARD)) { String guard = json.get(GUARD).toString().replace("\"", ""); policyData.setGuard(guard); } } else { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody(); + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + INVALIDJSON + parameters.getConfigBody(); LOGGER.error(message); return null; } - }else if("Optimization".equals(parameters.getPolicyConfigType().toString())){ + } else if ("Optimization".equals(parameters.getPolicyConfigType().toString())) { policyData.setConfigPolicyType("Optimization"); // get values and attributes from the JsonObject - if(json != null){ - if (json.containsKey(CONTENT)){ + if (json != null) { + if (json.containsKey(CONTENT)) { String content = json.get(CONTENT).toString(); ObjectMapper mapper = new ObjectMapper(); - JsonNode policyJSON = null; + JsonNode policyJson = null; try { - policyJSON = mapper.readTree(content); + policyJson = mapper.readTree(content); } catch (IOException e) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody(); + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + INVALIDJSON + + parameters.getConfigBody(); LOGGER.error(message, e); return null; } - policyData.setPolicyJSON(policyJSON); + policyData.setPolicyJSON(policyJson); } - if (json.containsKey(SERVICE)){ + if (json.containsKey(SERVICE)) { String serviceType = json.get(SERVICE).toString().replace("\"", ""); policyData.setServiceType(serviceType); } - if (json.containsKey("uuid")){ + if (json.containsKey("uuid")) { String uuid = json.get("uuid").toString().replace("\"", ""); policyData.setUuid(uuid); } - if (json.containsKey(LOCATION)){ + if (json.containsKey(LOCATION)) { String msLocation = json.get(LOCATION).toString().replace("\"", ""); policyData.setLocation(msLocation); } - if (json.containsKey(CONFIG_NAME)){ + if (json.containsKey(CONFIG_NAME)) { String configName = json.get(CONFIG_NAME).toString().replace("\"", ""); policyData.setConfigName(configName); } - if(json.containsKey(PRIORITY)){ + if (json.containsKey(PRIORITY)) { String priority = json.get(PRIORITY).toString().replace("\"", ""); policyData.setPriority(priority); } - if(json.containsKey(VERSION)){ + if (json.containsKey(VERSION)) { String version = json.get(VERSION).toString().replace("\"", ""); policyData.setVersion(version); } - if(json.containsKey(POLICYSCOPE)){ + if (json.containsKey(POLICYSCOPE)) { String policyScope = json.get(POLICYSCOPE).toString().replace("\"", ""); policyData.setPolicyScope(policyScope); } - if(json.containsKey(RISKTYPE)){ + if (json.containsKey(RISKTYPE)) { String riskType = json.get(RISKTYPE).toString().replace("\"", ""); policyData.setRiskType(riskType); } - if(json.containsKey(RISKLEVEL)){ + if (json.containsKey(RISKLEVEL)) { String riskLevel = json.get(RISKLEVEL).toString().replace("\"", ""); policyData.setRiskLevel(riskLevel); } - if(json.containsKey(GUARD)){ + if (json.containsKey(GUARD)) { String guard = json.get(GUARD).toString().replace("\"", ""); policyData.setGuard(guard); } } - } else if("Fault".equals(parameters.getPolicyConfigType().toString())){ + } else if ("Fault".equals(parameters.getPolicyConfigType().toString())) { policyData.setConfigPolicyType("ClosedLoop_Fault"); - if(json != null){ + if (json != null) { policyData.setJsonBody(json.toString()); - if (json.get(ONAPNAME)!=null){ + if (json.get(ONAPNAME) != null) { String onapName = json.get(ONAPNAME).toString().replace("\"", ""); policyData.setOnapName(onapName); } } - } else if("PM".equals(parameters.getPolicyConfigType().toString())){ + } else if ("PM".equals(parameters.getPolicyConfigType().toString())) { policyData.setConfigPolicyType("ClosedLoop_PM"); - if(json != null){ + if (json != null) { policyData.setJsonBody(json.toString()); - if (json.get(ONAPNAME)!=null){ + if (json.get(ONAPNAME) != null) { String onapName = json.get(ONAPNAME).toString().replace("\"", ""); policyData.setOnapName(onapName); } - if (json.get(SERVICETYPE_POLICY_NAME)!=null){ + if (json.get(SERVICETYPE_POLICY_NAME) != null) { String serviceType = json.get(SERVICETYPE_POLICY_NAME).toString().replace("\"", ""); LinkedHashMap serviceTypePolicyName = new LinkedHashMap<>(); serviceTypePolicyName.put(SERVICETYPE_POLICY_NAME, serviceType); policyData.setServiceTypePolicyName(serviceTypePolicyName); } } - } else if("BRMS_Param".equals(parameters.getPolicyConfigType().toString())){ - Map> drlRuleAndUIParams = parameters.getAttributes(); - Map rule = drlRuleAndUIParams.get(AttributeType.RULE); + } else if ("BRMS_Param".equals(parameters.getPolicyConfigType().toString())) { + Map> drlRuleAndUiParams = parameters.getAttributes(); + Map rule = drlRuleAndUiParams.get(AttributeType.RULE); policyData.setRuleName(rule.get("templateName")); } @@ -455,23 +469,25 @@ public class PolicyValidationRequestWrapper { return policyData; } - + private JsonObject stringToJsonObject(String value) { - try(JsonReader jsonReader = Json.createReader(new StringReader(value))){ + try (JsonReader jsonReader = Json.createReader(new StringReader(value))) { return jsonReader.readObject(); - } catch(JsonException| IllegalStateException e){ - LOGGER.info(XACMLErrorConstants.ERROR_DATA_ISSUE+ "Improper JSON format... may or may not cause issues in validating the policy: " + value, e); + } catch (JsonException | IllegalStateException e) { + LOGGER.info(XACMLErrorConstants.ERROR_DATA_ISSUE + + "Improper JSON format... may or may not cause issues in validating the policy: " + value, + e); return null; } } - + private String convertDate(Date date) { String strDate = null; - if (date!=null) { + if (date != null) { SimpleDateFormat dateformatJava = new SimpleDateFormat("dd-MM-yyyy"); strDate = dateformatJava.format(date); } - return (strDate==null) ? "NA": strDate; + return (strDate == null) ? "NA" : strDate; } } diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/XacmlRestTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/XacmlRestTest.java index 19800b42e..3b03bdcc8 100644 --- a/ONAP-REST/src/test/java/org/onap/policy/rest/XacmlRestTest.java +++ b/ONAP-REST/src/test/java/org/onap/policy/rest/XacmlRestTest.java @@ -26,9 +26,6 @@ import static org.junit.Assert.fail; import com.att.research.xacml.util.XACMLProperties; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; @@ -40,7 +37,6 @@ import java.util.List; import java.util.Map; import java.util.Properties; -import javax.servlet.ReadListener; import javax.servlet.ServletConfig; import javax.servlet.ServletInputStream; import javax.servlet.ServletOutputStream; @@ -199,8 +195,8 @@ public class XacmlRestTest extends Mockito { } @Test - public void testConstructorIsPrivate() - throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { + public void testConstructorIsPrivate() throws NoSuchMethodException, IllegalAccessException, + InvocationTargetException, InstantiationException { Constructor constructor = XacmlRestProperties.class.getDeclaredConstructor(); assertTrue(Modifier.isPrivate(constructor.getModifiers())); constructor.setAccessible(true); @@ -289,9 +285,12 @@ public class XacmlRestTest extends Mockito { XacmlRest.dumpRequest(httpServletRequest); Map parameterMap = new LinkedHashMap<>(); - String[] mapValue0 = {"MapValue0"}; - String[] mapValue1 = {"MapValue0"}; - String[] mapValue2 = {}; + String[] mapValue0 = + { "MapValue0" }; + String[] mapValue1 = + { "MapValue0" }; + String[] mapValue2 = + {}; parameterMap.put("Key0", mapValue0); parameterMap.put("Key1", mapValue1); parameterMap.put("Key2", mapValue2); diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/GetterSetterToStringTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/GetterSetterToStringTest.java new file mode 100644 index 000000000..62d486c63 --- /dev/null +++ b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/GetterSetterToStringTest.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.rest.jpa; + +import com.openpojo.reflection.filters.FilterClassName; +import com.openpojo.reflection.filters.FilterPackageInfo; +import com.openpojo.validation.Validator; +import com.openpojo.validation.ValidatorBuilder; +import com.openpojo.validation.test.impl.GetterTester; +import com.openpojo.validation.test.impl.SetterTester; + +import org.junit.Test; +import org.onap.policy.common.utils.test.ToStringTester; + +/** + * Class to perform unit testing of POJOs. + */ +public class GetterSetterToStringTest { + private static final String POJO_PACKAGE = "org.onap.policy.rest.jpa"; + + @Test + public void testPdpModels() { + // @formatter:off + final Validator validator = + ValidatorBuilder.create() + .with(new ToStringTester()) + .with(new SetterTester()) + .with(new GetterTester()) + .build(); + + // exclude Test classes and PdpMessage + validator.validate( + POJO_PACKAGE, + new FilterPackageInfo(), + new FilterClassName("^((?!Test$).)*$") + ); + // @formatter:on + } +} diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ModelsTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ModelsTest.java deleted file mode 100644 index fb1b8a527..000000000 --- a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ModelsTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.rest.jpa; - -import com.openpojo.reflection.filters.FilterClassName; -import com.openpojo.reflection.filters.FilterPackageInfo; -import com.openpojo.validation.Validator; -import com.openpojo.validation.ValidatorBuilder; -import com.openpojo.validation.test.impl.GetterTester; -import com.openpojo.validation.test.impl.SetterTester; - -import org.junit.Test; -import org.onap.policy.common.utils.test.ToStringTester; - -/** - * Class to perform unit testing of POJOs. - */ -public class ModelsTest { - private static final String POJO_PACKAGE = "org.onap.policy.rest.jpa"; - - @Test - public void testPdpModels() { - // @formatter:off - final Validator validator = - ValidatorBuilder.create() - .with(new ToStringTester()) - .with(new SetterTester()) - .with(new GetterTester()) - .build(); - - // exclude Test classes and PdpMessage - validator.validate( - POJO_PACKAGE, - new FilterPackageInfo(), - new FilterClassName("^((?!Test$).)*$") - ); - // @formatter:on - } -} diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/util/DummyPolicyContainer.java b/ONAP-REST/src/test/java/org/onap/policy/rest/util/DummyPolicyContainer.java new file mode 100644 index 000000000..385576744 --- /dev/null +++ b/ONAP-REST/src/test/java/org/onap/policy/rest/util/DummyPolicyContainer.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.rest.util; + +import java.util.Collection; + +public class DummyPolicyContainer implements PolicyContainer { + private static final long serialVersionUID = 1L; + + @Override + public Collection getContainerPropertyIds() { + return null; + } + + @Override + public Collection getItemIds() { + return null; + } + + @Override + public Class getType(Object propertyId) { + return null; + } + + @Override + public int size() { + return 0; + } + + @Override + public boolean containsId(Object itemId) { + return false; + } + + @Override + public Object addItem() { + return null; + } + + @Override + public boolean removeItem(Object itemId) { + return false; + } + + @Override + public boolean addContainerProperty(Object propertyId, Class type, Object defaultValue) { + return false; + } + + @Override + public boolean removeContainerProperty(Object propertyId) { + return false; + } + + @Override + public boolean removeAllItems() { + return false; + } +} diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/util/MSAttributeObjectTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/util/MSAttributeObjectTest.java deleted file mode 100644 index a39eb4996..000000000 --- a/ONAP-REST/src/test/java/org/onap/policy/rest/util/MSAttributeObjectTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP-REST - * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.rest.util; - -import static org.junit.Assert.assertTrue; -import java.util.HashMap; -import org.junit.Test; - -public class MSAttributeObjectTest { - - @Test - public void testMSAttributeObject() { - MSAttributeObject data = new MSAttributeObject(); - data.setClassName("Test"); - assertTrue("Test".equals(data.getClassName())); - data.setRefAttribute(new HashMap<>()); - assertTrue(data.getRefAttribute() != null); - data.setAttribute(new HashMap<>()); - assertTrue(data.getAttribute() != null); - data.setEnumType(new HashMap<>()); - assertTrue(data.getEnumType() != null); - data.addAttribute("test", "test"); - data.addRefAttribute("test", "test"); - data.addAllAttribute(new HashMap<>()); - data.addAllRefAttribute(new HashMap<>()); - data.setSubClass(new HashMap<>()); - assertTrue(data.getSubClass() != null); - data.addAllSubClass(new HashMap<>()); - data.setDependency("Test"); - assertTrue("Test".equals(data.getDependency())); - data.addSingleEnum("test", "test"); - data.setMatchingSet(new HashMap<>()); - assertTrue(data.getMatchingSet() != null); - data.addMatchingSet("test", "test"); - data.addMatchingSet(new HashMap<>()); - data.setPolicyTempalate(true); - assertTrue(data.isPolicyTempalate()); - data.setRuleFormation("ruleFormation"); - assertTrue(data.getRuleFormation() != null); - data.setDataOrderInfo("dataOrderInfo"); - assertTrue(data.getDataOrderInfo() != null); - } - - @Test - public void testMSAttributeValue() { - MSAttributeValue data = new MSAttributeValue(); - data.setName("Test"); - assertTrue("Test".equals(data.getName())); - data.setType("Test"); - assertTrue("Test".equals(data.getType())); - data.setRequired(true); - assertTrue(data.getRequired()); - data.setArrayValue(true); - assertTrue(data.getArrayValue()); - data.setDefaultValue("Test"); - assertTrue("Test".equals(data.getDefaultValue())); - } -} diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/util/MSModelUtilsTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/util/MSModelUtilsTest.java deleted file mode 100644 index 34d555062..000000000 --- a/ONAP-REST/src/test/java/org/onap/policy/rest/util/MSModelUtilsTest.java +++ /dev/null @@ -1,160 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP-REST - * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.rest.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.commons.lang.StringUtils; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.dao.CommonClassDao; -import org.onap.policy.rest.jpa.DictionaryData; -import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE; - -public class MSModelUtilsTest { - private static Logger logger = FlexLogger.getLogger(MSModelUtilsTest.class); - private static CommonClassDao commonClassDao; - - @Before - public void setUp() throws Exception { - List dictionaryData = new ArrayList(); - DictionaryData testData = new DictionaryData(); - testData.setDictionaryName("dictionaryName"); - testData.setDictionaryDataByName("dictionaryDataByName"); - dictionaryData.add(testData); - logger.info("setUp: Entering"); - commonClassDao = mock(CommonClassDao.class); - when(commonClassDao.getDataById(DictionaryData.class, "dictionaryName", "GocVNFType")) - .thenReturn(dictionaryData); - } - - @Test - public void testMSModelUtils() { - HashMap classMap = new HashMap<>(); - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("DKaTVESPolicy-v1802.xmi").getFile()); - MSModelUtils utils = new MSModelUtils("http://org.onap", "http://org.onap.policy"); - Map tempMap = - utils.processEpackage(file.getAbsolutePath().toString(), MODEL_TYPE.XMI); - classMap.putAll(tempMap); - MSAttributeObject mainClass = classMap.get("StandardDeviationThreshold"); - String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[] {"[", "]", " "}, - new String[] {"", "", ""}); - List dependency = new ArrayList(Arrays.asList(dependTemp.split(","))); - dependency = utils.getFullDependencyList(dependency, classMap); - String subAttribute = utils.createSubAttributes(dependency, classMap, "StandardDeviationThreshold"); - assertTrue(subAttribute != null); - } - - - /** - * Run the void stringBetweenDots(String, String) method test. - */ - - @Test - public void testStringBetweenDots() { - - // expect: uniqueKeys should contain a string value - MSModelUtils controllerA = new MSModelUtils(); - String str = "testing\\.byCorrectWay\\.OfDATA"; - assertEquals(1, controllerA.stringBetweenDots(str)); - - // expect: uniqueKeys should not contain a string value - str = "testing\byWrongtWay.\\OfDATA"; - MSModelUtils controllerB = new MSModelUtils(); - assertEquals(0, controllerB.stringBetweenDots(str)); - } - - /** - * Run the Map load(String) method test. - */ - - @Test - public void testLoad() { - - boolean isLocalTesting = true; - MSModelUtils controller = new MSModelUtils(); - String fileName = null; - Map result = null; - try { - ClassLoader classLoader = getClass().getClassLoader(); - fileName = new File(classLoader.getResource("TESTMODEL-v1806.yml").getFile()).getAbsolutePath(); - } catch (Exception e1) { - logger.error("Exception Occured while loading file" + e1); - } - if (isLocalTesting) { - try { - result = controller.load(fileName); - } catch (IOException e) { - logger.error("testLoad", e); - result = null; - } catch (ParserException e) { - logger.error("testLoad", e); - } - - assertTrue(result != null && !result.isEmpty()); - logger.debug("result : " + result); - } - - logger.debug("testLoad: exit"); - } - - /** - * Run the void parseTosca(String) method test. - */ - - @Test - public void testParseTosca() { - - logger.debug("testParseTosca: enter"); - boolean isLocalTesting = true; - String fileName = null; - try { - ClassLoader classLoader = getClass().getClassLoader(); - fileName = new File(classLoader.getResource("TESTMODEL-v1806.yml").getFile()).getAbsolutePath(); - } catch (Exception e1) { - logger.error("Exception Occured while loading file" + e1); - } - - MSModelUtils controller = new MSModelUtils(commonClassDao); - if (isLocalTesting) { - try { - controller.parseTosca(fileName); - } catch (Exception e) { - fail("parseTosca caused error: " + e); - } - } - logger.debug("testParseTosca: exit"); - } - -} diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/util/MsAttributeObjectTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/util/MsAttributeObjectTest.java new file mode 100644 index 000000000..8ec47fb0b --- /dev/null +++ b/ONAP-REST/src/test/java/org/onap/policy/rest/util/MsAttributeObjectTest.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.rest.util; + +import static org.junit.Assert.assertTrue; + +import java.util.HashMap; + +import org.junit.Test; + +public class MsAttributeObjectTest { + + @Test + public void testMsAttributeObject() { + MsAttributeObject data = new MsAttributeObject(); + data.setClassName("Test"); + assertTrue("Test".equals(data.getClassName())); + data.setRefAttribute(new HashMap<>()); + assertTrue(data.getRefAttribute() != null); + data.setAttribute(new HashMap<>()); + assertTrue(data.getAttribute() != null); + data.setEnumType(new HashMap<>()); + assertTrue(data.getEnumType() != null); + data.addAttribute("test", "test"); + data.addRefAttribute("test", "test"); + data.addAllAttribute(new HashMap<>()); + data.addAllRefAttribute(new HashMap<>()); + data.setSubClass(new HashMap<>()); + assertTrue(data.getSubClass() != null); + data.addAllSubClass(new HashMap<>()); + data.setDependency("Test"); + assertTrue("Test".equals(data.getDependency())); + data.addSingleEnum("test", "test"); + data.setMatchingSet(new HashMap<>()); + assertTrue(data.getMatchingSet() != null); + data.addMatchingSet("test", "test"); + data.addMatchingSet(new HashMap<>()); + data.setPolicyTempalate(true); + assertTrue(data.isPolicyTempalate()); + data.setRuleFormation("ruleFormation"); + assertTrue(data.getRuleFormation() != null); + data.setDataOrderInfo("dataOrderInfo"); + assertTrue(data.getDataOrderInfo() != null); + } + + @Test + public void testMsAttributeValue() { + MsAttributeValue data = new MsAttributeValue(); + data.setName("Test"); + assertTrue("Test".equals(data.getName())); + data.setType("Test"); + assertTrue("Test".equals(data.getType())); + data.setRequired(true); + assertTrue(data.getRequired()); + data.setArrayValue(true); + assertTrue(data.getArrayValue()); + data.setDefaultValue("Test"); + assertTrue("Test".equals(data.getDefaultValue())); + } +} diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/util/MsModelUtilsTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/util/MsModelUtilsTest.java new file mode 100644 index 000000000..59115b959 --- /dev/null +++ b/ONAP-REST/src/test/java/org/onap/policy/rest/util/MsModelUtilsTest.java @@ -0,0 +1,167 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.rest.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.DictionaryData; +import org.onap.policy.rest.util.MsModelUtils.ModelType; + +public class MsModelUtilsTest { + private static Logger logger = FlexLogger.getLogger(MsModelUtilsTest.class); + private static CommonClassDao commonClassDao; + + /** + * Set tests up. + * + * @throws Exception on setup failures + */ + @Before + public void setUp() throws Exception { + List dictionaryData = new ArrayList(); + DictionaryData testData = new DictionaryData(); + testData.setDictionaryName("dictionaryName"); + testData.setDictionaryDataByName("dictionaryDataByName"); + dictionaryData.add(testData); + logger.info("setUp: Entering"); + commonClassDao = mock(CommonClassDao.class); + when(commonClassDao.getDataById(DictionaryData.class, "dictionaryName", "GocVNFType")) + .thenReturn(dictionaryData); + } + + @Test + public void testMsModelUtils() { + HashMap classMap = new HashMap<>(); + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("DKaTVESPolicy-v1802.xmi").getFile()); + MsModelUtils utils = new MsModelUtils("http://org.onap", "http://org.onap.policy"); + Map tempMap = utils.processEpackage(file.getAbsolutePath().toString(), + ModelType.XMI); + classMap.putAll(tempMap); + MsAttributeObject mainClass = classMap.get("StandardDeviationThreshold"); + String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[] + { "[", "]", " " }, new String[] + { "", "", "" }); + List dependency = new ArrayList(Arrays.asList(dependTemp.split(","))); + dependency = utils.getFullDependencyList(dependency, classMap); + String subAttribute = utils.createSubAttributes(dependency, classMap, "StandardDeviationThreshold"); + assertTrue(subAttribute != null); + } + + /** + * Run the void stringBetweenDots(String, String) method test. + */ + + @Test + public void testStringBetweenDots() { + + // expect: uniqueKeys should contain a string value + MsModelUtils controllerA = new MsModelUtils(); + String str = "testing\\.byCorrectWay\\.OfDATA"; + assertEquals(1, controllerA.stringBetweenDots(str)); + + // expect: uniqueKeys should not contain a string value + str = "testing\byWrongtWay.\\OfDATA"; + MsModelUtils controllerB = new MsModelUtils(); + assertEquals(0, controllerB.stringBetweenDots(str)); + } + + /** + * Run the load method test. + */ + @Test + public void testLoad() { + + boolean isLocalTesting = true; + MsModelUtils controller = new MsModelUtils(); + String fileName = null; + Map result = null; + try { + ClassLoader classLoader = getClass().getClassLoader(); + fileName = new File(classLoader.getResource("TESTMODEL-v1806.yml").getFile()).getAbsolutePath(); + } catch (Exception e1) { + logger.error("Exception Occured while loading file" + e1); + } + if (isLocalTesting) { + try { + result = controller.load(fileName); + } catch (IOException e) { + logger.error("testLoad", e); + result = null; + } catch (ParserException e) { + logger.error("testLoad", e); + } + + assertTrue(result != null && !result.isEmpty()); + logger.debug("result : " + result); + } + + logger.debug("testLoad: exit"); + } + + /** + * Run the void parseTosca(String) method test. + */ + + @Test + public void testParseTosca() { + + logger.debug("testParseTosca: enter"); + boolean isLocalTesting = true; + String fileName = null; + try { + ClassLoader classLoader = getClass().getClassLoader(); + fileName = new File(classLoader.getResource("TESTMODEL-v1806.yml").getFile()).getAbsolutePath(); + } catch (Exception e1) { + logger.error("Exception Occured while loading file" + e1); + } + + MsModelUtils controller = new MsModelUtils(commonClassDao); + if (isLocalTesting) { + try { + controller.parseTosca(fileName); + } catch (Exception e) { + fail("parseTosca caused error: " + e); + } + } + logger.debug("testParseTosca: exit"); + } + +} diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/util/PDPPolicyContainerTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/util/PDPPolicyContainerTest.java deleted file mode 100644 index 9302df3b5..000000000 --- a/ONAP-REST/src/test/java/org/onap/policy/rest/util/PDPPolicyContainerTest.java +++ /dev/null @@ -1,138 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.policy.rest.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import java.util.HashSet; -import java.util.Set; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.rest.util.PDPPolicyContainer.PDPPolicyItem; -import org.onap.policy.xacml.std.pap.StdPDP; -import org.onap.policy.xacml.std.pap.StdPDPGroup; -import org.onap.policy.xacml.std.pap.StdPDPPolicy; -import com.att.research.xacml.api.pap.PDP; -import com.att.research.xacml.api.pap.PDPPolicy; - -public class PDPPolicyContainerTest { - StdPDPGroup group; - PDPPolicyContainer container; - StdPDPPolicy policy; - - @Before - public void setUp() { - group = new StdPDPGroup(); - group.setDefault(true); - group.setDefaultGroup(true); - group.setDescription("Test"); - group.setId("Test"); - group.setName("Test"); - group.setOnapPdps(new HashSet<>()); - group.setOperation("Test"); - group.setPipConfigs(new HashSet<>()); - HashSet policies = new HashSet<>(); - policy = new StdPDPPolicy(); - policy.setName("Config_test.1.xml"); - policy.setId("Config_test"); - policy.setVersion("1.0"); - policy.setDescription("testDescription"); - policies.add(policy); - group.setPolicies(policies); - group.setSelectedPolicies(new HashSet<>()); - container = new PDPPolicyContainer(group); - } - - @Test - public void testPDPPolicyContainer() { - container.nextItemId(policy); - container.prevItemId(policy); - container.firstItemId(); - container.lastItemId(); - container.isFirstId(policy); - container.isLastId(policy); - container.addItemAfter(policy); - container.getContainerPropertyIds(); - container.getItemIds(); - container.getType("Id"); - assertTrue(String.class.equals(String.class)); - container.getType("Name"); - assertTrue(String.class.equals(String.class)); - container.getType("Version"); - assertTrue(String.class.equals(String.class)); - container.getType("Description"); - assertTrue(String.class.equals(String.class)); - container.getType("Root"); - assertTrue(Boolean.class.equals(Boolean.class)); - assertTrue(container.size() == 1); - container.containsId(policy); - container.removeItem(policy); - container.addContainerProperty(null, null, null); - container.removeContainerProperty(policy); - container.removeAllItems(); - container.addItemAt(0); - } - - @Test(expected = NullPointerException.class) - public void testConstructor() { - // Test PDP based constructor - PDP pdp = new StdPDP(); - PDPPolicyContainer container1 = new PDPPolicyContainer(pdp); - assertNotNull(container1); - - // Test set based constructor - Set set = new HashSet(); - PDPPolicyContainer container2 = new PDPPolicyContainer(set); - assertNotNull(container2); - - // Test object based constructor - PDPPolicyContainer container3 = new PDPPolicyContainer("testObject"); - assertNotNull(container3); - } - - @Test(expected = UnsupportedOperationException.class) - public void testAddItem() { - container.addItem(); - } - - @Test - public void testGetters() { - assertNull(container.nextItemId("testItem")); - assertNull(container.prevItemId("testItem")); - assertNotNull(container.firstItemId()); - assertNotNull(container.lastItemId()); - assertEquals(container.indexOfId("testItem"), -1); - assertNotNull(container.getIdByIndex(0)); - assertNotNull(container.getItemIds(0, 1)); - } - - @Test - public void testPDPPolicyItem() { - PDPPolicyItem item = container.new PDPPolicyItem(policy); - assertEquals("Config_test", item.getId()); - assertEquals("Config_test.1.xml", item.getName()); - assertEquals("1.0", item.getVersion()); - assertEquals("testDescription", item.getDescription()); - item.setRoot(true); - assertEquals(true, item.getRoot()); - } -} diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/util/ParserExceptionTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/util/ParserExceptionTest.java new file mode 100644 index 000000000..92b56a146 --- /dev/null +++ b/ONAP-REST/src/test/java/org/onap/policy/rest/util/ParserExceptionTest.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.rest.util; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class ParserExceptionTest { + + @Test + public void test() { + ParserException pe = new ParserException("A Message"); + assertEquals("A Message", pe.getMessage()); + } +} diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/util/PdpPolicyContainerTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/util/PdpPolicyContainerTest.java new file mode 100644 index 000000000..32d9e5255 --- /dev/null +++ b/ONAP-REST/src/test/java/org/onap/policy/rest/util/PdpPolicyContainerTest.java @@ -0,0 +1,267 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.rest.util; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFLogger.Level; +import com.att.eelf.configuration.EELFManager; +import com.att.research.xacml.api.pap.PDP; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.rest.util.PdpPolicyContainer.PdpPolicyItem; +import org.onap.policy.xacml.std.pap.StdPDP; +import org.onap.policy.xacml.std.pap.StdPDPGroup; +import org.onap.policy.xacml.std.pap.StdPDPPolicy; + +public class PdpPolicyContainerTest { + StdPDPGroup group; + PdpPolicyContainer container; + StdPDPPolicy policy; + + /** + * Set test up. + */ + @Before + public void setUp() { + group = new StdPDPGroup(); + group.setDefault(true); + group.setDefaultGroup(true); + group.setDescription("Test"); + group.setId("Test"); + group.setName("Test"); + group.setOnapPdps(new HashSet<>()); + group.setOperation("Test"); + group.setPipConfigs(new HashSet<>()); + policy = new StdPDPPolicy(); + policy.setName("Config_test.1.xml"); + policy.setId("Config_test"); + policy.setVersion("1.0"); + policy.setDescription("testDescription"); + + HashSet policies = new HashSet<>(); + policies.add(policy); + group.setPolicies(policies); + group.setSelectedPolicies(new HashSet<>()); + container = new PdpPolicyContainer(group); + } + + @Test + public void testPdpPolicyContainer() { + container.nextItemId(policy); + container.prevItemId(policy); + container.firstItemId(); + container.lastItemId(); + container.isFirstId(policy); + container.isLastId(policy); + container.addItemAfter(policy); + container.getContainerPropertyIds(); + container.getItemIds(); + container.getType("Id"); + assertNull(container.getType("NonExistant")); + assertTrue(String.class.equals(String.class)); + container.getType("Name"); + assertTrue(String.class.equals(String.class)); + container.getType("Version"); + assertTrue(String.class.equals(String.class)); + container.getType("Description"); + assertTrue(String.class.equals(String.class)); + container.getType("Root"); + assertTrue(Boolean.class.equals(Boolean.class)); + assertTrue(container.size() == 1); + container.containsId(policy); + container.removeItem(policy); + container.addContainerProperty(null, null, null); + container.removeContainerProperty(policy); + container.removeAllItems(); + + assertFalse(container.isFirstId(policy)); + assertFalse(container.isLastId(policy)); + assertNull(container.firstItemId()); + assertNull(container.lastItemId()); + assertNull(container.prevItemId(policy)); + + assertThatThrownBy(() -> container.getItemIds(0, -1)).isInstanceOf(IllegalArgumentException.class); + + container.addItemAt(0); + } + + @Test + public void testPdpPolicyContainerWithTrace() { + EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger(); + + final Level currentLevel = PolicyLogger.getDebugLevel(); + debugLogger.setLevel(Level.TRACE); + + testPdpPolicyContainer(); + debugLogger.setLevel(currentLevel); + } + + @Test(expected = NullPointerException.class) + public void testConstructor() { + // Test PDP based constructor + PDP pdp = new StdPDP(); + PdpPolicyContainer container1 = new PdpPolicyContainer(pdp); + assertNotNull(container1); + + // Test set based constructor + Set set = new HashSet(); + PdpPolicyContainer container2 = new PdpPolicyContainer(set); + assertNotNull(container2); + + // Test object based constructor + PdpPolicyContainer container3 = new PdpPolicyContainer("testObject"); + assertNotNull(container3); + } + + @Test(expected = UnsupportedOperationException.class) + public void testAddItem() { + container.addItem(); + } + + @Test + public void testGettersWithTrace() { + EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger(); + + final Level currentLevel = PolicyLogger.getDebugLevel(); + debugLogger.setLevel(Level.TRACE); + + testGetters(); + debugLogger.setLevel(currentLevel); + } + + @Test + public void testGetters() { + assertNull(container.nextItemId("testItem")); + assertNull(container.prevItemId("testItem")); + assertNotNull(container.firstItemId()); + assertNotNull(container.lastItemId()); + assertEquals(container.indexOfId("testItem"), -1); + assertNotNull(container.getIdByIndex(0)); + assertNotNull(container.getItemIds(0, 1)); + } + + @Test + public void testPdpPolicyItemWithTrace() { + EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger(); + + final Level currentLevel = PolicyLogger.getDebugLevel(); + debugLogger.setLevel(Level.TRACE); + + testPdpPolicyItem(); + debugLogger.setLevel(currentLevel); + } + + @Test + public void testPdpPolicyItem() { + PdpPolicyItem item = container.new PdpPolicyItem(policy); + assertEquals("Config_test", item.getId()); + assertEquals("Config_test.1.xml", item.getName()); + assertEquals("1.0", item.getVersion()); + assertEquals("testDescription", item.getDescription()); + item.setRoot(true); + assertEquals(true, item.getRoot()); + } + + @Test + public void testContainerListOfPolicies() { + StdPDPGroup testGroup = new StdPDPGroup(); + testGroup.setDefault(true); + testGroup.setDefaultGroup(true); + testGroup.setDescription("Test"); + testGroup.setId("Test"); + testGroup.setName("Test"); + testGroup.setOnapPdps(new HashSet<>()); + testGroup.setOperation("Test"); + testGroup.setPipConfigs(new HashSet<>()); + + StdPDPPolicy testPolicy0 = new StdPDPPolicy(); + testPolicy0.setName("Config_test.0.xml"); + testPolicy0.setId("Config_test0"); + testPolicy0.setVersion("1.0"); + testPolicy0.setDescription("testDescription0"); + + StdPDPPolicy testPolicy1 = new StdPDPPolicy(); + testPolicy1.setName("Config_test.1.xml"); + testPolicy1.setId("Config_test1"); + testPolicy1.setVersion("1.0"); + testPolicy1.setDescription("testDescription1"); + + HashSet policies = new HashSet<>(); + policies.add(testPolicy0); + policies.add(testPolicy1); + + testGroup.setPolicies(policies); + testGroup.setSelectedPolicies(new HashSet<>()); + PdpPolicyContainer testContainer = new PdpPolicyContainer(testGroup); + + assertEquals("Config_test0", ((PdpPolicyItem) testContainer.nextItemId(testPolicy1)).getId()); + assertEquals("Config_test1", ((PdpPolicyItem) testContainer.prevItemId(testPolicy0)).getId()); + + ObjectMapper mapper = new ObjectMapper(); + try { + mapper.writeValue(System.err, testPolicy0); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + // @formatter:off + assertTrue(testContainer.removeItem("{" + + "\"PDPPolicyType\":\"StdPDPPolicy\"," + + "\"id\":\"Config_test0\"," + + "\"name\":\"Config_test.0.xml\"," + + "\"policyId\":null," + + "\"description\":\"testDescription0\"," + + "\"version\":\"1.0\"," + + "\"location\":null," + + "\"valid\":false," + + "\"root\":false" + + "}")); + assertFalse(testContainer.removeItem("{" + + "\"PDPPolicyType\":\"StdPDPPolicy\"," + + "\"id\":\"Config_test99\"," + + "\"name\":\"Config_test.0.xml\"," + + "\"policyId\":null," + + "\"description\":\"testDescription0\"," + + "\"version\":\"1.0\"," + + "\"location\":null," + + "\"valid\":false," + + "\"root\":false" + + "}")); + // @formatter:on + } +} diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyItemSetChangeNotifierTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyItemSetChangeNotifierTest.java index 9e5ff5d9f..5e42ec6f6 100644 --- a/ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyItemSetChangeNotifierTest.java +++ b/ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyItemSetChangeNotifierTest.java @@ -3,13 +3,14 @@ * ONAP Policy Engine * ================================================================================ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,31 +21,57 @@ package org.onap.policy.rest.util; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; + import org.junit.Test; import org.mockito.Mockito; import org.onap.policy.rest.util.PolicyContainer.ItemSetChangeEvent; import org.onap.policy.rest.util.PolicyContainer.ItemSetChangeListener; public class PolicyItemSetChangeNotifierTest { - @Test - public void testNotifier() { - // Setup test data - ItemSetChangeListener listener = Mockito.mock(ItemSetChangeListener.class); - ItemSetChangeEvent event = Mockito.mock(ItemSetChangeEvent.class); - - // Test constructor - PolicyItemSetChangeNotifier notifier = new PolicyItemSetChangeNotifier(); - assertNotNull(notifier); - - // Test listener methods - try { - notifier.addItemSetChangeListener(listener); - notifier.fireItemSetChange(event); - notifier.removeItemSetChangeListener(listener); - } catch (Exception ex) { - fail("Not expecting any exceptions: " + ex); + @Test + public void testNotifier() { + + // Test constructor + PolicyItemSetChangeNotifier notifier = new PolicyItemSetChangeNotifier(); + assertNotNull(notifier); + + assertEquals(null, notifier.getItemSetChangeListeners()); + + ItemSetChangeListener listener1 = Mockito.mock(ItemSetChangeListener.class); + notifier.addItemSetChangeListener(listener1); + assertEquals(1, notifier.getItemSetChangeListeners().size()); + ItemSetChangeListener listener2 = Mockito.mock(ItemSetChangeListener.class); + notifier.addItemSetChangeListener(listener2); + assertEquals(2, notifier.getItemSetChangeListeners().size()); + + notifier.removeItemSetChangeListener(listener1); + assertEquals(1, notifier.getItemSetChangeListeners().size()); + notifier.addItemSetChangeListener(listener1); + assertEquals(2, notifier.getItemSetChangeListeners().size()); + + ItemSetChangeEvent event = Mockito.mock(ItemSetChangeEvent.class); + notifier.fireItemSetChange(event); + + notifier.removeItemSetChangeListener(listener1); + assertEquals(1, notifier.getItemSetChangeListeners().size()); + notifier.removeItemSetChangeListener(listener2); + assertEquals(0, notifier.getItemSetChangeListeners().size()); + notifier.removeItemSetChangeListener(listener2); + assertEquals(0, notifier.getItemSetChangeListeners().size()); + + notifier.setItemSetChangeListeners(null); + notifier.removeItemSetChangeListener(listener2); + assertEquals(null, notifier.getItemSetChangeListeners()); + + assertThatCode(() -> notifier.fireItemSetChange(event)).doesNotThrowAnyException(); + + notifier.setContainer(new DummyPolicyContainer()); + assertThatCode(() -> notifier.fireItemSetChange()).doesNotThrowAnyException(); + + PolicyContainer dummySource = new DummyPolicyContainer(); + assertEquals(dummySource, new PolicyItemSetChangeNotifier.BaseItemSetChangeEvent(dummySource).getContainer()); } - } } diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyValidationTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyValidationTest.java index 6051db4c3..47b0f49b5 100644 --- a/ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyValidationTest.java +++ b/ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyValidationTest.java @@ -3,13 +3,14 @@ * ONAP-REST * ================================================================================ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,12 +18,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.rest.util; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; + import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; + import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -41,9 +46,7 @@ public class PolicyValidationTest { } @Test - public void microServicePolicyTests() throws Exception{ - PolicyValidation validation = new PolicyValidation(); - PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper(); + public void microServicePolicyTests() throws Exception { PolicyParameters policyParameters = new PolicyParameters(); policyParameters.setPolicyConfigType(PolicyConfigType.MicroService); @@ -51,8 +54,20 @@ public class PolicyValidationTest { policyParameters.setPolicyDescription("This is a sample Micro Service policy Create example"); policyParameters.setOnapName("DCAE"); policyParameters.setPriority("1"); - String MSjsonString = "{\"service\":\"TOSCA_namingJenny\",\"location\":\"Test DictMSLoc\",\"uuid\":\"testDict DCAEUIID\",\"policyName\":\"testModelValidation\",\"description\":\"test\",\"configName\":\"testDict MSConfName\",\"templateVersion\":\"1607\",\"version\":\"gw12181031\",\"priority\":\"5\",\"policyScope\":\"resource=ResourcetypeVenktest1,service=ServiceName1707,type=Name1707,closedLoopControlName=Retest_retest1\",\"riskType\":\"Test\",\"riskLevel\":\"3\",\"guard\":\"True\",\"content\":{\"police-instance-name\":\"testing\",\"naming-models\":[{\"naming-properties\":[{\"property-value\":\"test\",\"source-endpoint\":\"test\",\"property-name\":\"testPropertyname\",\"increment-sequence\":{\"scope\":\"VNF\",\"start-value\":\"1\",\"length\":\"3\",\"increment\":\"2\"},\"source-system\":\"TOSCA\"}],\"naming-type\":\"testNamingType\",\"naming-recipe\":\"testNamingRecipe\"}]}}";; - policyParameters.setConfigBody(MSjsonString); + String msJsonString = "{\"service\":\"TOSCA_namingJenny\",\"location\":\"Test DictMSLoc\"," + + "\"uuid\":\"testDict DCAEUIID\",\"policyName\":\"testModelValidation\"," + + "\"description\":\"test\",\"configName\":\"testDict MSConfName\"," + + "\"templateVersion\":\"1607\",\"version\":\"gw12181031\",\"priority\":\"5\"," + + "\"policyScope\":\"resource=ResourcetypeVenktest1,service=ServiceName1707,type=Name1707," + + "closedLoopControlName=Retest_retest1\",\"riskType\":\"Test\",\"riskLevel\":\"3\"," + + "\"guard\":\"True\",\"content\":{\"police-instance-name\":\"testing\"," + + "\"naming-models\":[{\"naming-properties\":[{\"property-value\":\"test\"," + + "\"source-endpoint\":\"test\",\"property-name\":\"testPropertyname\"," + + "\"increment-sequence\":{\"scope\":\"VNF\",\"start-value\":\"1\",\"length\":\"3\"," + + "\"increment\":\"2\"},\"source-system\":\"TOSCA\"}],\"naming-type\":\"testNamingType\"," + + "\"naming-recipe\":\"testNamingRecipe\"}]}}"; + ; + policyParameters.setConfigBody(msJsonString); policyParameters.setRequestID(UUID.randomUUID()); SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy"); Date date = dateformat3.parse("15/10/2016"); @@ -62,8 +77,9 @@ public class PolicyValidationTest { policyParameters.setRiskType("TEST"); policyParameters.setRequestID(UUID.randomUUID()); - + PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper(); PolicyRestAdapter policyData = wrapper.populateRequestParameters(policyParameters); + PolicyValidation validation = new PolicyValidation(); StringBuilder responseString = validation.validatePolicy(policyData); assertNotSame("success", responseString.toString()); -- cgit 1.2.3-korg