Fix instance declared inputs mapped to substitution mapping
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / ServiceImportBusinessLogic.java
index 151717f..b3f1d57 100644 (file)
@@ -42,6 +42,8 @@ import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Optional;
 import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicReference;
 import java.util.regex.Pattern;
 import java.util.stream.Collectors;
@@ -73,7 +75,6 @@ import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphDao;
 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
 import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
-import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
 import org.openecomp.sdc.be.datatypes.elements.CustomYamlFunction;
 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
 import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
@@ -99,6 +100,7 @@ import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
 import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
 import org.openecomp.sdc.be.model.Component;
 import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
 import org.openecomp.sdc.be.model.ComponentInstanceInput;
 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
 import org.openecomp.sdc.be.model.ComponentParametersView;
@@ -144,6 +146,7 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.openecomp.sdc.be.model.operations.impl.ArtifactTypeOperation;
 import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation;
 import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation;
+import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
@@ -203,6 +206,8 @@ public class ServiceImportBusinessLogic {
 
     private final GroupTypeImportManager groupTypeImportManager;
     private final GroupTypeOperation groupTypeOperation;
+    private InterfaceLifecycleOperation interfaceLifecycleTypeOperation;
+    private InterfaceLifecycleTypeImportManager interfaceLifecycleTypeImportManager;
 
     private final CapabilityTypeImportManager capabilityTypeImportManager;
     private final CapabilityTypeOperation capabilityTypeOperation;
@@ -219,6 +224,8 @@ public class ServiceImportBusinessLogic {
                                       final DataTypeBusinessLogic dataTypeBusinessLogic, final ArtifactTypeOperation artifactTypeOperation,
                                       final ArtifactTypeImportManager artifactTypeImportManager, final GroupTypeImportManager groupTypeImportManager,
                                       final GroupTypeOperation groupTypeOperation,
+                                      final InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+                                      final InterfaceLifecycleTypeImportManager interfaceLifecycleTypeImportManager,
                                       final CapabilityTypeImportManager capabilityTypeImportManager,
                                       final CapabilityTypeOperation capabilityTypeOperation) {
         this.componentsUtils = componentsUtils;
@@ -242,6 +249,8 @@ public class ServiceImportBusinessLogic {
         this.artifactTypeImportManager = artifactTypeImportManager;
         this.groupTypeImportManager = groupTypeImportManager;
         this.groupTypeOperation = groupTypeOperation;
+        this.interfaceLifecycleTypeOperation = interfaceLifecycleTypeOperation;
+        this.interfaceLifecycleTypeImportManager = interfaceLifecycleTypeImportManager;
         this.capabilityTypeImportManager = capabilityTypeImportManager;
         this.capabilityTypeOperation = capabilityTypeOperation;
     }
@@ -282,43 +291,47 @@ public class ServiceImportBusinessLogic {
     protected Service createServiceFromCsar(Service service, User user, Map<String, byte[]> csarUIPayload, String csarUUID) {
         log.trace("************* created successfully from YAML, resource TOSCA ");
         try {
-            ServiceCsarInfo csarInfo = csarBusinessLogic.getCsarInfo(service, null, user, csarUIPayload, csarUUID);
-
-            final Map<String, Object> dataTypesToCreate = getDatatypesToCreate(service.getModel(), csarInfo);
+            final ServiceCsarInfo csarInfo = csarBusinessLogic.getCsarInfo(service, null, user, csarUIPayload, csarUUID);
+            final String serviceModel = service.getModel();
+            final Map<String, Object> dataTypesToCreate = getDatatypesToCreate(serviceModel, csarInfo);
             if (MapUtils.isNotEmpty(dataTypesToCreate)) {
-                dataTypeBusinessLogic.createDataTypeFromYaml(new Yaml().dump(dataTypesToCreate), service.getModel(), true);
-                dataTypesToCreate.entrySet().stream().forEach(createdOrUpdatedDataType -> {
-                    applicationDataTypeCache.reload(service.getModel(),
-                        UniqueIdBuilder.buildDataTypeUid(service.getModel(), createdOrUpdatedDataType.getKey()));
-                });
+                dataTypeBusinessLogic.createDataTypeFromYaml(new Yaml().dump(dataTypesToCreate), serviceModel, true);
+                dataTypesToCreate.keySet().forEach(key ->
+                    applicationDataTypeCache.reload(serviceModel, UniqueIdBuilder.buildDataTypeUid(serviceModel, key))
+                );
             }
 
-            final Map<String, Object> artifactTypesToCreate = getArtifactTypesToCreate(service.getModel(), csarInfo);
+            final Map<String, Object> artifactTypesToCreate = getArtifactTypesToCreate(serviceModel, csarInfo);
             if (MapUtils.isNotEmpty(artifactTypesToCreate)) {
-                artifactTypeImportManager.createArtifactTypes(new Yaml().dump(artifactTypesToCreate), service.getModel(), true);
+                artifactTypeImportManager.createArtifactTypes(new Yaml().dump(artifactTypesToCreate), serviceModel, true);
             }
 
-            final List<NodeTypeDefinition> nodeTypesToCreate = getNodeTypesToCreate(service.getModel(), csarInfo);
+            final List<NodeTypeDefinition> nodeTypesToCreate = getNodeTypesToCreate(serviceModel, csarInfo);
             if (CollectionUtils.isNotEmpty(nodeTypesToCreate)) {
-                createNodeTypes(nodeTypesToCreate, service.getModel(), csarInfo.getModifier());
+                createNodeTypes(nodeTypesToCreate, serviceModel, csarInfo.getModifier());
             }
 
-            final Map<String, Object> groupTypesToCreate = getGroupTypesToCreate(service.getModel(), csarInfo);
+            final Map<String, Object> groupTypesToCreate = getGroupTypesToCreate(serviceModel, csarInfo);
             if (MapUtils.isNotEmpty(groupTypesToCreate)) {
                 final Map<String, ToscaTypeMetadata> toscaTypeMetadata = fillToscaTypeMetadata(groupTypesToCreate);
                 final ToscaTypeImportData toscaTypeImportData = new ToscaTypeImportData(new Yaml().dump(groupTypesToCreate), toscaTypeMetadata);
-                groupTypeImportManager.createGroupTypes(toscaTypeImportData, service.getModel(), true);
+                groupTypeImportManager.createGroupTypes(toscaTypeImportData, serviceModel, true);
+            }
+
+            final Map<String, Object> interfaceTypesToCreate = getInterfaceTypesToCreate(serviceModel, csarInfo);
+            if (MapUtils.isNotEmpty(interfaceTypesToCreate)) {
+                interfaceLifecycleTypeImportManager.createLifecycleTypes(new Yaml().dump(interfaceTypesToCreate), serviceModel, true);
             }
 
-            final Map<String, Object> capabilityTypesToCreate = getCapabilityTypesToCreate(service.getModel(), csarInfo);
+            final Map<String, Object> capabilityTypesToCreate = getCapabilityTypesToCreate(serviceModel, csarInfo);
 
             if (MapUtils.isNotEmpty(capabilityTypesToCreate)) {
-                capabilityTypeImportManager.createCapabilityTypes(new Yaml().dump(capabilityTypesToCreate), service.getModel(), true);
+                capabilityTypeImportManager.createCapabilityTypes(new Yaml().dump(capabilityTypesToCreate), serviceModel, true);
             }
 
             Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractTypesInfo();
-            Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = serviceImportParseLogic
-                .findNodeTypesArtifactsToHandle(nodeTypesInfo, csarInfo, service);
+            Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes
+                = serviceImportParseLogic.findNodeTypesArtifactsToHandle(nodeTypesInfo, csarInfo, service);
             if (findNodeTypesArtifactsToHandleRes.isRight()) {
                 log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID());
                 throw new ComponentException(findNodeTypesArtifactsToHandleRes.right().value());
@@ -426,6 +439,20 @@ public class ServiceImportBusinessLogic {
         return artifactTypesToCreate;
     }
 
+    private Map<String, Object> getInterfaceTypesToCreate(final String model, final CsarInfo csarInfo) {
+        final Map<String, Object> interfaceTypesToCreate = new HashMap<>();
+        Map<String, Object> interfacetypeMap = csarInfo.getInterfaceTypes();
+
+        interfacetypeMap.entrySet().forEach(interfacetypeDef -> {
+            Either<InterfaceDefinition, StorageOperationStatus> interfaceDefinition =
+                interfaceLifecycleTypeOperation.getInterface(UniqueIdBuilder.buildInterfaceTypeUid(model, interfacetypeDef.getKey()));
+            if (interfaceDefinition.isRight() && interfaceDefinition.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
+                interfaceTypesToCreate.put(interfacetypeDef.getKey(), interfacetypeDef.getValue());
+            }
+        });
+        return interfaceTypesToCreate;
+    }
+
     private boolean hasNewProperties(final Either<DataTypeDefinition, JanusGraphOperationStatus> result,
                                      final Map<String, Map<String, Object>> dataType) {
         return result.isLeft() && dataType.containsKey("properties") && result.left().value().getProperties() != null
@@ -436,7 +463,7 @@ public class ServiceImportBusinessLogic {
         NodeTypesMetadataList nodeTypesMetadataList = new NodeTypesMetadataList();
         List<NodeTypeMetadata> nodeTypeMetadataList = new ArrayList<>();
         final Map<String, Object> allTypesToCreate = new HashMap<>();
-        nodeTypesToCreate.stream().forEach(nodeType -> {
+        nodeTypesToCreate.forEach(nodeType -> {
             allTypesToCreate.put(nodeType.getMappedNodeType().getKey(), nodeType.getMappedNodeType().getValue());
             nodeTypeMetadataList.add(nodeType.getNodeTypeMetadata());
         });
@@ -454,14 +481,14 @@ public class ServiceImportBusinessLogic {
                 namesOfNodeTypesToCreate.add(nodeTypeDefinition);
             } else if (result.isLeft()) {
                 Resource latestResource = (Resource) result.left().value();
-                Entry<String, Object> latestMappedToscaTemplate = getResourceToscaTemplate(latestResource.getUniqueId(),
+                Entry<String, Object> existingMappedToscaTemplate = getResourceToscaTemplate(latestResource.getUniqueId(),
                     latestResource.getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE), csarInfo.getModifier().getUserId());
-                Map<String, Object> mappedToscaTemplate = (Map<String, Object>) nodeTypeDefinition.getMappedNodeType().getValue();
-                Map<String, Object> newMappedToscaTemplate =
-                    getNewChangesToToscaTemplate(mappedToscaTemplate, (Map<String, Object>) latestMappedToscaTemplate.getValue());
-                if (!newMappedToscaTemplate.equals(latestMappedToscaTemplate.getValue())) {
-                    latestMappedToscaTemplate.setValue(newMappedToscaTemplate);
-                    nodeTypeDefinition.setMappedNodeType(latestMappedToscaTemplate);
+                Map<String, Object> newMappedToscaTemplate = (Map<String, Object>) nodeTypeDefinition.getMappedNodeType().getValue();
+                Map<String, Object> combinedMappedToscaTemplate =
+                    getNewChangesToToscaTemplate(newMappedToscaTemplate, (Map<String, Object>) existingMappedToscaTemplate.getValue());
+                if (!combinedMappedToscaTemplate.equals(existingMappedToscaTemplate.getValue())) {
+                    existingMappedToscaTemplate.setValue(combinedMappedToscaTemplate);
+                    nodeTypeDefinition.setMappedNodeType(existingMappedToscaTemplate);
                     namesOfNodeTypesToCreate.add(nodeTypeDefinition);
                 }
             }
@@ -482,28 +509,112 @@ public class ServiceImportBusinessLogic {
         return eitherNodeTypes.left().value().entrySet().iterator().next();
     }
 
-    private Map<String, Object> getNewChangesToToscaTemplate(Map<String, Object> mappedToscaTemplate, Map<String, Object> latestMappedToscaTemplate) {
-        Map<String, Object> newMappedToscaTemplate = new HashMap<>(latestMappedToscaTemplate);
+    private Map<String, Object> getNewChangesToToscaTemplate(Map<String, Object> newMappedToscaTemplate,
+                                                             Map<String, Object> existingMappedToscaTemplate) {
+        Map<String, Object> combinedMappedToscaTemplate = new HashMap<>(existingMappedToscaTemplate);
+        combinePropertiesIntoToscaTemplate((Map<String, Object>) newMappedToscaTemplate.get("properties"),
+            (Map<String, Object>) existingMappedToscaTemplate.get("properties"), combinedMappedToscaTemplate);
+        combineAttributesIntoToscaTemplate((Map<String, Object>) newMappedToscaTemplate.get("attributes"),
+            (Map<String, Object>) existingMappedToscaTemplate.get("attributes"), combinedMappedToscaTemplate);
+        combineRequirementsIntoToscaTemplate((List<Map<String, Object>>) newMappedToscaTemplate.get("requirements"),
+            (List<Map<String, Object>>) existingMappedToscaTemplate.get("requirements"), combinedMappedToscaTemplate);
+        combineCapabilitiesIntoToscaTemplate((Map<String, Object>) newMappedToscaTemplate.get("capabilities"),
+            (Map<String, Object>) existingMappedToscaTemplate.get("capabilities"), combinedMappedToscaTemplate);
+        combineInterfacesIntoToscaTemplate((Map<String, Map<String, Object>>) newMappedToscaTemplate.get("interfaces"),
+            (Map<String, Map<String, Object>>) existingMappedToscaTemplate.get("interfaces"), combinedMappedToscaTemplate);
+        return combinedMappedToscaTemplate;
+    }
+
+    private void combineInterfacesIntoToscaTemplate(Map<String, Map<String, Object>> newInterfaces,
+                                                    Map<String, Map<String, Object>> existingInterfaces,
+                                                    Map<String, Object> combinedMappedToscaTemplate) {
+        Map<String, Map<String, Object>> combinedInterfaces = combineAdditionalInterfaces(existingInterfaces, newInterfaces);
+        if ((MapUtils.isEmpty(existingInterfaces) && MapUtils.isNotEmpty(combinedInterfaces))
+            || (MapUtils.isNotEmpty(existingInterfaces) && !existingInterfaces.equals(combinedInterfaces))) {
+            combinedMappedToscaTemplate.put("interfaces", combinedInterfaces);
+        }
+    }
+
+    private void combineCapabilitiesIntoToscaTemplate(Map<String, Object> newCapabilities, Map<String, Object> existingCapabilities,
+                                                      Map<String, Object> combinedMappedToscaTemplate) {
+        Map<String, Object> combinedCapabilities = combineEntries(newCapabilities, existingCapabilities);
+        if ((MapUtils.isEmpty(existingCapabilities) && MapUtils.isNotEmpty(combinedCapabilities)) ||
+            (MapUtils.isNotEmpty(existingCapabilities) && !combinedCapabilities.equals(existingCapabilities))) {
+            combinedMappedToscaTemplate.put("capabilities", combinedCapabilities);
+        }
+    }
+
+    private void combineRequirementsIntoToscaTemplate(List<Map<String, Object>> newRequirements, List<Map<String, Object>> existingRequirements,
+                                                      Map<String, Object> combinedMappedToscaTemplate) {
+        List<Map<String, Object>> combinedRequirements = combineAdditionalRequirements(newRequirements, existingRequirements);
+        if ((CollectionUtils.isEmpty(existingRequirements) && CollectionUtils.isNotEmpty(combinedRequirements))
+            || (CollectionUtils.isNotEmpty(existingRequirements) && !combinedRequirements.equals(existingRequirements))) {
+            combinedMappedToscaTemplate.put("requirements", combinedRequirements);
+        }
+    }
+
+    private void combineAttributesIntoToscaTemplate(Map<String, Object> newAttributes, Map<String, Object> existingAttributes,
+                                                    Map<String, Object> combinedMappedToscaTemplate) {
+        Map<String, Object> combinedAttributes = combineEntries(newAttributes, existingAttributes);
+        if ((MapUtils.isEmpty(existingAttributes) && MapUtils.isNotEmpty(combinedAttributes)) ||
+            (MapUtils.isNotEmpty(existingAttributes) && !combinedAttributes.equals(existingAttributes))) {
+            combinedMappedToscaTemplate.put("attributes", combinedAttributes);
+        }
+    }
+
+    private void combinePropertiesIntoToscaTemplate(Map<String, Object> newProperties, Map<String, Object> existingProperties,
+                                                    Map<String, Object> combinedMappedToscaTemplate) {
+        Map<String, Object> combinedProperties = combineEntries(newProperties, existingProperties);
+        if ((MapUtils.isEmpty(existingProperties) && MapUtils.isNotEmpty(combinedProperties)) ||
+            (MapUtils.isNotEmpty(existingProperties) && !combinedProperties.equals(existingProperties))) {
+            combinedMappedToscaTemplate.put("properties", combinedProperties);
+        }
+    }
+
+    private Map<String, Map<String, Object>> combineAdditionalInterfaces(Map<String, Map<String, Object>> existingInterfaces,
+                                                                         Map<String, Map<String, Object>> newInterfaces) {
+        if (MapUtils.isEmpty(newInterfaces)) {
+            newInterfaces = new HashMap<>();
+        }
+        Map<String, Map<String, Object>> combinedEntries = new HashMap<>(newInterfaces);
+        if (MapUtils.isEmpty(existingInterfaces)) {
+            return combinedEntries;
+        }
+        existingInterfaces.entrySet().forEach(interfaceDef -> {
+            combinedEntries.entrySet().stream().filter((interFace) -> interFace.getValue().get("type").equals((interfaceDef.getValue()).get("type")))
+                .findFirst().ifPresentOrElse((interFace) -> {
+                    interFace.getValue().putAll(interfaceDef.getValue());
+                }, () -> {
+                    combinedEntries.put(interfaceDef.getKey(), interfaceDef.getValue());
+                });
+        });
+        return combinedEntries;
+    }
 
-        Map<String, Object> properties = (Map<String, Object>) mappedToscaTemplate.get("properties");
-        Map<String, Object> latestProperties = (Map<String, Object>) latestMappedToscaTemplate.get("properties");
-        Map<String, Object> allProperties = combinedEntries(properties, latestProperties);
-        if ((MapUtils.isEmpty(latestProperties) && MapUtils.isNotEmpty(allProperties)) ||
-            (MapUtils.isNotEmpty(latestProperties) && !allProperties.equals(latestProperties))) {
-            newMappedToscaTemplate.put("properties", allProperties);
+    private List<Map<String, Object>> combineAdditionalRequirements(List<Map<String, Object>> newReqs,
+                                                                    List<Map<String, Object>> existingResourceReqs) {
+        if (CollectionUtils.isEmpty(existingResourceReqs)) {
+            existingResourceReqs = new ArrayList<>();
         }
-        return newMappedToscaTemplate;
+        Set<Map<String, Object>> combinedReqs = new TreeSet<>((map1, map2) ->
+            map1.keySet().equals(map2.keySet()) ? 0 : map1.keySet().iterator().next().compareTo(map2.keySet().iterator().next()));
+        combinedReqs.addAll(existingResourceReqs);
+        if (CollectionUtils.isEmpty(newReqs)) {
+            return new ArrayList<>(combinedReqs);
+        }
+        combinedReqs.addAll(newReqs);
+        return new ArrayList<>(combinedReqs);
     }
 
-    private Map<String, Object> combinedEntries(Map<String, Object> firstMap, Map<String, Object> secondMap) {
-        if (MapUtils.isEmpty(firstMap)) {
-            firstMap = new HashMap<>();
+    private Map<String, Object> combineEntries(Map<String, Object> newMap, Map<String, Object> existingMap) {
+        if (MapUtils.isEmpty(newMap)) {
+            newMap = new HashMap<>();
         }
-        Map<String, Object> combinedEntries = new HashMap<>(firstMap);
-        if (MapUtils.isEmpty(secondMap)) {
+        Map<String, Object> combinedEntries = new HashMap<>(newMap);
+        if (MapUtils.isEmpty(existingMap)) {
             return combinedEntries;
         }
-        combinedEntries.putAll(secondMap);
+        combinedEntries.putAll(existingMap);
         return combinedEntries;
     }
 
@@ -649,72 +760,69 @@ public class ServiceImportBusinessLogic {
 
     private Service updateInputs(final Service component, final String userId) {
         final List<InputDefinition> inputs = component.getInputs();
-        final List<ComponentInstance> componentInstances = component.getComponentInstances();
-        final String componentUniqueId = component.getUniqueId();
-        final Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component.getComponentInstancesProperties();
-        for (final InputDefinition input : inputs) {
-            if (isInputFromComponentInstanceProperty(input.getName(), componentInstances, componentInstancesProperties)) {
-                associateInputToComponentInstanceProperty(userId, input, componentInstances, componentInstancesProperties,
-                    componentUniqueId);
-            } else {
-                associateInputToServiceProperty(userId, input, component);
+        if (CollectionUtils.isNotEmpty(inputs)) {
+            final List<ComponentInstance> componentInstances = component.getComponentInstances();
+            final String componentUniqueId = component.getUniqueId();
+            for (final InputDefinition input : inputs) {
+                if (isInputFromComponentInstanceProperty(input.getName(), componentInstances)) {
+                    associateInputToComponentInstanceProperty(userId, input, componentInstances, componentUniqueId);
+                } else {
+                    associateInputToServiceProperty(userId, input, component);
+                }
             }
 
-        }
-
-        final Either<List<InputDefinition>, StorageOperationStatus> either
-            = toscaOperationFacade.updateInputsToComponent(inputs, componentUniqueId);
-        if (either.isRight()) {
-            throw new ComponentException(ActionStatus.GENERAL_ERROR);
+            Either<List<InputDefinition>, StorageOperationStatus> either = toscaOperationFacade.updateInputsToComponent(inputs, componentUniqueId);
+            if (either.isRight()) {
+                throw new ComponentException(ActionStatus.GENERAL_ERROR);
+            }
         }
 
         return component;
     }
 
-    private boolean isInputFromComponentInstanceProperty(final String inputName, final List<ComponentInstance> componentInstances,
-                                                         final Map<String, List<ComponentInstanceProperty>> componentInstancesProperties) {
+    private boolean isInputFromComponentInstanceProperty(final String inputName, final List<ComponentInstance> componentInstances) {
+
+        AtomicBoolean isInputFromCIProp = new AtomicBoolean(false);
         if (CollectionUtils.isNotEmpty(componentInstances)) {
-            // get instance's names
-            final List<String> componentInstancesNames = componentInstances.stream().map(ComponentInstanceDataDefinition::getNormalizedName)
-                .collect(toList());
-            final Optional<String> componentInstancesNameOptional = componentInstancesNames.stream()
-                .filter(cin -> inputName.startsWith(cin + "_")).findFirst();
-            if (componentInstancesNameOptional.isPresent() && MapUtils.isNotEmpty(componentInstancesProperties)) {
-                final Optional<String> componentInstanceIdOptional = componentInstancesProperties.keySet().stream()
-                    .filter(key -> key.endsWith("." + componentInstancesNameOptional.get())).findFirst();
-                if (componentInstanceIdOptional.isPresent()) {
-                    // get property's name
-                    final String propertyNameFromInput = extractPropertyNameFromInputName(inputName, componentInstancesNames);
-                    return componentInstancesProperties.get(componentInstanceIdOptional.get()).stream()
-                        .anyMatch(prop -> prop.getName().equals(propertyNameFromInput) && prop.getValue() != null
-                            && prop.getValue().contains(ToscaGetFunctionType.GET_INPUT.getFunctionName()));
+            outer: for (ComponentInstance instance : componentInstances) {
+                for (PropertyDefinition instanceProperty : instance.getProperties()) {
+                    if (CollectionUtils.isNotEmpty(instanceProperty.getGetInputValues())) {
+                        for (GetInputValueDataDefinition getInputValueDataDefinition : instanceProperty.getGetInputValues()) {
+                            if (inputName.equals(getInputValueDataDefinition.getInputName())) {
+                                isInputFromCIProp.set(true);
+                                break outer;
+                            }
+                        }
+                    }
                 }
             }
         }
-        return false;
+        return isInputFromCIProp.get();
     }
 
     private void associateInputToComponentInstanceProperty(final String userId, final InputDefinition input,
                                                            final List<ComponentInstance> componentInstances,
-                                                           final Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
                                                            String componentUniqueId) {
-        // From Instance
-        final List<String> componentInstancesNames = componentInstances.stream().map(ComponentInstanceDataDefinition::getNormalizedName)
-            .collect(toList());
-        final String propertyNameFromInput = extractPropertyNameFromInputName(input.getName(), componentInstancesNames);
-
-        final Optional<String> componentInstancesNameOptional = componentInstancesNames.stream()
-            .filter(cin -> input.getName().startsWith(cin + "_")).findFirst();
-
-        final Optional<String> componentInstanceIdOptional = componentInstancesProperties.keySet().stream()
-            .filter(key -> key.endsWith("." + componentInstancesNameOptional.get())).findFirst();
 
-        final String componentInstanceId = componentInstanceIdOptional.get();
-        final List<ComponentInstanceProperty> componentInstanceProperties = componentInstancesProperties.get(componentInstanceId);
+        String componentInstanceId = null;
+        ComponentInstanceProperty componentInstanceProperty = new ComponentInstanceProperty();
+
+        outer: for (ComponentInstance instance : componentInstances) {
+            for (PropertyDefinition instanceProperty : instance.getProperties()) {
+                if (CollectionUtils.isNotEmpty(instanceProperty.getGetInputValues())) {
+                    for (GetInputValueDataDefinition getInputValueDataDefinition : instanceProperty.getGetInputValues()) {
+                        if (input.getName().equals(getInputValueDataDefinition.getInputName())) {
+                            componentInstanceId = instance.getUniqueId();
+                            componentInstanceProperty = new ComponentInstanceProperty(instanceProperty);
+                            break outer;
+                        }
+                    }
+                }
+            }
+        }
 
-        final ComponentInstanceProperty componentInstanceProperty = componentInstanceProperties.stream()
-            .filter(prop -> prop.getName().equals(propertyNameFromInput) && prop.getValue() != null
-                && prop.getValue().contains(ToscaGetFunctionType.GET_INPUT.getFunctionName())).findFirst().get();
+        //unmapping instance property declared inputs from substitution mapping
+        input.setMappedToComponentProperty(false);
 
         // From Instance
         updateInput(input, componentInstanceProperty, userId, componentInstanceId);
@@ -771,12 +879,6 @@ public class ServiceImportBusinessLogic {
         input.setParentPropertyType(propertyDefinition.getType());
     }
 
-    private String extractPropertyNameFromInputName(final String inputName, final List<String> componentInstancesNames) {
-        final AtomicReference<String> result = new AtomicReference<>(inputName);
-        componentInstancesNames.forEach(cin -> result.set(result.get().replace(cin + "_", "")));
-        return result.get();
-    }
-
     protected Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum operation,
                                                                        List<ArtifactDefinition> createdArtifacts, String yamlFileName,
                                                                        CsarInfo csarInfo, Resource preparedResource,
@@ -1309,21 +1411,20 @@ public class ServiceImportBusinessLogic {
         if (MapUtils.isEmpty(policies)) {
             return Either.left(service);
         }
-        final Map<String, List<AttributeDefinition>> instanceAttributeMap =
-            service.getComponentInstancesAttributes()
+        Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes = service.getComponentInstancesAttributes();
+        final Map<String, List<AttributeDefinition>> instanceAttributeMap = new HashMap<>();
+        if (MapUtils.isNotEmpty(componentInstancesAttributes)) {
+            instanceAttributeMap.putAll(componentInstancesAttributes
                 .entrySet().stream()
-                .collect(
-                    toMap(Entry::getKey,
-                        entry -> entry.getValue().stream().map(AttributeDefinition.class::cast).collect(toList()))
-                );
+                .collect(toMap(Entry::getKey, entry -> entry.getValue().stream().map(AttributeDefinition.class::cast).collect(toList()))));
+        }
         policies.values().stream()
             .map(PolicyDataDefinition::getProperties)
             .flatMap(Collection::stream)
             .filter(PropertyDataDefinition::isToscaFunction)
-            .forEach(policyDefinition ->
-                toscaFunctionService
-                    .updateFunctionWithDataFromSelfComponent(policyDefinition.getToscaFunction(), service, service.getComponentInstancesProperties(),
-                        instanceAttributeMap)
+            .forEach(policyDefinition -> toscaFunctionService
+                .updateFunctionWithDataFromSelfComponent(policyDefinition.getToscaFunction(), service, service.getComponentInstancesProperties(),
+                    instanceAttributeMap)
             );
         policyBusinessLogic.createPolicies(service, policies);
         return getServiceResponseFormatEither(service);
@@ -2194,7 +2295,7 @@ public class ServiceImportBusinessLogic {
                 interfaceDef.setUniqueId(currentInterfaceDef.getType());
                 interfaceDef.setDescription(uploadInterfaceInfo.getDescription());
                 interfaceDef.setOperations(operationsToAdd);
-                instInterfacesMap.put(interfaceName, interfaceDef);
+                instInterfacesMap.put(currentInterfaceDef.getType(), interfaceDef);
                 currInterfacesMap.remove(interfaceName);
             }
         }
@@ -2563,7 +2664,8 @@ public class ServiceImportBusinessLogic {
             if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
                 uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
             }
-            Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, existingnodeTypeMap);
+            Resource refResource =
+                validateResourceInstanceBeforeCreate(yamlName, component.getModel(), uploadComponentInstanceInfo, existingnodeTypeMap);
             ComponentInstance componentInstance = new ComponentInstance();
             componentInstance.setComponentUid(refResource.getUniqueId());
             Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
@@ -2595,26 +2697,28 @@ public class ServiceImportBusinessLogic {
             componentInstance.setName(uploadComponentInstanceInfo.getName());
             componentInstance.setIcon(origResource.getIcon());
             resourcesInstancesMap.put(componentInstance, origResource);
-        } catch (Exception e) {
+        } catch (final ComponentException e) {
+            throw e;
+        } catch (final Exception e) {
             throw new ComponentException(ActionStatus.GENERAL_ERROR, e.getMessage());
         }
     }
 
-    protected Resource validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo,
+    protected Resource validateResourceInstanceBeforeCreate(String yamlName, String model, UploadComponentInstanceInfo uploadComponentInstanceInfo,
                                                             Map<String, Resource> nodeNamespaceMap) {
         Resource refResource;
         try {
             if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
                 refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
             } else {
-                Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
-                    .getLatestResourceByToscaResourceName(uploadComponentInstanceInfo.getType());
-                if (findResourceEither.isRight()) {
+                final Either<Component, StorageOperationStatus> resourceEither =
+                    toscaOperationFacade.getLatestByToscaResourceName(uploadComponentInstanceInfo.getType(), model);
+                if (resourceEither.isRight()) {
                     ResponseFormat responseFormat = componentsUtils
-                        .getResponseFormat(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
+                        .getResponseFormat(componentsUtils.convertFromStorageResponse(resourceEither.right().value()));
                     throw new ComponentException(responseFormat);
                 }
-                refResource = findResourceEither.left().value();
+                refResource = (Resource) resourceEither.left().value();
                 nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
             }
             String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
@@ -2632,7 +2736,9 @@ public class ServiceImportBusinessLogic {
                 throw new ComponentException(responseFormat);
             }
             return refResource;
-        } catch (Exception e) {
+        } catch (final ComponentException e) {
+            throw e;
+        } catch (final Exception e) {
             throw new ComponentException(ActionStatus.GENERAL_ERROR, e.getMessage());
         }
     }