Support Policies during Import Service
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / ResourceBusinessLogic.java
index 9ba20f4..1f107e4 100644 (file)
@@ -21,7 +21,6 @@ package org.openecomp.sdc.be.components.impl;
 
 import static java.util.stream.Collectors.toList;
 import static java.util.stream.Collectors.toMap;
-import static java.util.stream.Collectors.toSet;
 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
 import static org.apache.commons.collections.MapUtils.isEmpty;
 import static org.apache.commons.collections.MapUtils.isNotEmpty;
@@ -29,6 +28,9 @@ import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStr
 import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
 import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
 import static org.openecomp.sdc.common.api.Constants.DEFAULT_GROUP_VF_MODULE;
+
+import com.google.common.annotations.VisibleForTesting;
+import fj.data.Either;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
@@ -115,6 +117,7 @@ import org.openecomp.sdc.be.model.ComponentInstanceProperty;
 import org.openecomp.sdc.be.model.ComponentParametersView;
 import org.openecomp.sdc.be.model.DataTypeDefinition;
 import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupProperty;
 import org.openecomp.sdc.be.model.InputDefinition;
 import org.openecomp.sdc.be.model.InterfaceDefinition;
 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
@@ -124,6 +127,7 @@ 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.PolicyTypeDefinition;
 import org.openecomp.sdc.be.model.PropertyDefinition;
 import org.openecomp.sdc.be.model.RelationshipImpl;
 import org.openecomp.sdc.be.model.RelationshipInfo;
@@ -154,6 +158,7 @@ import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
+import org.openecomp.sdc.be.model.operations.impl.ModelOperation;
 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
@@ -165,6 +170,7 @@ import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
 import org.openecomp.sdc.be.user.UserBusinessLogic;
 import org.openecomp.sdc.be.utils.CommonBeUtils;
 import org.openecomp.sdc.be.utils.TypeUtils;
+import org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum;
 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
 import org.openecomp.sdc.common.api.Constants;
@@ -182,8 +188,6 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Lazy;
 import org.yaml.snakeyaml.DumperOptions;
 import org.yaml.snakeyaml.Yaml;
-import com.google.common.annotations.VisibleForTesting;
-import fj.data.Either;
 
 @org.springframework.stereotype.Component("resourceBusinessLogic")
 public class ResourceBusinessLogic extends ComponentBusinessLogic {
@@ -215,6 +219,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
     private final PropertyBusinessLogic propertyBusinessLogic;
     private final PolicyBusinessLogic policyBusinessLogic;
     private final ModelBusinessLogic modelBusinessLogic;
+    private final DataTypeBusinessLogic dataTypeBusinessLogic;
+    private final PolicyTypeBusinessLogic policyTypeBusinessLogic;
+    private final ModelOperation modelOperation;
     private IInterfaceLifecycleOperation interfaceTypeOperation;
     private LifecycleBusinessLogic lifecycleBusinessLogic;
     @Autowired
@@ -247,7 +254,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
                                  final ComponentValidator componentValidator, final ComponentIconValidator componentIconValidator,
                                  final ComponentProjectCodeValidator componentProjectCodeValidator,
                                  final ComponentDescriptionValidator componentDescriptionValidator, final PolicyBusinessLogic policyBusinessLogic,
-                                 final ModelBusinessLogic modelBusinessLogic) {
+                                 final ModelBusinessLogic modelBusinessLogic,
+                                 final DataTypeBusinessLogic dataTypeBusinessLogic, final PolicyTypeBusinessLogic policyTypeBusinessLogic,
+                                 final ModelOperation modelOperation) {
         super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic, interfaceOperation,
             interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, componentContactIdValidator, componentNameValidator,
             componentTagsValidator, componentValidator, componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator);
@@ -264,6 +273,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
         this.propertyBusinessLogic = propertyBusinessLogic;
         this.policyBusinessLogic = policyBusinessLogic;
         this.modelBusinessLogic = modelBusinessLogic;
+        this.dataTypeBusinessLogic = dataTypeBusinessLogic;
+        this.policyTypeBusinessLogic = policyTypeBusinessLogic;
+        this.modelOperation = modelOperation;
     }
 
     static <T> Either<T, RuntimeException> rollbackWithEither(final JanusGraphDao janusGraphDao, final ActionStatus actionStatus,
@@ -1031,22 +1043,21 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
                 user.getUserId());
         CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID);
         Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractTypesInfo();
