Policies import when import VSP 61/101561/11
authorDmitry Puzikov <dmitry.puzikov@tieto.com>
Tue, 28 Jan 2020 17:04:40 +0000 (18:04 +0100)
committerDmitry Puzikov <d.puzikov2@partner.samsung.com>
Tue, 25 Feb 2020 09:11:49 +0000 (10:11 +0100)
Polices import implemented.

Error type added for invalid policies.

Import tests added.

Fix test failures.

Got rid of Either in the new code.

Change-Id: I3e91cc6d24433c2b3862f407348e71e1e67c3b4e
Issue-ID: SDC-2728
Signed-off-by: Dmitry Puzikov <d.puzikov2@partner.samsung.com>
19 files changed:
catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/YamlTemplateParsingHandler.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/PropertiesUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/GroupExportParserImpl.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PolicyExportParserImpl.java
catalog-be/src/main/resources/config/error-configuration.yaml
catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java
catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java
catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java
catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/YamlTemplateParsingHandlerTest.java
catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java
catalog-be/src/test/resources/config/catalog-be/error-configuration.yaml
catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ActionStatus.java
catalog-model/src/main/java/org/openecomp/sdc/be/model/ParsedToscaYamlInfo.java
catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCache.java
catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCacheTest.java
common-be/src/main/java/org/openecomp/sdc/be/utils/TypeUtils.java

index b86348d..41dc3a6 100644 (file)
@@ -25,6 +25,9 @@ import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 import com.google.gson.Gson;
 import fj.data.Either;
+import java.util.Collections;
+import java.util.EnumMap;
+import java.util.Objects;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections.MapUtils;
 import org.apache.commons.lang.StringUtils;
@@ -32,12 +35,15 @@ import org.openecomp.sdc.be.components.impl.AnnotationBusinessLogic;
 import org.openecomp.sdc.be.components.impl.GroupTypeBusinessLogic;
 import org.openecomp.sdc.be.components.impl.ImportUtils;
 import org.openecomp.sdc.be.components.impl.NodeFilterUploadCreator;
+import org.openecomp.sdc.be.components.impl.PolicyTypeBusinessLogic;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
+import org.openecomp.sdc.be.components.utils.PropertiesUtils;
 import org.openecomp.sdc.be.config.BeEcompErrorManager;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao;
 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
 import org.openecomp.sdc.be.model.CapabilityDefinition;
 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
@@ -46,6 +52,8 @@ import org.openecomp.sdc.be.model.GroupTypeDefinition;
 import org.openecomp.sdc.be.model.InputDefinition;
 import org.openecomp.sdc.be.model.NodeTypeInfo;
 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
+import org.openecomp.sdc.be.model.PolicyDefinition;
+import org.openecomp.sdc.be.model.PolicyTypeDefinition;
 import org.openecomp.sdc.be.model.UploadArtifactInfo;
 import org.openecomp.sdc.be.model.UploadCapInfo;
 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
@@ -85,9 +93,11 @@ import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.IS_PASSWORD
 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.MEMBERS;
 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.NODE;
 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.NODE_TEMPLATES;
+import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.POLICIES;
 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.PROPERTIES;
 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.REQUIREMENTS;
 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS;
+import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.TARGETS;
 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE;
 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.TYPE;
 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES;