-        if (StringUtils.isNotEmpty(resource.getModel())) {
-            final Map<String, Object> dataTypesToCreate = new HashMap<>();
-            for (final String dataType: csarInfo.getDataTypes().keySet()) {
-                final Either<DataTypeDefinition, StorageOperationStatus> result = propertyOperation.getDataTypeByName(dataType, resource.getModel());
-                if (result.isRight() && result.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
-                    dataTypesToCreate.put(dataType, csarInfo.getDataTypes().get(dataType));
-                }
+        final String model = resource.getModel();
+        if (StringUtils.isNotEmpty(model)) {
+            final Map<String, Object> dataTypesToCreate = getDatatypesToCreate(model, csarInfo.getDataTypes());
+            final Map<String, Object> policyTypesToCreate = getPolicytypesToCreate(model, csarInfo.getPolicyTypes());
+            if (MapUtils.isNotEmpty(dataTypesToCreate) || MapUtils.isNotEmpty(policyTypesToCreate)) {
+                createModel(resource, csarInfo.getVfResourceName());
             }
             if (MapUtils.isNotEmpty(dataTypesToCreate)) {
-                final String nameForGeneratedModel = resource.getModel() + "_" + csarInfo.getVfResourceName() + resource.getCsarVersion();
-                final Model model = new Model(nameForGeneratedModel, resource.getModel(), ModelTypeEnum.NORMATIVE_EXTENSION);
-                modelBusinessLogic.createModel(model, new Yaml().dump(dataTypesToCreate));
-                resource.setModel(nameForGeneratedModel);
+                dataTypeBusinessLogic.createDataTypeFromYaml(new Yaml().dump(dataTypesToCreate), model, true);
+            }
+            if (MapUtils.isNotEmpty(policyTypesToCreate)) {
+                policyTypeBusinessLogic.createPolicyTypeFromYaml(new Yaml().dump(policyTypesToCreate), model, true);
             }
         }
-        
+
         Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
             nodeTypesInfo, csarInfo, resource);
         if (findNodeTypesArtifactsToHandleRes.isRight()) {
@@ -1148,6 +1159,37 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
         return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES).left().orValue(HashMap::new);
     }
 
+    private void createModel(final Resource resource, final String vfResourcename) {
+        final String nameForGeneratedModel = resource.getModel() + "_" + vfResourcename + resource.getCsarVersion();
+        Model model = new Model(nameForGeneratedModel, resource.getModel(), ModelTypeEnum.NORMATIVE_EXTENSION);
+        modelBusinessLogic.createModel(model);
+        resource.setModel(nameForGeneratedModel);
+    }
+
+    private Map<String, Object> getDatatypesToCreate(final String model, final Map<String, Object> dataTypes) {
+        final Map<String, Object> dataTypesToCreate = new HashMap<>();
+        for (final String dataType : dataTypes.keySet()) {
+            final Either<DataTypeDefinition, StorageOperationStatus> result =
+                propertyOperation.getDataTypeByName(dataType, model);
+            if (result.isRight() && result.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
+                dataTypesToCreate.put(dataType, dataTypes.get(dataType));
+            }
+        }
+        return dataTypesToCreate;
+    }
+
+    private Map<String, Object> getPolicytypesToCreate(final String model, final Map<String, Object> policyTypes) {
+        final Map<String, Object> policyTypesToCreate = new HashMap<>();
+        for (final String policyType : policyTypes.keySet()) {
+            final Either<PolicyTypeDefinition, StorageOperationStatus> result =
+                policyTypeOperation.getLatestPolicyTypeByType(policyType, model);
+            if (result.isRight() && result.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
+                policyTypesToCreate.put(policyType, policyTypes.get(policyType));
+            }
+        }
+        return policyTypesToCreate;
+    }
+
     private void createNodeTypes(String yamlName, Resource resource, boolean needLock,
                                  Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
                                  List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
@@ -1512,13 +1554,17 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
                 resource = createRIAndRelationsFromYaml(yamlName, resource, instancesToCreate, topologyTemplateYaml,
                     nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName, null);
             }
-
             log.trace("************* Finished to create nodes, RI and Relation  from yaml {}", yamlName);
             loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
                 "Finished to create nodes, RI and Relation  from yaml: {}", yamlName);
             // validate update vf module group names
+            Optional<Map<String, GroupDefinition>> asdGroups = checkAndCreateAsdTypeVfModules(parsedToscaYamlInfo.getInstances());
+            Map<String, GroupDefinition> parsedGroups = parsedToscaYamlInfo.getGroups();
+            if (asdGroups.isPresent()) {
+                parsedGroups.putAll(asdGroups.get());
+            }
             final Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
-                .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
+                .validateUpdateVfGroupNames(parsedGroups, resource.getSystemName());
             if (validateUpdateVfGroupNamesRes.isRight()) {
                 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
                 throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right().value());
@@ -1531,7 +1577,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
             if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
                 groups = validateUpdateVfGroupNamesRes.left().value();
             } else {
-                groups = parsedToscaYamlInfo.getGroups();
+                groups = parsedGroups;
             }
             final Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, groups);
             if (createGroupsOnResource.isRight()) {
@@ -1594,6 +1640,67 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
         }
     }
 
+    private Optional<Map<String, GroupDefinition>> checkAndCreateAsdTypeVfModules(Map<String, UploadComponentInstanceInfo> instances) {
+        Map<String, GroupDefinition> addAsdGroups = new HashMap<>();
+        if (isNotEmpty(instances) || instances != null) {
+            for (Map.Entry<String, UploadComponentInstanceInfo> instance : instances.entrySet()) {
+                if (isNotEmpty(instance.getValue().getArtifacts()) || instance.getValue().getArtifacts() != null) {
+                    Map<String, UploadArtifactInfo> artifactsMap = instance.getValue().getArtifacts()
+                        .get(ToscaTagNamesEnum.ARTIFACTS.getElementName());
+                    if (isNotEmpty(artifactsMap) || artifactsMap != null) {
+                        for (Map.Entry<String, UploadArtifactInfo> artifact : artifactsMap.entrySet()) {
+                            if (artifact.getValue().getType().equals(Constants.ASD_DEPLOYMENT_ITEM)) {
+                                GroupDefinition groupDefinition = new GroupDefinition();
+                                groupDefinition.setName(artifact.getKey());
+                                groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
+                                addAsdTypeProperties(groupDefinition);
+                                addAsdGroups.put(groupDefinition.getName(), groupDefinition);
+                            }
+                        }
+                    }
+                }
+            }
+        }
+        return Optional.of(addAsdGroups);
+    }
+
+    private void addAsdTypeProperties(GroupDefinition groupDefinition) {
+        List<GroupProperty> properties = new ArrayList<>();
+        GroupProperty propIsBase = new GroupProperty();
+        propIsBase.setName(Constants.IS_BASE);
+        propIsBase.setValue("true");
+        properties.add(propIsBase);
+        GroupProperty propVfModuleLabel = new GroupProperty();
+        propVfModuleLabel.setName(Constants.VF_MODULE_LABEL);
+        propVfModuleLabel.setValue(groupDefinition.getName());
+        properties.add(propVfModuleLabel);
+        GroupProperty propVfModuleDescription = new GroupProperty();
+        propVfModuleDescription.setName(Constants.VF_MODULE_DESCRIPTION);
+        propVfModuleDescription.setValue("VF Module representing deployment item " + groupDefinition.getName());
+        properties.add(propVfModuleDescription);
+        GroupProperty propMinVfModuleInstances = new GroupProperty();
+        propMinVfModuleInstances.setName(Constants.MIN_VF_MODULE_INSTANCES);
+        propMinVfModuleInstances.setValue("1");
+        properties.add(propMinVfModuleInstances);
+        GroupProperty propMaxVfModuleInstances = new GroupProperty();
+        propMaxVfModuleInstances.setName(Constants.MAX_VF_MODULE_INSTANCES);
+        propMaxVfModuleInstances.setValue("1");
+        properties.add(propMaxVfModuleInstances);
+        GroupProperty propInitialCount = new GroupProperty();
+        propInitialCount.setName(Constants.INITIAL_COUNT);
+        propInitialCount.setValue("1");
+        properties.add(propInitialCount);
+        GroupProperty propVfModuleType = new GroupProperty();
+        propVfModuleType.setName(Constants.VF_MODULE_TYPE);
+        propVfModuleType.setValue("Base");
+        properties.add(propVfModuleType);
+        GroupProperty propVolumeGroup = new GroupProperty();
+        propVolumeGroup.setName(Constants.VOLUME_GROUP);
+        propVolumeGroup.setValue("false");
+        properties.add(propVolumeGroup);
+        groupDefinition.convertFromGroupProperties(properties);
+    }
+
     private boolean processSubstitutableAsNodeType(final Resource resource, final ParsedToscaYamlInfo parsedToscaYamlInfo) {
         return !resource.getResourceType().isAtomicType() && StringUtils.isNotEmpty(resource.getModel())
             && parsedToscaYamlInfo.getSubstitutionMappingNodeType() != null;
@@ -1655,7 +1762,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
     }
 
     private Resource createPoliciesOnResource(Resource resource, Map<String, PolicyDefinition> policies) {
-        policyBusinessLogic.createPoliciesFromParsedCsar(resource, policies);
+        policyBusinessLogic.createPolicies(resource, policies);
         return resource;
     }
 