@@ -108,12 +118,14 @@ public class YamlTemplateParsingHandler {
     private JanusGraphDao janusGraphDao;
     private GroupTypeBusinessLogic groupTypeBusinessLogic;
     private AnnotationBusinessLogic annotationBusinessLogic;
+    private PolicyTypeBusinessLogic policyTypeBusinessLogic;
 
-    public YamlTemplateParsingHandler(JanusGraphDao janusGraphDao,
-                                      GroupTypeBusinessLogic groupTypeBusinessLogic, AnnotationBusinessLogic annotationBusinessLogic) {
+    public YamlTemplateParsingHandler(JanusGraphDao janusGraphDao, GroupTypeBusinessLogic groupTypeBusinessLogic,
+            AnnotationBusinessLogic annotationBusinessLogic, PolicyTypeBusinessLogic policyTypeBusinessLogic) {
         this.janusGraphDao = janusGraphDao;
         this.groupTypeBusinessLogic = groupTypeBusinessLogic;
         this.annotationBusinessLogic = annotationBusinessLogic;
+        this.policyTypeBusinessLogic = policyTypeBusinessLogic;
     }
 
     public ParsedToscaYamlInfo parseResourceInfoFromYAML(String fileName, String resourceYml, Map<String, String> createdNodesToscaResourceNames,
@@ -128,6 +140,7 @@ public class YamlTemplateParsingHandler {
         parsedToscaYamlInfo.setInputs(getInputs(mappedToscaTemplate));
         parsedToscaYamlInfo.setInstances(getInstances(fileName, mappedToscaTemplate, createdNodesToscaResourceNames));
         parsedToscaYamlInfo.setGroups(getGroups(fileName, mappedToscaTemplate));
+        parsedToscaYamlInfo.setPolicies(getPolicies(fileName, mappedToscaTemplate));
         log.debug("#parseResourceInfoFromYAML - The yaml {} has been parsed ", fileName);
         return parsedToscaYamlInfo;
     }
@@ -165,6 +178,110 @@ public class YamlTemplateParsingHandler {
         return inputs;
     }
 
+    private Map<String, PolicyDefinition> getPolicies(String fileName, Map<String, Object> toscaJson) {
+
+        Map<String, Object> foundPolicies = findFirstToscaMapElement(toscaJson, POLICIES)
+                                                  .left()
+                                                  .on(err -> logPoliciesNotFound(fileName));
+
+        if (MapUtils.isNotEmpty(foundPolicies)) {
+            return foundPolicies
+                           .entrySet()
+                           .stream()
+                           .map(this::createPolicy)
+                           .collect(Collectors.toMap(PolicyDefinition::getName, p -> p));
+        }
+        return Collections.emptyMap();
+    }
+
+    private PolicyDefinition createPolicy(Map.Entry<String, Object> policyNameValue) {
+        PolicyDefinition emptyPolicyDef = new PolicyDefinition();
+        String policyName = policyNameValue.getKey();
+        emptyPolicyDef.setName(policyName);
+        try {
+            if (policyNameValue.getValue() != null && policyNameValue.getValue() instanceof Map) {
+                Map<String, Object> policyTemplateJsonMap = (Map<String, Object>) policyNameValue.getValue();
+                validateAndFillPolicy(emptyPolicyDef, policyTemplateJsonMap);
+            } else {
+                rollbackWithException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
+            }
+        } catch (ClassCastException e) {
+            log.debug("#createPolicy - Failed to create the policy {}. The exception occurred", policyName, e);
+            rollbackWithException(ActionStatus.INVALID_YAML);
+        }
+        return emptyPolicyDef;
+    }
+
+    private Map<String, Object> logPoliciesNotFound(String fileName) {
+        log.debug("#logPoliciesNotFound - Policies were not found in the yaml template {}.", fileName);
+        return Collections.emptyMap();
+    }
+
+    private void validateAndFillPolicy(PolicyDefinition emptyPolicyDefinition, Map<String, Object> policyTemplateJsonMap) {
+        String policyTypeName = (String) policyTemplateJsonMap.get(TYPE.getElementName());
+        if(StringUtils.isEmpty(policyTypeName)){
+            log.debug("#validateAndFillPolicy - The 'type' member is not found under policy {}", emptyPolicyDefinition.getName());
+            rollbackWithException(ActionStatus.POLICY_MISSING_POLICY_TYPE, emptyPolicyDefinition.getName());
+        }
+        emptyPolicyDefinition.setType(policyTypeName);
+        // set policy targets
+        emptyPolicyDefinition.setTargets(validateFillPolicyTargets(policyTemplateJsonMap));
+        PolicyTypeDefinition policyTypeDefinition = validateGetPolicyTypeDefinition(policyTypeName);
+        // set policy properties
+        emptyPolicyDefinition.setProperties(validateFillPolicyProperties(policyTypeDefinition, policyTemplateJsonMap));
+    }
+
+    private PolicyTypeDefinition validateGetPolicyTypeDefinition(String policyType) {
+        PolicyTypeDefinition policyTypeDefinition = policyTypeBusinessLogic.getLatestPolicyTypeByType(policyType);
+        if (policyTypeDefinition == null) {
+            log.debug("#validateAndFillPolicy - The policy type {} not found", policyType);
+            rollbackWithException(ActionStatus.POLICY_TYPE_IS_INVALID, policyType);
+        }
+        return policyTypeDefinition;
+    }
+
+    private List<PropertyDataDefinition> validateFillPolicyProperties(PolicyTypeDefinition policyTypeDefinition,
+            Map<String, Object> policyTemplateJsonMap) {
+        if (MapUtils.isEmpty(policyTemplateJsonMap) || Objects.isNull(policyTypeDefinition)) {
+            return Collections.emptyList();
+        }
+        List<PropertyDataDefinition> propertyDataDefinitionList = new ArrayList<>();
+        Map<String, Object> propertiesMap =
+                (Map<String, Object>) policyTemplateJsonMap.get(PROPERTIES.getElementName());
+        if (MapUtils.isEmpty(propertiesMap)) {
+            return Collections.emptyList();
+        }
+        if (CollectionUtils.isNotEmpty(policyTypeDefinition.getProperties())) {
+            propertyDataDefinitionList = policyTypeDefinition
+                                                 .getProperties()
+                                                 .stream()
+                                                 .map(propertyDefinition -> setPropertyValue(propertiesMap,
+                                                         propertyDefinition))
+                                                 .collect(Collectors.toList());
+        }
+        return propertyDataDefinitionList;
+    }
+
+    private PropertyDataDefinition setPropertyValue(Map<String, Object> propertiesMap, PropertyDataDefinition srcPropertyDataDefinition) {
+        PropertyDataDefinition newPropertyDef = new PropertyDataDefinition(srcPropertyDataDefinition);
+        String propertyName = newPropertyDef.getName();
+        if (Objects.nonNull(propertiesMap.get(propertyName))) {
+            Object propValue = propertiesMap.get(propertyName);
+            newPropertyDef.setValue(PropertiesUtils.trimQuotes(gson.toJson(propValue)));
+        }
+        return newPropertyDef;
+    }
+
+    private Map<PolicyTargetType, List<String>> validateFillPolicyTargets(Map<String, Object> policyTemplateJson) {
+        Map<PolicyTargetType, List<String>> targets = new EnumMap<>(PolicyTargetType.class);
+        if (policyTemplateJson.containsKey(TARGETS.getElementName())
+                    && policyTemplateJson.get(TARGETS.getElementName()) instanceof List ) {
+            List<String> targetsElement = (List<String>) policyTemplateJson.get(TARGETS.getElementName());
+            targets.put(PolicyTargetType.COMPONENT_INSTANCES, targetsElement);
+        }
+        return targets;
+    }
+
     private Map<String, UploadComponentInstanceInfo> getInstances(String yamlName, Map<String, Object> toscaJson, Map<String, String> createdNodesToscaResourceNames) {
 
         Map<String, Object> nodeTemlates = findFirstToscaMapElement(toscaJson, NODE_TEMPLATES)
index 2d0ee0d..f872074 100644 (file)
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.EnumMap;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang.StringUtils;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
 import org.openecomp.sdc.be.components.property.PropertyDeclarationOrchestrator;
@@ -32,9 +36,11 @@ import org.openecomp.sdc.be.datatypes.elements.GetPolicyValueDataDefinition;
 import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
 import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum;
 import org.openecomp.sdc.be.model.Component;
 import org.openecomp.sdc.be.model.ComponentInstInputsMap;
+import org.openecomp.sdc.be.model.ComponentInstance;
 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
 import org.openecomp.sdc.be.model.ComponentParametersView;
 import org.openecomp.sdc.be.model.PolicyDefinition;
@@ -49,6 +55,9 @@ import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
 import org.openecomp.sdc.common.datastructure.Wrapper;
+import org.openecomp.sdc.common.log.elements.LoggerSupportability;
+import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
+import org.openecomp.sdc.common.log.enums.StatusCode;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -76,6 +85,7 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
     private static final String FAILED_TO_VALIDATE_COMPONENT = "#{} - failed to validate the component {} before policy processing. ";
     private static final String DECLARE_PROPERTIES_TO_POLICIES = "declare properties to policies";
     private static final Logger log = Logger.getLogger(PolicyBusinessLogic.class);
+    private static final LoggerSupportability loggerSupportability= LoggerSupportability.getLogger(PolicyBusinessLogic.class.getName());
 
     private PropertyDeclarationOrchestrator propertyDeclarationOrchestrator;
 
@@ -123,6 +133,85 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
         }
     }
 
+    public Map<String, PolicyDefinition> createPoliciesFromParsedCsar(Component component,
+            final Map<String, PolicyDefinition> incomingPolicyDefinitions) {
+        if (MapUtils.isEmpty(incomingPolicyDefinitions)) {
+            return Collections.emptyMap();
+        }
+        Map<String, PolicyDefinition> createdPolicies = new HashMap<>();
+        for (Map.Entry<String, PolicyDefinition> policyEntry : incomingPolicyDefinitions.entrySet()) {
+            PolicyDefinition incomingPolicyDefinition = policyEntry.getValue();
+            String policyName = incomingPolicyDefinition.getName();
+            log.trace("Going to create policy {}", incomingPolicyDefinition);
+            loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(),
+                    StatusCode.STARTED,"Start to create policy: {} for component {}", policyName, component.getName());
+            String policyType = incomingPolicyDefinition.getType();
+            if (StringUtils.isEmpty(policyType)) {
+                log.debug("Policy type '{}' for policy '{}' not found.", policyType, policyName);
+                throw new ByActionStatusComponentException(ActionStatus.POLICY_MISSING_POLICY_TYPE, policyName);
+            }
+            // create policyDefinition
+            String policyTypeName = incomingPolicyDefinition.getPolicyTypeName();
+            PolicyDefinition createdPolicyDefinition = createPolicy(policyTypeName, component);
+            // set isFromCsar
+            createdPolicyDefinition.setToscaPresentationValue(JsonPresentationFields.IS_FROM_CSAR, true);
+            // link policy to component
+            component.addPolicy(createdPolicyDefinition);
+            // process targets
+            Map<PolicyTargetType, List<String>> policyTargets = incomingPolicyDefinition.getTargets();
+            createdPolicyDefinition = setUpdatePolicyTargets(component, createdPolicyDefinition, policyTargets);
+            // process policy properties
+            List<PropertyDataDefinition> properties = incomingPolicyDefinition.getProperties();
+            createdPolicyDefinition = setUpdatePolicyProperties(component, createdPolicyDefinition, properties);
+            createdPolicies.put(policyName, createdPolicyDefinition);
+            loggerSupportability.log(LoggerSupportabilityActions.CREATE_POLICIES,component.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,"policy {} has been created ", policyName);
+        }
+        return createdPolicies;
+    }
+
+    private PolicyDefinition setUpdatePolicyProperties(Component component, PolicyDefinition policyDefinition, List<PropertyDataDefinition> properties) {
+        if (CollectionUtils.isNotEmpty(properties)) {
+            PropertyDataDefinition[] propertiesArray = properties.toArray(new PropertyDataDefinition[properties.size()]);
+            List<PropertyDataDefinition> updatedPropertiesList = setComponentValidateUpdatePolicyProperties(
+                    policyDefinition.getUniqueId(),
+                    propertiesArray,
+                    component
+            );
+            policyDefinition.setProperties(updatedPropertiesList);
+        }
+        return policyDefinition;
+    }
+
+    private PolicyDefinition setUpdatePolicyTargets(Component component, PolicyDefinition policyDefinition,
+            Map<PolicyTargetType, List<String>> targets) {
+        if (MapUtils.isEmpty(targets)) {
+            return policyDefinition;
+        }
+        List<String> targetsToUpdate = targets.get(PolicyTargetType.COMPONENT_INSTANCES);
+        if (CollectionUtils.isEmpty(targetsToUpdate)) {
+            return policyDefinition;
+        }
+        // update targets to uniqueIds of respective component instance
+        List<String> targetsUniqueIds = new ArrayList<>();
+        for (String targetName : targetsToUpdate) {
+            Optional<ComponentInstance> componentInstance = component.getComponentInstanceByName(targetName);
+            String componentUniqueId = componentInstance
+                                               .orElseThrow(
+                                                       () -> new ByActionStatusComponentException(
+                                                               ActionStatus.COMPONENT_INSTANCE_NOT_FOUND
+                                                       )
+                                               )
+                                               .getUniqueId();
+            targetsUniqueIds.add(componentUniqueId);
+        }
+        EnumMap<PolicyTargetType, List<String>> updatedTargets = new EnumMap<>(PolicyTargetType.class);
+        updatedTargets.put(PolicyTargetType.COMPONENT_INSTANCES, targetsUniqueIds);
+        policyDefinition.setTargets(updatedTargets);
+        policyDefinition = validateAndUpdatePolicyTargets(component, policyDefinition.getUniqueId(),
+                policyDefinition.getTargets());
+        return policyDefinition;
+    }
+
     /*public Either<PolicyDefinition, ResponseFormat> createPolicy(ComponentTypeEnum componentType, String componentId, String policyTypeName, String userId, boolean shouldLock) {
 
         Either<PolicyDefinition, ResponseFormat> result = null;
index 6154061..c74520f 100644 (file)
@@ -22,8 +22,10 @@ package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
 import org.apache.commons.lang.StringUtils;
+import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
 import org.openecomp.sdc.be.components.validation.UserValidations;
 import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao;
 import org.openecomp.sdc.be.impl.ComponentsUtils;
 import org.openecomp.sdc.be.model.PolicyTypeDefinition;
@@ -63,6 +65,12 @@ public class PolicyTypeBusinessLogic {
         return getPolicyTypes(excludedPolicyTypes);
     }
 
+    public PolicyTypeDefinition getLatestPolicyTypeByType(String policyTypeName) {
+        return policyTypeOperation.getLatestPolicyTypeByType(policyTypeName)
+                       .left()
+                       .on(e -> failOnPolicyType(e, policyTypeName));
+    }
+
     public Set<String> getExcludedPolicyTypes(String internalComponentType) {
         if (StringUtils.isEmpty(internalComponentType)) {
             return emptySet();
@@ -80,4 +88,13 @@ public class PolicyTypeBusinessLogic {
         log.debug("error when trying to fetch policy types: {}", err);
         return componentsUtils.convertToResponseFormatOrNotFoundErrorToEmptyList(err);
     }
+
+    private PolicyTypeDefinition failOnPolicyType(StorageOperationStatus status, String policyType) {
+        janusGraphDao.rollback();
+        if (status == StorageOperationStatus.INVALID_ID) {
+            throw new ByActionStatusComponentException(ActionStatus.POLICY_TYPE_IS_INVALID, policyType);
+        } else {
+            throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
+        }
+    }
 }
index cd0f8a0..45f2434 100644 (file)
@@ -124,6 +124,7 @@ import org.openecomp.sdc.be.model.LifecycleStateEnum;
 import org.openecomp.sdc.be.model.NodeTypeInfo;
 import org.openecomp.sdc.be.model.Operation;
 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
+import org.openecomp.sdc.be.model.PolicyDefinition;
 import org.openecomp.sdc.be.model.PropertyDefinition;
 import org.openecomp.sdc.be.model.RelationshipImpl;
 import org.openecomp.sdc.be.model.RelationshipInfo;
@@ -217,6 +218,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
     private final UiComponentDataConverter uiComponentDataConverter;
     private final CsarBusinessLogic csarBusinessLogic;
     private final PropertyBusinessLogic propertyBusinessLogic;
+       private final PolicyBusinessLogic policyBusinessLogic;
 
        @Autowired
     public ResourceBusinessLogic(IElementOperation elementDao,
@@ -238,7 +240,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
                ComponentValidator componentValidator,
                ComponentIconValidator componentIconValidator,
                ComponentProjectCodeValidator componentProjectCodeValidator,
-               ComponentDescriptionValidator componentDescriptionValidator) {
+               ComponentDescriptionValidator componentDescriptionValidator, PolicyBusinessLogic policyBusinessLogic) {
         super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic,
             interfaceOperation, interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation,
                                componentContactIdValidator, componentNameValidator, componentTagsValidator, componentValidator,
@@ -253,6 +255,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
         this.uiComponentDataConverter = uiComponentDataConverter;
         this.csarBusinessLogic = csarBusinessLogic;
         this.propertyBusinessLogic = propertyBusinessLogic;
+               this.policyBusinessLogic = policyBusinessLogic;
     }
 
        @Autowired
@@ -270,7 +273,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
        @Autowired
        private SoftwareInformationBusinessLogic softwareInformationBusinessLogic;
 
-
        public LifecycleBusinessLogic getLifecycleBusinessLogic() {
                return lifecycleBusinessLogic;
        }
@@ -1690,8 +1692,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
                                resource.getComponentMetadataForSupportLog(),
                                StatusCode.STARTED,"Started to add artifacts from yaml: {}",yamlName);
 
+                       log.trace("************* Starting to add policies from yaml {}", yamlName);
+                       Map<String, PolicyDefinition> policies = parsedToscaYamlInfo.getPolicies();
+                       if (MapUtils.isNotEmpty(policies)) {
+                               resource = createPoliciesOnResource(resource, policies);
+                       }
+                       log.trace("************* Finished to add policies from yaml {}", yamlName);
+
                        final NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts =
-                               new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
+                                       new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
 
                        final Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(
                                ArtifactOperationEnum.CREATE, createdArtifacts, yamlName, csarInfo, resource,
@@ -1789,6 +1798,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
                }
        }
 
+    private Resource createPoliciesOnResource(Resource resource, Map<String, PolicyDefinition> policies) {
+               policyBusinessLogic.createPoliciesFromParsedCsar(resource, policies);
+               return resource;
+    }
+
        private void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
                if (isNotEmpty(property.getGetInputValues())) {
                        if (inputs == null || inputs.isEmpty()) {
index 22ba03f..351e2a3 100644 (file)
@@ -16,6 +16,7 @@
 
 package org.openecomp.sdc.be.components.utils;
 
+import com.google.common.base.CharMatcher;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections.MapUtils;
 import org.apache.commons.collections4.ListUtils;
@@ -188,4 +189,12 @@ public class PropertiesUtils {
         ResourceTypeEnum resType = resource.getResourceType();
         return resType.equals(ResourceTypeEnum.ServiceProxy);
     }
+
+    /**
+     * Trim " and ' quotes
+     * @return String
+     */
+    public static String trimQuotes(String incomingString) {
+        return CharMatcher.is('\"').or(CharMatcher.is('\'')).trimFrom(incomingString);
+    }
 }