@@ -1819,10 +1926,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
         final List<PropertyDefinition> resourceProperties = resource.getProperties();
         for (PropertyDefinition propertyDefinition : resourceProperties) {
             final Either<PropertyDefinition, StorageOperationStatus> addPropertyEither = toscaOperationFacade
-                .addPropertyToComponent(propertyDefinition.getName(), propertyDefinition, resource);
+                .addPropertyToComponent(propertyDefinition, resource);
 
             if (addPropertyEither.isRight()) {
-                final String error = String.format("failed to add properties from yaml: {}", addPropertyEither.right().value());
+                final String error = String.format("failed to add properties from yaml: %s", addPropertyEither.right().value());
                 loggerSupportability.log(LoggerSupportabilityActions.CREATE_PROPERTIES, resource.getComponentMetadataForSupportLog(),
                     StatusCode.ERROR,
                     error);
@@ -1836,14 +1943,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
         List<GroupDefinition> result = new ArrayList<>();
         List<ComponentInstance> componentInstances = component.getComponentInstances();
         if (groups != null) {
-            Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
-            if (validateCyclicGroupsDependencies.isRight()) {
-                throw new ByResponseFormatComponentException(validateCyclicGroupsDependencies.right().value());
-            }
             for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
                 String groupName = entry.getKey();
                 GroupDefinition groupDefinition = entry.getValue();
                 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
+
                 updatedGroupDefinition.setMembers(null);
                 Map<String, String> members = groupDefinition.getMembers();
                 if (members != null) {
@@ -1881,91 +1985,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
         updatedGroupDefinition.setMembers(relevantInstances);
     }
 
-    /**
-     * This Method validates that there is no cyclic group dependencies. meaning group A as member in group B which is member in group A
-     *
-     * @param allGroups
-     * @return
-     */
-    private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
-        Either<Boolean, ResponseFormat> result = Either.left(true);
-        try {
-            Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
-            while (allGroupsItr.hasNext() && result.isLeft()) {
-                Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
-                // Fetches a group member A
-                String groupAName = groupAEntry.getKey();
-                // Finds all group members in group A
-                Set<String> allGroupAMembersNames = new HashSet<>();
-                fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
-                // If A is a group member of itself found cyclic dependency
-                if (allGroupAMembersNames.contains(groupAName)) {
-                    ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
-                    result = Either.right(responseFormat);
-                }
-            }
-        } catch (Exception e) {
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
-            result = Either.right(responseFormat);
-            log.debug("Exception occurred when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
-        }
-        return result;
-    }
-
-    /**
-     * This Method fills recursively the set groupMembers with all the members of the given group which are also of type group.
-     *
-     * @param groupName
-     * @param allGroups
-     * @param allGroupMembers
-     * @return
-     */
-    private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups, Set<String> allGroupMembers) {
-        // Found Cyclic dependency
-        if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
-            return;
-        }
-        GroupDefinition groupDefinition = allGroups.get(groupName);
-        // All Members Of Current Group Resource Instances & Other Groups
-        Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
-        // Filtered Members Of Current Group containing only members which
-
-        // are groups
-        List<String> currGroupFilteredMembers = currGroupMembers.stream().
-            // Keep Only Elements of type group and not Resource Instances
-                filter(allGroups::containsKey).
-            // Add Filtered Elements to main Set
-                peek(allGroupMembers::add).
-            // Collect results
-                collect(toList());
-        // Recursively call the method for all the filtered group members
-        for (String innerGroupName : currGroupFilteredMembers) {
-            fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
-        }
-    }
-
-    private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
-                                                               Set<String> allGroupMembers) {
-        boolean stop = !allGroups.containsKey(groupName);
-        // In Case Not Group Stop
-        // In Case Group Has no members stop
-        if (!stop) {
-            GroupDefinition groupDefinition = allGroups.get(groupName);
-            stop = isEmpty(groupDefinition.getMembers());
-        }
-        // In Case all group members already contained stop
-        if (!stop) {
-            final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
-            Set<String> membersOfTypeGroup = allMembers.stream().
-                // Filter In Only Group members
-                    filter(allGroups::containsKey).
-                // Collect
-                    collect(toSet());
-            stop = allGroupMembers.containsAll(membersOfTypeGroup);
-        }
-        return stop;
-    }
-
     private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
                                                   Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
                                                   String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
@@ -2099,8 +2118,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
                     return Either.right(createArtifactsFromCsar.right().value());
                 }
                 return Either.left(createArtifactsFromCsar.left().value());
-            } else {
-                return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock, inTransaction);
             }
         }
         return Either.left(resource);
@@ -3368,6 +3385,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
                 ToscaArtifactDataDefinition to = new ToscaArtifactDataDefinition();
                 to.setFile(entry.getValue().getFile());
                 to.setType(entry.getValue().getType());
+                if (isNotEmpty(entry.getValue().getProperties())) {
+                    Map<String, Object> newPropertiesMap = new HashMap<>();
+                    List<UploadPropInfo> artifactPropsInfo = entry.getValue().getProperties();
+                    for (UploadPropInfo propInfo : artifactPropsInfo) {
+                        newPropertiesMap.put(propInfo.getName(), propInfo.getValue());
+                    }
+                    to.setProperties(newPropertiesMap);
+                }
                 toscaArtifacts.put(entry.getKey(), to);
             }
             componentInstance.setToscaArtifacts(toscaArtifacts);
@@ -3414,7 +3439,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
         } else {
             Either<Resource, StorageOperationStatus> findResourceEither = StringUtils.isEmpty(resource.getModel()) ?
                 toscaOperationFacade.getByToscaResourceNameMatchingVendorRelease(uploadComponentInstanceInfo.getType(),
-                    ((ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition()).getVendorRelease()):
+                    ((ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition()).getVendorRelease()) :
                 toscaOperationFacade.getLatestByToscaResourceNameAndModel(uploadComponentInstanceInfo.getType(), resource.getModel());
             if (findResourceEither.isRight()) {
                 log.debug("validateResourceInstanceBeforeCreate - not found latest version for resource instance with name {} and type {}",
@@ -3599,9 +3624,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
             if (oldResource.getCsarUUID() != null) {
                 newResource.setCsarUUID(oldResource.getCsarUUID());
             }
-            if (oldResource.getCsarVersionId() != null) {
-                newResource.setCsarVersionId(oldResource.getCsarVersionId());
-            }
             if (oldResource.getImportedToscaChecksum() != null) {
                 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
             }
@@ -3702,9 +3724,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
         if (newResource.getResourceType().isAtomicType() && !newResource.getName().equals("Root")
             && newResource.getResourceType() != ResourceTypeEnum.CVFC) {
             ResourceTypeEnum updatedResourceType = newResource.getResourceType();
-            Component derivedFromResource = getParentComponent(newResource);
-            if (derivedFromResource.getComponentType() == ComponentTypeEnum.RESOURCE) {
-                Resource parentResource = (Resource) derivedFromResource;
+            Optional<Component> derivedFromResourceOptional = getParentComponent(newResource);
+            if (derivedFromResourceOptional.isPresent() && derivedFromResourceOptional.get().getComponentType() == ComponentTypeEnum.RESOURCE) {
+                Resource parentResource = (Resource) derivedFromResourceOptional.get();
                 if (!(parentResource.isAbstract() && (ResourceTypeEnum.VFC == parentResource.getResourceType()
                     || ResourceTypeEnum.ABSTRACT == parentResource.getResourceType())) && parentResource.getResourceType() != updatedResourceType
                     && oldResource.getResourceType() != updatedResourceType) {
@@ -3719,7 +3741,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
         }
     }
 
-    private Component getParentComponent(Resource newResource) {
+    private Optional<Component> getParentComponent(Resource newResource) {
+        if (newResource.getDerivedFrom() == null) {
+            return Optional.empty();
+        }
         String toscaResourceNameDerivedFrom = newResource.getDerivedFrom().get(0);
         Either<Component, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade
             .getLatestByToscaResourceName(toscaResourceNameDerivedFrom, newResource.getModel());
@@ -3729,7 +3754,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
             log.debug("#mergeOldResourceMetadataWithNew - derived from resource {} not found", toscaResourceNameDerivedFrom);
             throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, toscaResourceNameDerivedFrom);
         }
-        return latestByToscaResourceName.left().value();
+        return Optional.of(latestByToscaResourceName.left().value());
     }
 
     private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user, boolean inTransaction, boolean needLock) {
@@ -3846,7 +3871,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
                                                                          Resource resource, List<?> validationObjects, AuditingActionEnum actionEnum,
                                                                          Either<Boolean, ResponseFormat> eitherResult, String type,
                                                                          boolean inTransaction) {
-        Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(UniqueIdBuilder.buildCapabilityTypeUid(resource.getModel(), type), inTransaction);
+        Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(
+            UniqueIdBuilder.buildCapabilityTypeUid(resource.getModel(), type), inTransaction);
         if (eitherCapTypeFound.isRight()) {
             if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
                 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
@@ -4130,6 +4156,53 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
         }
     }
 
+    private boolean isComponentSystemDeployed(Resource resource) {
+        return resource.getComponentMetadataDefinition().getMetadataDataDefinition().isNormative();
+    }
+
+    /**
+     * Deletes every version of the provided resource
+     *
+     * @param resourceId the resource identifier
+     * @param user       the user that performs the deletion
+     * @return
+     * @throws ComponentException if there is any error in the deletion of the resource operation
+     */
+    public void deleteResourceAllVersions(String resourceId, User user) {
+        validateUserExists(user);
+        Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
+        if (resourceStatus.isRight()) {
+            log.debug("Failed to get resource {}", resourceId);
+            componentException(resourceStatus.right().value());
+        }
+        Resource resource = resourceStatus.left().value();
+        if (isComponentSystemDeployed(resource)) {
+            throw new ByActionStatusComponentException(ActionStatus.CANNOT_DELETE_SYSTEM_DEPLOYED_RESOURCES, ComponentTypeEnum.RESOURCE.getValue(),
+                resource.getName());
+        }
+        if (Boolean.FALSE.equals(resource.isArchived())) {
+            log.debug("The resource, {}, requested for delete has not been archived.", resourceId);
+            throw new ComponentException(ActionStatus.COMPONENT_NOT_ARCHIVED, resourceId);
+        }
+        try {
+            String model = resource.getModel();
+            final Optional<Model> modelOptional = modelOperation.findModelByName(model);
+            List<String> deletedResourceList = toscaOperationFacade.deleteComponent(resource.getInvariantUUID(), NodeTypeEnum.Resource, true);
+            if (log.isDebugEnabled()) {
+                deletedResourceList.forEach(deletedR -> log.debug("Component {} was deleted.", deletedR));
+            }
+            if (modelOptional.isPresent() && modelOptional.get().getModelType() == ModelTypeEnum.NORMATIVE_EXTENSION) {
+                modelOperation.deleteModel(modelOptional.get(), true);
+            }
+            toscaOperationFacade.commitAndCheck(resource.getUniqueId());
+            updateCatalog(resource, ChangeTypeEnum.DELETE);
+        } catch (ComponentException exception) {
+            log.debug("Failed to delete resource, {} ", resourceId);
+            janusGraphDao.rollback();
+            throw exception;
+        }
+    }
+
     public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
         validateUserExists(user);