index 981c444..bb4d363 100644 (file)
@@ -43,7 +43,6 @@ import org.openecomp.sdc.be.tosca.model.VfModuleToscaMetadata;
 import org.openecomp.sdc.common.api.Constants;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
 
 import java.util.Collection;
 import java.util.HashMap;
@@ -52,6 +51,7 @@ import java.util.Map;
 import java.util.Optional;
 import java.util.function.Predicate;
 import java.util.function.Supplier;
+import org.springframework.context.event.EventListener;
 
 import static java.util.stream.Collectors.toList;
 import static java.util.stream.Collectors.toMap;
@@ -62,7 +62,7 @@ import static org.apache.commons.collections.MapUtils.isNotEmpty;
 import static org.apache.commons.lang.StringUtils.isNotEmpty;
 import static org.openecomp.sdc.be.model.utils.ComponentUtilities.getComponentInstanceNameByInstanceId;
 
-@Service
+@org.springframework.stereotype.Component
 public class GroupExportParserImpl implements GroupExportParser {
 
     private static final Logger log = Logger.getLogger(GroupExportParserImpl.class);
@@ -87,6 +87,13 @@ public class GroupExportParserImpl implements GroupExportParser {
                
                return dataTypesEither.left().value();
        }
+
+       @EventListener
+       public void onDataTypesCacheChangedEvent(
+                       ApplicationDataTypeCache.DataTypesCacheChangedEvent dataTypesCacheChangedEvent) {
+               dataTypes = dataTypesCacheChangedEvent.getNewData();
+               log.debug("Data types cache updated.");
+       }
     
        @Override
        public Map<String, ToscaGroupTemplate> getGroups(Component component) {
index ca4d405..598f73f 100644 (file)
@@ -37,7 +37,6 @@ import org.openecomp.sdc.be.tosca.model.ToscaMetadata;
 import org.openecomp.sdc.be.tosca.model.ToscaPolicyTemplate;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
 
 import java.util.ArrayList;
 import java.util.HashMap;
@@ -45,13 +44,14 @@ import java.util.List;
 import java.util.Map;
 import java.util.function.Supplier;
 import java.util.stream.Collectors;
+import org.springframework.context.event.EventListener;
 
 import static org.apache.commons.collections.CollectionUtils.isEmpty;
 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
 import static org.apache.commons.collections.MapUtils.isNotEmpty;
 import static org.apache.commons.lang.StringUtils.isNotEmpty;
 
-@Service
+@org.springframework.stereotype.Component
 public class PolicyExportParserImpl implements PolicyExportParser {
 
        private static final Logger log = Logger.getLogger(PolicyExportParserImpl.class);
@@ -76,6 +76,13 @@ public class PolicyExportParserImpl implements PolicyExportParser {
                
                return dataTypesEither.left().value();
        }
+
+       @EventListener
+       public void onDataTypesCacheChangedEvent(
+                       ApplicationDataTypeCache.DataTypesCacheChangedEvent dataTypesCacheChangedEvent) {
+               dataTypes = dataTypesCacheChangedEvent.getNewData();
+               log.debug("Data types cache updated.");
+       }
        
        @Override
        public Map<String, ToscaPolicyTemplate> getPolicies(Component component) {
index 25989df..a4491de 100644 (file)
@@ -1915,6 +1915,22 @@ errors:
         message: "Error: Invalid policy name %1 received.",
         messageId: "SVC4684"
     }
+    #---------SVC4801------------------------------
+    # %1 - policy type
+    POLICY_TYPE_IS_INVALID: {
+        code: 400,
+        message: "Error: Invalid content. Policy type %1 does not exist",
+        messageId: "SVC4801"
+    }
+
+    #---------SVC4802------------------------------
+    # %1 - policy name
+    POLICY_MISSING_POLICY_TYPE: {
+        code: 400,
+        message: "Error: Invalid content. Type name is not defined for policy %1",
+        messageId: "SVC4802"
+    }
+
     #---------SVC4685------------------------------
     # %1 - policy name
     POLICY_NAME_ALREADY_EXIST: {
index 82b49ff..b8bb4a7 100644 (file)
@@ -18,6 +18,8 @@ package org.openecomp.sdc.be.components.impl;
 
 
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Optional;
 import org.apache.commons.collections.CollectionUtils;
 import org.junit.Before;
 import org.junit.BeforeClass;
@@ -76,11 +78,14 @@ import java.util.Map;
 
 import static org.assertj.core.api.Java6Assertions.assertThat;
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyBoolean;
 import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.when;
 
@@ -177,6 +182,47 @@ public class PolicyBusinessLogicTest {
         PolicyDefinition response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true);
         assertTrue(!response.isEmpty());
     }
+
+    @Test
+    public void createPolicyFromCsarDefinitionTest() {
+        String prop1 = "Prop_1";
+        String prop2 = "Prop_2";
+        Map<String, PolicyDefinition> policies = new HashMap<>();
+        PolicyDefinition policy = buildPolicy(POLICY_NAME);
+        Map<PolicyTargetType, List<String>> targets = getTargets();
+        PropertyDataDefinition[] properties = getProperties(prop1, prop2);
+        policy.setTargets(targets);
+        policy.setProperties(Arrays.asList(properties));
+        policies.put(POLICY_NAME, policy);
+
+        List<ComponentInstance> instanceList = new ArrayList<>();
+        ComponentInstance componentInstance = new ComponentInstance();
+        componentInstance.setUniqueId(UNIQUE_ID_EXSISTS);
+        componentInstance.setName(UNIQUE_ID_EXSISTS);
+        instanceList.add(componentInstance);
+
+        Resource newResource = buildResource();
+        newResource.setPolicies(policies);
+        newResource.setComponentInstances(instanceList);
+        
+        when(policyTypeOperation.getLatestPolicyTypeByType(eq(POLICY_TYPE_NAME))).thenReturn(getPolicyTypeSuccessEither);
+        when(toscaOperationFacade.associatePolicyToComponent(eq(COMPONENT_ID), any(PolicyDefinition.class), eq(0))).thenReturn(Either.left(policy));
+        when(toscaOperationFacade.getToscaFullElement(eq(COMPONENT_ID))).thenReturn(Either.left(newResource));
+        when(toscaOperationFacade.updatePolicyOfComponent(eq(COMPONENT_ID), any(PolicyDefinition.class), any(PromoteVersionEnum.class))).thenReturn(Either.left(policy));
+        when(dataTypeCache.getAll()).thenReturn(Either.left(new HashMap<>()));
+        when(propertyOperation.validateAndUpdatePropertyValue(eq(null), eq(prop1), anyBoolean(), eq(null), anyMap())).thenReturn(Either.left(prop1));
+        when(propertyOperation.validateAndUpdatePropertyValue(eq(null), eq(prop2), anyBoolean(), eq(null), anyMap())).thenReturn(Either.left(prop2));
+
+        Map<String, PolicyDefinition> createdPolicy = businessLogic.createPoliciesFromParsedCsar(newResource, policies);
+
+        assertFalse(createdPolicy.isEmpty());
+        PolicyDefinition newPolicy = createdPolicy.get(POLICY_NAME);
+        assertNotNull(newPolicy);
+        assertNotNull(newPolicy.getTargets());
+        assertNotNull(newPolicy.getProperties());
+        assertEquals(2, newPolicy.getProperties().size());
+        assertEquals(1, newPolicy.getTargets().size());
+    }
     
     @Test
     public void createPolicyUserFailureTest(){
index 44d1e06..2baafdc 100644 (file)
@@ -22,6 +22,7 @@
 package org.openecomp.sdc.be.components.impl;
 
 import com.google.common.collect.ImmutableMap;
+import fj.data.Either;
 import org.junit.Before;
 import org.junit.BeforeClass;
 import org.junit.Test;
@@ -122,4 +123,12 @@ public class PolicyTypeBusinessLogicTest {
         }
     }
 
+    @Test
+    public void getLatestPolicyTypeByTypeTest() {
+        PolicyTypeDefinition policyTypeDefinition = new PolicyTypeBuilder().setType("org.openecomp.policies.placement.Antilocate").build();
+        when(policyTypeOperation.getLatestPolicyTypeByType("org.openecomp.policies.placement.Antilocate")).thenReturn(
+                Either.left(policyTypeDefinition));
+        assertThat(policyTypeOperation.getLatestPolicyTypeByType("org.openecomp.policies.placement.Antilocate"))
+                .isEqualTo(Either.left(testInstance.getLatestPolicyTypeByType("org.openecomp.policies.placement.Antilocate")));
+    }
 }
\ No newline at end of file
index 69b3f1d..2401c7e 100644 (file)
@@ -198,7 +198,7 @@ public class ResourceBusinessLogicTest {
        MergeInstanceUtils mergeInstanceUtils = Mockito.mock(MergeInstanceUtils.class);
        UiComponentDataConverter uiComponentDataConverter = Mockito.mock(UiComponentDataConverter.class);
        ToscaExportHandler toscaExportHandler = Mockito.mock(ToscaExportHandler.class);
-
+       PolicyBusinessLogic policyBusinessLogic = Mockito.mock(PolicyBusinessLogic.class);
 
 
        @InjectMocks
@@ -318,7 +318,8 @@ public class ResourceBusinessLogicTest {
                                resourceImportManager, inputsBusinessLogic, compositionBusinessLogic, resourceDataMergeBusinessLogic,
                                csarArtifactsAndGroupsBusinessLogic, mergeInstanceUtils, uiComponentDataConverter, csarBusinessLogic,
                                artifactToscaOperation, propertyBusinessLogic, componentContactIdValidator, componentNameValidator,
-                               componentTagsValidator, componentValidator,     componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator);
+                               componentTagsValidator, componentValidator,     componentIconValidator, componentProjectCodeValidator,
+                               componentDescriptionValidator, policyBusinessLogic);
                bl.setElementDao(mockElementDao);
                bl.setUserAdmin(mockUserAdmin);
                bl.setCapabilityTypeOperation(capabilityTypeOperation);
index b63e6ff..1d7a1c5 100644 (file)
@@ -35,6 +35,7 @@ import org.openecomp.sdc.be.components.csar.CsarInfo;
 import org.openecomp.sdc.be.components.csar.YamlTemplateParsingHandler;
 import org.openecomp.sdc.be.components.impl.AnnotationBusinessLogic;
 import org.openecomp.sdc.be.components.impl.GroupTypeBusinessLogic;
+import org.openecomp.sdc.be.components.impl.PolicyTypeBusinessLogic;
 import org.openecomp.sdc.be.components.validation.AnnotationValidator;
 import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao;
 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
@@ -43,6 +44,8 @@ import org.openecomp.sdc.be.model.ComponentInstanceProperty;
 import org.openecomp.sdc.be.model.GroupProperty;
 import org.openecomp.sdc.be.model.GroupTypeDefinition;
 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
+import org.openecomp.sdc.be.model.PolicyDefinition;
+import org.openecomp.sdc.be.model.PolicyTypeDefinition;
 import org.openecomp.sdc.be.model.UploadArtifactInfo;
 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
 import org.openecomp.sdc.be.model.User;
@@ -58,6 +61,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 import java.util.stream.Collectors;
+import org.springframework.test.util.ReflectionTestUtils;
 
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.junit.Assert.assertNotNull;
@@ -78,6 +82,8 @@ public class YamlTemplateParsingHandlerTest {
     private JanusGraphDao janusGraphDao;
     @Mock
     private User user;
+    @Mock
+    private PolicyTypeBusinessLogic policyTypeBusinessLogic;
 
     private YamlTemplateParsingHandler handler;
 
@@ -87,9 +93,13 @@ public class YamlTemplateParsingHandlerTest {
     private final static String VFC_GROUP_TYPE = "org.openecomp.groups.VfcInstanceGroup";
     private final static String HEAT_GROUP_TYPE = "org.openecomp.groups.heat.HeatStack";
     private final static String ROOT_GROUP_TYPE = "tosca.groups.Root";
+    private final static String OPENECOMP_ANTILOCATE_POLICY_TYPE = "org.openecomp.policies.placement.Antilocate";
+    private final static String ROOT_POLICIES_TYPE = "tosca.policies.Root";
     private final static GroupTypeDefinition VfcInstanceGroupType = buildVfcInstanceGroupType();
     private final static GroupTypeDefinition heatGroupType = buildHeatStackGroupType();
     private final static GroupTypeDefinition rootGroupType = buildRootGroupType();
+    private static final PolicyTypeDefinition OPENECOMP_POLICY_TYPE = buildOpenecompPolicyType();
+    private final static String OPENECOMP_POLICY_NAME = "vepdg_server_group_policy";
     private final static String CAPABILITY_TYPE = "org.openecomp.capabilities.VLANAssignment";
     private final static String CAPABILITY_NAME = "vlan_assignment";
     private static final String CSAR_FILE_PATH = "csars/with_groups.csar";
@@ -122,8 +132,10 @@ public class YamlTemplateParsingHandlerTest {
 
         AnnotationBusinessLogic annotationBusinessLogic = new AnnotationBusinessLogic(annotationTypeOperations,
                 annotationValidator);
-        handler = new YamlTemplateParsingHandler(janusGraphDao, groupTypeBusinessLogic, annotationBusinessLogic);
+        handler = new YamlTemplateParsingHandler(janusGraphDao, groupTypeBusinessLogic, annotationBusinessLogic, policyTypeBusinessLogic);
+        ReflectionTestUtils.setField(handler, "policyTypeBusinessLogic", policyTypeBusinessLogic);
         stubGetGroupType();
+        stubGetPolicyType();
     }
 
     @Test
@@ -148,6 +160,79 @@ public class YamlTemplateParsingHandlerTest {
         validateParsedYamlWithCapability(parsedYaml);
     }
 
+    @Test
+    public void testSetArtifacts() {
+        UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo();
+        Map<String, Object> nodeTemplateJsonMap = new HashMap<>();
+        Map<String, String> nodeMap = new HashMap<>();
+        nodeMap.put("name","test_name");
+        nodeMap.put("type","test_type");
+        nodeTemplateJsonMap.put(ARTIFACTS.getElementName(), nodeMap);
+        Deencapsulation.invoke(testSubject, "setArtifacts", nodeTemplateInfo, nodeTemplateJsonMap);
+        assertNotNull(nodeTemplateInfo.getArtifacts());
+    }
+
+    @Test
+    public void testCreateArtifactsModuleFromYaml() {
+        Map<String, Map<String, Map<String, String>>> nodeTemplateJsonMap = new HashMap<>();
+        Map<String, Map<String,String>> map0 = new HashMap<>();
+        Map<String, String> map1 = new HashMap<>();
+        map1.put("file", "test_file");
+        map1.put("type", "test_type");
+        map0.put("test_art", map1);
+        nodeTemplateJsonMap.put(ARTIFACTS.getElementName(), map0);
+        Map<String, Map<String, UploadArtifactInfo>> result;
+        result = Deencapsulation.invoke(testSubject, "createArtifactsModuleFromYaml", nodeTemplateJsonMap);
+        Assert.assertTrue(MapUtils.isNotEmpty(result));
+        Assert.assertTrue(MapUtils.isNotEmpty(result.get(ARTIFACTS.getElementName())));
+        Assert.assertEquals("test_file", result.get(ARTIFACTS.getElementName()).get("test_art").getFile());
+        Assert.assertEquals("test_type", result.get(ARTIFACTS.getElementName()).get("test_art").getType());
+    }
+
+    @Test
+    public void testAddModuleNodeTemplateArtifacts() {
+        Map<String, Map<String, UploadArtifactInfo>> result = new HashMap<>();
+        Map<String, String> map1 = new HashMap<>();
+        map1.put("file", "test_file");
+        map1.put("type", "test_type");
+        Deencapsulation.invoke(testSubject, "addModuleNodeTemplateArtifacts", result, map1, "test_art");
+        Assert.assertTrue(MapUtils.isNotEmpty(result));
+        Assert.assertTrue(MapUtils.isNotEmpty(result.get(ARTIFACTS.getElementName())));
+        Assert.assertEquals("test_file", result.get(ARTIFACTS.getElementName()).get("test_art").getFile());
+        Assert.assertEquals("test_type", result.get(ARTIFACTS.getElementName()).get("test_art").getType());
+    }
+
+    @Test
+    public void testBuildModuleNodeTemplateArtifact() {
+        Map<String, String> map1 = new HashMap<>();
+        map1.put("file", "test_file");
+        map1.put("type", "test_type");
+        UploadArtifactInfo result;
+        result = Deencapsulation.invoke(testSubject, "buildModuleNodeTemplateArtifact", map1);
+        assertNotNull(result);
+        Assert.assertEquals("test_file", result.getFile());
+        Assert.assertEquals("test_type", result.getType());
+    }
+
+    @Test
+    public void testFillArtifact() {
+        Map<String, String> map1 = new HashMap<>();
+        map1.put("file", "test_file");
+        map1.put("type", "test_type");
+        UploadArtifactInfo result = new UploadArtifactInfo();
+        Deencapsulation.invoke(testSubject, "fillArtifact", result, map1);
+        assertNotNull(result);
+        Assert.assertEquals("test_file", result.getFile());
+        Assert.assertEquals("test_type", result.getType());
+    }
+
+    @Test
+    public void parseResourceWithPoliciesDefined() {
+        ParsedToscaYamlInfo parsedYaml = handler.parseResourceInfoFromYAML(FILE_NAME, resourceYml, new HashMap<>(),
+                new HashMap<>(), "");
+        validateParsedYamlWithPolicies(parsedYaml);
+    }
+
     private void validateParsedYaml(ParsedToscaYamlInfo parsedYaml, String group, List<String> expectedProp) {
         assertThat(parsedYaml).isNotNull();
         assertThat(parsedYaml.getGroups()).isNotNull().containsKey(group);
@@ -155,15 +240,15 @@ public class YamlTemplateParsingHandlerTest {
 
         assertThat(parsedYaml.getGroups().get(group).getProperties()).isNotNull();
         assertThat(parsedYaml.getGroups().get(group).getProperties()
-                .stream()
-                .map(PropertyDataDefinition::getName)
-                .collect(Collectors.toList()))
+                           .stream()
+                           .map(PropertyDataDefinition::getName)
+                           .collect(Collectors.toList()))
                 .containsAll(expectedProp);
 
         assertThat(parsedYaml.getGroups().get(group).getMembers()).isNotNull();
     }
 
-       private void validateParsedYamlWithCapability(ParsedToscaYamlInfo parsedYaml) {
+    private void validateParsedYamlWithCapability(ParsedToscaYamlInfo parsedYaml) {
 
         final List<String> expectedProp = Lists.newArrayList("vfc_parent_port_role",
                 "network_collection_function", "vfc_instance_group_function", "subinterface_role");
@@ -171,23 +256,23 @@ public class YamlTemplateParsingHandlerTest {
         validateParsedYaml(parsedYaml, MAIN_GROUP_NAME, expectedProp);
 
         assertThat(parsedYaml.getGroups().get(MAIN_GROUP_NAME).getCapabilities()
-                .get(CAPABILITY_TYPE)
-                .get(0).getProperties().get(0).getValue()).isEqualTo("success");
+                           .get(CAPABILITY_TYPE)
+                           .get(0).getProperties().get(0).getValue()).isEqualTo("success");
         assertThat(parsedYaml.getGroups().get(MAIN_GROUP_NAME).getCapabilities()).isNotNull();
-       }
+    }
 
-       private void stubGetGroupType() {
-               when(groupTypeBusinessLogic.getLatestGroupTypeByType(eq(VFC_GROUP_TYPE))).thenReturn(VfcInstanceGroupType);
-               when(groupTypeBusinessLogic.getLatestGroupTypeByType(eq(HEAT_GROUP_TYPE))).thenReturn(heatGroupType);
+    private void stubGetGroupType() {
+        when(groupTypeBusinessLogic.getLatestGroupTypeByType(eq(VFC_GROUP_TYPE))).thenReturn(VfcInstanceGroupType);
+        when(groupTypeBusinessLogic.getLatestGroupTypeByType(eq(HEAT_GROUP_TYPE))).thenReturn(heatGroupType);
         when(groupTypeBusinessLogic.getLatestGroupTypeByType(eq(ROOT_GROUP_TYPE))).thenReturn(rootGroupType);
     }
 
     private static GroupTypeDefinition buildRootGroupType() {
         return createGroupTypeDefinition(ROOT_GROUP_TYPE, null,
                 "The TOSCA Group Type all other TOSCA Group Types derive from");
-       }
+    }
 
-       private static GroupTypeDefinition buildHeatStackGroupType() {
+    private static GroupTypeDefinition buildHeatStackGroupType() {
         GroupTypeDefinition groupType = createGroupTypeDefinition(HEAT_GROUP_TYPE, "tosca.groups.Root",
                 "Grouped all heat resources which are in the same heat stack");
 
@@ -199,9 +284,9 @@ public class YamlTemplateParsingHandlerTest {
 
         groupType.setProperties(Lists.newArrayList(property1, property2));
         return groupType;
-       }
+    }
 
-       private static GroupTypeDefinition buildVfcInstanceGroupType() {
+    private static GroupTypeDefinition buildVfcInstanceGroupType() {
         GroupTypeDefinition groupType = createGroupTypeDefinition(VFC_GROUP_TYPE, "tosca.groups.Root",
                 "Groups of VFCs with same parent port role");
 
@@ -250,7 +335,7 @@ public class YamlTemplateParsingHandlerTest {
         return property;
     }
     private static GroupProperty createGroupProperty(String name, String description,
-                                                     String status){
+            String status){
         GroupProperty property = new GroupProperty();
         if (name != null)
             property.setName(name);
@@ -268,69 +353,38 @@ public class YamlTemplateParsingHandlerTest {
 
         return property;
     }
-    @Test
-    public void testSetArtifacts() {
-        UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo();
-        Map<String, Object> nodeTemplateJsonMap = new HashMap<>();
-        Map<String, String> nodeMap = new HashMap<>();
-        nodeMap.put("name","test_name");
-        nodeMap.put("type","test_type");
-        nodeTemplateJsonMap.put(ARTIFACTS.getElementName(), nodeMap);
-        Deencapsulation.invoke(testSubject, "setArtifacts", nodeTemplateInfo, nodeTemplateJsonMap);
-        assertNotNull(nodeTemplateInfo.getArtifacts());
-    }
 
-    @Test
-    public void testCreateArtifactsModuleFromYaml() {
-        Map<String, Map<String, Map<String, String>>> nodeTemplateJsonMap = new HashMap<>();
-        Map<String, Map<String,String>> map0 = new HashMap<>();
-        Map<String, String> map1 = new HashMap<>();
-        map1.put("file", "test_file");
-        map1.put("type", "test_type");
-        map0.put("test_art", map1);
-        nodeTemplateJsonMap.put(ARTIFACTS.getElementName(), map0);
-        Map<String, Map<String, UploadArtifactInfo>> result;
-        result = Deencapsulation.invoke(testSubject, "createArtifactsModuleFromYaml", nodeTemplateJsonMap);
-        Assert.assertTrue(MapUtils.isNotEmpty(result));
-        Assert.assertTrue(MapUtils.isNotEmpty(result.get(ARTIFACTS.getElementName())));
-        Assert.assertEquals("test_file", result.get(ARTIFACTS.getElementName()).get("test_art").getFile());
-        Assert.assertEquals("test_type", result.get(ARTIFACTS.getElementName()).get("test_art").getType());
+    private void validateParsedYamlWithPolicies(ParsedToscaYamlInfo parsedYaml) {
+        // validate  policies
+        assertThat(parsedYaml.getPolicies()).isNotNull();
+        assertThat(parsedYaml.getPolicies()).containsKey(OPENECOMP_POLICY_NAME);
+        assertThat(parsedYaml.getPolicies().get(OPENECOMP_POLICY_NAME)).isInstanceOf(PolicyDefinition.class);
     }
 
-    @Test
-    public void testAddModuleNodeTemplateArtifacts() {
-        Map<String, Map<String, UploadArtifactInfo>> result = new HashMap<>();
-        Map<String, String> map1 = new HashMap<>();
-        map1.put("file", "test_file");
-        map1.put("type", "test_type");
-        Deencapsulation.invoke(testSubject, "addModuleNodeTemplateArtifacts", result, map1, "test_art");
-        Assert.assertTrue(MapUtils.isNotEmpty(result));
-        Assert.assertTrue(MapUtils.isNotEmpty(result.get(ARTIFACTS.getElementName())));
-        Assert.assertEquals("test_file", result.get(ARTIFACTS.getElementName()).get("test_art").getFile());
-        Assert.assertEquals("test_type", result.get(ARTIFACTS.getElementName()).get("test_art").getType());
+    private void stubGetPolicyType () {
+        when(policyTypeBusinessLogic.getLatestPolicyTypeByType(eq(OPENECOMP_ANTILOCATE_POLICY_TYPE))).thenReturn(
+                OPENECOMP_POLICY_TYPE);
     }
 
-    @Test
-    public void testBuildModuleNodeTemplateArtifact() {
-        Map<String, String> map1 = new HashMap<>();
-        map1.put("file", "test_file");
-        map1.put("type", "test_type");
-        UploadArtifactInfo result;
-        result = Deencapsulation.invoke(testSubject, "buildModuleNodeTemplateArtifact", map1);
-        assertNotNull(result);
-        Assert.assertEquals("test_file", result.getFile());
-        Assert.assertEquals("test_type", result.getType());
+    private static PolicyTypeDefinition buildOpenecompPolicyType() {
+        return createPolicyTypeDefinition(OPENECOMP_POLICY_NAME, OPENECOMP_ANTILOCATE_POLICY_TYPE, ROOT_POLICIES_TYPE,
+                "The Openecomp Antilocate policy");
     }
 
-    @Test
-    public void testFillArtifact() {
-        Map<String, String> map1 = new HashMap<>();
-        map1.put("file", "test_file");
-        map1.put("type", "test_type");
-        UploadArtifactInfo result = new UploadArtifactInfo();
-        Deencapsulation.invoke(testSubject, "fillArtifact", result, map1);
-        assertNotNull(result);
-        Assert.assertEquals("test_file", result.getFile());
-        Assert.assertEquals("test_type", result.getType());
+    private static PolicyTypeDefinition createPolicyTypeDefinition(String policyName, String policyType, String derivedFrom, String description) {
+        PolicyTypeDefinition policyTypeDefinition = new PolicyTypeDefinition();
+        if (policyName != null && !policyName.isEmpty()) {
+            policyTypeDefinition.setName(policyName);
+        }
+        if (policyType != null) {
+            policyTypeDefinition.setType(policyType);
+        }
+        if (derivedFrom != null) {
+            policyTypeDefinition.setDerivedFrom(derivedFrom);
+        }
+        if (description != null) {
+            policyTypeDefinition.setDescription(description);
+        }
+        return policyTypeDefinition;
     }
 }
index a27c959..48c2c9c 100644 (file)
@@ -30,6 +30,7 @@ import org.openecomp.sdc.be.components.csar.CsarBusinessLogic;
 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
 import org.openecomp.sdc.be.components.impl.CompositionBusinessLogic;
 import org.openecomp.sdc.be.components.impl.InputsBusinessLogic;
+import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic;
 import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic;
 import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
@@ -64,7 +65,7 @@ public class CheckoutTest extends LifecycleTestBase {
     private final PropertyBusinessLogic propertyBusinessLogic = Mockito.mock(PropertyBusinessLogic.class);
     protected ComponentContactIdValidator componentContactIdValidator = new ComponentContactIdValidator(componentsUtils);
     protected ComponentNameValidator componentNameValidator = new ComponentNameValidator(componentsUtils, toscaOperationFacade);
-
+    private final PolicyBusinessLogic policyBusinessLogic = Mockito.mock(PolicyBusinessLogic.class);
     @InjectMocks
     ResourceBusinessLogic bl = new ResourceBusinessLogic(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
         groupBusinessLogic, interfaceOperation, interfaceLifecycleTypeOperation, artifactsBusinessLogic,
@@ -72,7 +73,7 @@ public class CheckoutTest extends LifecycleTestBase {
         resourceDataMergeBusinessLogic, csarArtifactsAndGroupsBusinessLogic, mergeInstanceUtils,
         uiComponentDataConverter, csarBusinessLogic, artifactToscaOperation, propertyBusinessLogic,
         componentContactIdValidator, componentNameValidator, componentTagsValidator, componentValidator,
-            componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator );
+            componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator ,policyBusinessLogic);
 
     @Before
     public void setup() {
index 39316c6..a28f31b 100644 (file)
@@ -2239,3 +2239,18 @@ errors:
         message: 'Error: Invalid Content. %1 has invalid format.',
         messageId: "SVC4723"
     }
+    #---------SVC4801------------------------------
+    # %1 - policy type
+    POLICY_TYPE_IS_INVALID: {
+        code: 400,
+        message: "Error: Invalid content. Policy type %1 does not exist",
+        messageId: "SVC4801"
+    }
+
+    #---------SVC4802------------------------------
+    # %1 - policy name
+    POLICY_MISSING_POLICY_TYPE: {
+        code: 400,
+        message: "Error: Invalid content. Type name is not defined for policy %1",
+        messageId: "SVC4802"
+    }
index bbd9db3..09824fc 100644 (file)
@@ -106,7 +106,7 @@ public enum ActionStatus {
     RESOURCE_CANNOT_CONTAIN_POLICIES,
     POLICY_NOT_FOUND_ON_CONTAINER,
     INVALID_POLICY_NAME,
-    POLICY_NAME_ALREADY_EXIST, EXCLUDED_POLICY_TYPE,
+    POLICY_NAME_ALREADY_EXIST, EXCLUDED_POLICY_TYPE, POLICY_MISSING_POLICY_TYPE, POLICY_TYPE_IS_INVALID,
 
     //External References Statuses
     EXT_REF_ALREADY_EXIST,
index f975806..a6f4165 100644 (file)
 package org.openecomp.sdc.be.model;
 
 import java.util.Map;
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
 
+@ToString
+@Getter
+@Setter
 public class ParsedToscaYamlInfo {
     Map<String, InputDefinition> inputs;
-
     Map<String, UploadComponentInstanceInfo> instances;
-
     Map<String, GroupDefinition> groups;
-
-    public Map<String, UploadComponentInstanceInfo> getInstances() {
-        return instances;
-    }
-
-    public void setInstances(Map<String, UploadComponentInstanceInfo> instances) {
-        this.instances = instances;
-    }
-
-    public Map<String, GroupDefinition> getGroups() {
-        return groups;
-    }
-
-    public void setGroups(Map<String, GroupDefinition> groups) {
-        this.groups = groups;
-    }
-
-    public Map<String, InputDefinition> getInputs() {
-        return inputs;
-    }
-
-    public void setInputs(Map<String, InputDefinition> inputs) {
-        this.inputs = inputs;
-    }
-
-    @Override
-    public String toString() {
-        return "ParsedToscaYamlInfo [inputs=" + inputs + ", instances=" + instances + ", groups=" + groups + "]";
-    }
-
+    Map<String, PolicyDefinition> policies;
 }
index fb49762..25a305e 100644 (file)
@@ -21,6 +21,7 @@
 package org.openecomp.sdc.be.model.cache;
 
 import fj.data.Either;
+import lombok.Getter;
 import org.apache.commons.lang3.concurrent.BasicThreadFactory;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -34,6 +35,9 @@ import org.openecomp.sdc.be.model.DataTypeDefinition;
 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
 import org.openecomp.sdc.be.resources.data.DataTypeData;
 import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.ApplicationEvent;
+import org.springframework.context.ApplicationEventPublisher;
 import org.springframework.stereotype.Component;
 
 import javax.annotation.PostConstruct;
@@ -74,6 +78,9 @@ public class ApplicationDataTypeCache implements ApplicationCache<DataTypeDefini
     @Resource
     private PropertyOperation propertyOperation;
 
+    @Autowired
+    private ApplicationEventPublisher applicationEventPublisher;
+
     @PostConstruct
     public void init() {
 
@@ -313,6 +320,8 @@ public class ApplicationDataTypeCache implements ApplicationCache<DataTypeDefini
                 w.lock();
 
                 data = allDataTypes.left().value();
+                // send notification on data types change
+                onDataChangeEventEmit(data);
 
                 BeEcompErrorManager.getInstance().logInternalFlowError("ReplaceDataTypesCache",
                         "Succeed to replace the data types cache", ErrorSeverity.INFO);
@@ -325,4 +334,22 @@ public class ApplicationDataTypeCache implements ApplicationCache<DataTypeDefini
 
     }
 
+    private void onDataChangeEventEmit(Map<String, DataTypeDefinition> newData) {
+        log.trace("Cache data has changed, sending event to all listening for this change.");
+        DataTypesCacheChangedEvent dataTypesCacheChangedEvent = new DataTypesCacheChangedEvent(this, newData);
+        applicationEventPublisher.publishEvent(dataTypesCacheChangedEvent);
+    }
+
+    /**
+     * Custom event to notify all interested in cached data changes
+     */
+    public static class DataTypesCacheChangedEvent extends ApplicationEvent {
+        @Getter
+        private Map<String, DataTypeDefinition> newData;
+
+        public DataTypesCacheChangedEvent(Object source, Map<String, DataTypeDefinition> newData) {
+            super(source);
+            this.newData = newData;
+        }
+    }
 }
index 481894c..7186d2a 100644 (file)
@@ -39,6 +39,7 @@ import java.util.HashMap;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
+import org.springframework.context.ApplicationEventPublisher;
 
 public class ApplicationDataTypeCacheTest extends ModelConfDependentTest{
 
@@ -48,6 +49,9 @@ public class ApplicationDataTypeCacheTest extends ModelConfDependentTest{
        @Mock
        PropertyOperation propertyOperation;
 
+       @Mock
+       ApplicationEventPublisher applicationEventPublisher;
+
        @Before
        public void setUpMocks() throws Exception {
                MockitoAnnotations.initMocks(this);
index f68f217..5198be9 100644 (file)
@@ -46,7 +46,7 @@ public class TypeUtils {
         // Group Types
         MEMBERS("members"), METADATA("metadata"),
         // Policy Types
-        TARGETS("targets"),
+        POLICIES("policies"), TARGETS("targets"),
         // Capabilities
         CAPABILITIES("capabilities"), VALID_SOURCE_TYPES("valid_source_types"),
         // Requirements