Support for Test Topology Auto Design- Service Import
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / ArtifactsBusinessLogic.java
index 8a18879..c9e0a44 100644 (file)
@@ -28,6 +28,7 @@ import com.google.common.annotations.VisibleForTesting;
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
 import fj.data.Either;
+import io.vavr.control.Option;
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.math.BigDecimal;
@@ -42,6 +43,7 @@ import java.util.Map.Entry;
 import java.util.Objects;
 import java.util.Optional;
 import java.util.Set;
+import java.util.function.Consumer;
 import java.util.function.Function;
 import java.util.function.Predicate;
 import java.util.function.Supplier;
@@ -49,6 +51,7 @@ import java.util.stream.Collectors;
 import javax.servlet.http.HttpServletRequest;
 import javax.xml.XMLConstants;
 import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.parsers.SAXParser;
 import javax.xml.parsers.SAXParserFactory;
 import org.apache.commons.codec.binary.Base64;
 import org.apache.commons.collections.CollectionUtils;
@@ -65,9 +68,11 @@ import org.openecomp.sdc.be.components.impl.artifact.PayloadTypeEnum;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
+import org.openecomp.sdc.be.components.impl.utils.ComponentUtils;
 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
+import org.openecomp.sdc.be.components.utils.ArtifactUtils;
 import org.openecomp.sdc.be.components.utils.InterfaceOperationUtils;
 import org.openecomp.sdc.be.config.ArtifactConfiguration;
 import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -125,9 +130,7 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
 import org.openecomp.sdc.be.servlets.RepresentationUtils;
 import org.openecomp.sdc.be.tosca.CsarUtils;
-import org.openecomp.sdc.be.tosca.ToscaError;
 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
-import org.openecomp.sdc.be.tosca.ToscaRepresentation;
 import org.openecomp.sdc.be.user.Role;
 import org.openecomp.sdc.be.user.UserBusinessLogic;
 import org.openecomp.sdc.be.utils.TypeUtils;
@@ -355,38 +358,50 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         ArtifactDefinition artifactDefinition, Component component,
         User user, boolean isInCertificationRequest, boolean shouldLock, boolean inTransaction,
         boolean fetchTemplatesFromDB) {
-        generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
-        byte[] decodedPayload = artifactDefinition.getPayloadData();
-        artifactDefinition.setEsId(artifactDefinition.getUniqueId());
-        artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload));
-        return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition.getUniqueId(),
-                user, component.getComponentType(), component, decodedPayload, null, null, shouldLock, inTransaction);
-    }
 
-    private ArtifactDefinition generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
+        return decodeToscaArtifactPayload(
+            component, isInCertificationRequest, fetchTemplatesFromDB, artifactDefinition.getArtifactType()
+        ).left().bind(payload -> {
+            // TODO: Avoid output argument
+            artifactDefinition.setPayload(payload);
+            artifactDefinition.setEsId(artifactDefinition.getUniqueId());
+            artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(payload));
+            return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition,
+                AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition.getUniqueId(),
+                user, component.getComponentType(), component, payload, shouldLock, inTransaction
+            );
+        }).right().map(ex -> {
+            // TODO: This should not be done but in order to keep this refactoring small enough, we stop here.
+            // Bubble up this exception
+            throw ex;
+        });
+    }
+
+    private Either<byte[], ComponentException> decodeToscaArtifactPayload(
+        Component parent,
+        boolean isInCertificationRequest,
+        boolean fetchTemplatesFromDB,
+        String artifactType
+    ) {
         log.debug("tosca artifact generation");
-        if (ArtifactTypeEnum.TOSCA_CSAR.getType().equals(artifactInfo.getArtifactType())) {
-            Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
-            if (generated.isRight()) {
-                ResponseFormat error = generated.right().value();
-                log.debug("Failed to generate tosca csar for component {} error {}", parent.getUniqueId(), error);
-                throw new ByResponseFormatComponentException(error);
-            }
-            artifactInfo.setPayload(generated.left().value());
-
-        }
-        else {
-            Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
-            if (exportComponent.isRight()) {
-                ToscaError toscaError = exportComponent.right().value();
-                log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), toscaError);
-                ActionStatus status = componentsUtils.convertFromToscaError(toscaError);
-                throw new ByActionStatusComponentException(status);
-            }
-            log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
-            artifactInfo.setPayloadData(exportComponent.left().value().getMainYaml());
+        if (ArtifactTypeEnum.TOSCA_CSAR.getType().equals(artifactType)) {
+            return csarUtils
+                .createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest)
+                .right().map(error -> {
+                    log.debug("Failed to generate tosca csar for component {} error {}", parent.getUniqueId(), error);
+                    return new ByResponseFormatComponentException(error);
+                });
+        } else {
+            return toscaExportUtils
+                .exportComponent(parent)
+                .left().map(toscaRepresentation -> {
+                    log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
+                    return toscaRepresentation.getMainYaml();
+                }).right().map(toscaError -> {
+                    log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), toscaError);
+                    return new ByActionStatusComponentException(componentsUtils.convertFromToscaError(toscaError));
+                });
         }
-        return artifactInfo;
     }
 
     private Either<ArtifactDefinition, Operation> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
@@ -473,7 +488,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                 decodedPayload = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user,
                         componentType, parent, origMd5, originData, interfaceName, operationName);
             }
-            result = updateArtifactFlow(parent, componentId, artifactId, artifactInfo, decodedPayload, componentType, auditingAction, interfaceName, operationName);
+            result = updateArtifactFlow(parent, componentId, artifactId, artifactInfo, decodedPayload, componentType, auditingAction
+            );
             if (needUpdateGroup && result.isLeft()) {
                 ArtifactDefinition updatedArtifact = result.left().value();
                 updateGroupForHeat(artifactInfo, updatedArtifact, parent);
@@ -646,20 +662,28 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return ActionStatus.OK;
     }
 
-    ArtifactDefinition generateNotSavedArtifact(Component parent, ArtifactDefinition artifactInfo) {
-        if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
-            return generateToscaArtifact(parent, artifactInfo, false, false);
+    ArtifactDefinition generateNotSavedArtifact(Component parent, ArtifactDefinition artifactDefinition) {
+        if (artifactDefinition.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
+            Either<byte[], ComponentException> decodedPayload = decodeToscaArtifactPayload(parent, false,
+                false, artifactDefinition.getArtifactType());
+            // TODO: This should not be done, but in order to keep this refactoring relatively small, we stop here
+            if(decodedPayload.isRight())
+                throw decodedPayload.right().value();
+            else {
+                artifactDefinition.setPayload(decodedPayload.left().value());
+                return artifactDefinition;
+            }
         }
         else {
-            String heatArtifactId = artifactInfo.getGeneratedFromId();
+            String heatArtifactId = artifactDefinition.getGeneratedFromId();
             Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
             if (heatRes.isRight()) {
-                log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo.getUniqueId());
+                log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactDefinition.getUniqueId());
                 throw new StorageException(heatRes.right().value());
             }
             String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
-            artifactInfo.setPayloadData(generatedPayload);
-            return artifactInfo;
+            artifactDefinition.setPayloadData(generatedPayload);
+            return artifactDefinition;
         }
     }
 
@@ -832,10 +856,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         switch (componentType) {
             case RESOURCE:
             case SERVICE:
-                found = checkArtifactInComponent(component, artifactId);
+                found = ComponentUtils.checkArtifactInComponent(component, artifactId);
                 break;
             case RESOURCE_INSTANCE:
-                found = checkArtifactInResourceInstance(component, componentId, artifactId);
+                found = ComponentUtils.checkArtifactInResourceInstance(component, componentId, artifactId);
                 break;
             default:
                 found = false;
@@ -871,23 +895,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return artifactDefinitionEither.left().value();
     }
 
-    private Either<ArtifactDefinition, Operation> lockComponentAndUpdateArtifact(
-            String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId,
-            User user, ComponentTypeEnum componentType, Component parent, byte[] decodedPayload, String interfaceType,
-            String operationName, boolean shouldLock, boolean inTransaction) {
+    private <T> Either<ArtifactDefinition, T> lockComponentAndUpdateArtifact(
+        String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId,
+        User user, ComponentTypeEnum componentType, Component parent, byte[] decodedPayload,
+        boolean shouldLock, boolean inTransaction) {
 
-        Either<ArtifactDefinition, Operation> resultOp = null;
         boolean failed = false;
         boolean writeAudit = true;
         try {
             lockComponent(parent, shouldLock, ARTIFACT_ACTION_LOCK);
             writeAudit = false;
-            resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, decodedPayload, componentType, auditingAction, interfaceType, operationName);
-            return resultOp;
+            return updateArtifactFlow(parent, parentId, artifactId, artifactInfo, decodedPayload, componentType,
+                auditingAction);
         }
         catch (ComponentException ce) {
             if(writeAudit) {
-                handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, ce.getResponseFormat(), componentType, null);
+                handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, ce.getResponseFormat(),
+                    componentType, null);
             }
             failed = true;
             throw ce;
@@ -1118,7 +1142,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         if (isDeploymentArtifact(artifactInfo)) {
             if (componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
                 final String artifactName = artifactInfo.getArtifactName();
-                if (operation.isCreateOrLink() || !artifactName.equalsIgnoreCase(existingArtifactInfo.getArtifactName())) {
+                final String existingArtifactName =
+                    (existingArtifactInfo == null) ? null : existingArtifactInfo.getArtifactName();
+
+                if (operation.isCreateOrLink()
+                    || ((artifactName != null) && !artifactName.equalsIgnoreCase(existingArtifactName))) {
                     validateSingleDeploymentArtifactName(artifactName, parentComponent);
                 }
             }
@@ -1247,60 +1275,76 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     }
 
     // This method is here for backward compatibility - when other parts of the code are cleaned can change to use the internal version
-    public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent,
-                                                                                      boolean shouldLock, boolean inTransaction) {
+    public Either<ArtifactDefinition, ResponseFormat> handleDelete(
+        String parentId, String artifactId, User user, Component parent,
+        boolean shouldLock, boolean inTransaction) {
+
         ResponseFormat responseFormat;
         boolean operationSucceeded = false;
         if (shouldLock) {
-            lockComponent(componentType, artifactId, auditingAction, user, parent);
+            lockComponent(ComponentTypeEnum.RESOURCE, artifactId, AuditingActionEnum.ARTIFACT_DELETE, user, parent);
         }
         try {
-            ArtifactDefinition artifactDefinition = handleDeleteInternal(parentId, artifactId, componentType, parent);
+            ArtifactDefinition artifactDefinition = handleDeleteInternal(parentId, artifactId,
+                ComponentTypeEnum.RESOURCE, parent);
             operationSucceeded = true;
-            return Either.left(Either.left(artifactDefinition));
+            return Either.left(artifactDefinition);
         }
         catch (ComponentException ce) {
             responseFormat = componentsUtils.getResponseFormat(ce);
-            handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+            handleAuditing(AuditingActionEnum.ARTIFACT_DELETE, parent, parentId, user, null, null,
+                artifactId, responseFormat, ComponentTypeEnum.RESOURCE, null);
             return Either.right(responseFormat);
         }
         catch (StorageException se) {
             responseFormat = componentsUtils.getResponseFormat(se);
-            handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+            handleAuditing(AuditingActionEnum.ARTIFACT_DELETE, parent, parentId, user, null, null,
+                artifactId, responseFormat, ComponentTypeEnum.RESOURCE, null);
             return Either.right(responseFormat);
         } finally {
             handleLockingAndCommit(parent, shouldLock, inTransaction, operationSucceeded);
         }
     }
 
-    private ArtifactDefinition handleDeleteInternal(String parentId, String artifactId, ComponentTypeEnum componentType, Component parent) {
+    private ArtifactDefinition handleDeleteInternal(
+        String parentId, String artifactId,
+        ComponentTypeEnum componentType, Component parent
+    ) {
         NodeTypeEnum parentType = convertParentType(componentType);
         log.debug("Going to find the artifact {} on the component {}", artifactId, parent.getUniqueId());
-        Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = findArtifact(artifactId, parent, parentId, componentType);
+
+        Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes =
+            findArtifact(artifactId, parent, parentId, componentType);
         if (getArtifactRes.isRight()) {
-            log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, parent.getUniqueId());
+            log.debug("Failed to find the artifact {} belonging to {} on the component {}",
+                artifactId, parentId, parent.getUniqueId());
             throw new ByActionStatusComponentException(getArtifactRes.right().value(), artifactId);
         }
         ArtifactDefinition foundArtifact = getArtifactRes.left().value().getLeft();
         ComponentInstance foundInstance = getArtifactRes.left().value().getRight();
+
         String esId = foundArtifact.getEsId();
+        Either<Boolean, StorageOperationStatus> needClone = ifTrue(StringUtils.isNotEmpty(esId), () -> forEach(
+            artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, parentType),
+            b -> log.debug("handleDelete: clone is needed for deleting {} held by {} in component {} {}? {}",
+                foundArtifact.getArtifactName(), parentType, parent.getUniqueId(), parent.getName(), b)
+        ));
+
         boolean needToClone = false;
-        if (StringUtils.isNotEmpty(esId)) {
-            Either<Boolean, StorageOperationStatus> needCloneRes = null;
-            needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, parentType);
-            if (needCloneRes.isRight()) {
-                throw new StorageException(needCloneRes.right().value(), foundArtifact.getArtifactDisplayName());
-            } else if (log.isDebugEnabled()) {
-                needToClone = needCloneRes.left().value();
-                log.debug("handleDelete: clone is needed for deleting {} held by {} in component {} ? {}",
-                        foundArtifact.getArtifactName(), parentType, parent.getUniqueId(), parent.getName(), needCloneRes.left().value());
-            }
+        // TODO: This should not be done, but in order to keep this refactoring small, we stop here.
+        // Remove this block once the above refactoring is merged.
+        if(needClone.isLeft()) {
+            needToClone = needClone.left().value();
+        } else {
+            throw new StorageException(needClone.right().value(), foundArtifact.getArtifactDisplayName());
         }
-        boolean isNeedToDeleteArtifactFromDB = true;
+
+        boolean isNeedToDeleteArtifactFromDB =
+            componentType == ComponentTypeEnum.RESOURCE_INSTANCE &&
+                isArtifactOnlyResourceInstanceArtifact(foundArtifact, parent, parentId);
+
         boolean isDuplicated = false;
-        if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
-            isNeedToDeleteArtifactFromDB = isArtifactOnlyResourceInstanceArtifact(foundArtifact, parent, parentId);
-        }
+
         ArtifactDataDefinition updatedArtifact = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needToClone);
         isDuplicated = updatedArtifact.getDuplicated();
 
@@ -1339,6 +1383,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return foundArtifact;
     }
 
+    public static <R> Either<Boolean, R> ifTrue(boolean predicate, Supplier<Either<Boolean, R>> ifTrue) {
+        return predicate ? ifTrue.get() : Either.left(false);
+    }
+
+    public static <L, R> Either<L, R> forEach(Either<L, R> e, Consumer<L> c) {
+        return e.left().map(l -> {
+            c.accept(l);
+            return l;
+        });
+    }
+
     private boolean isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) {
         Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstanceById(instanceId);
         if (!componentInstanceOpt.isPresent()) {
@@ -1398,27 +1453,25 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return updatedGroups;
     }
 
-    private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
-        List<GroupInstance> updatedGroupInstances = new ArrayList<>();
-        if (CollectionUtils.isNotEmpty(groupInstances)) {
-            boolean isUpdated = false;
-            for (GroupInstance groupInstance : groupInstances) {
-                isUpdated = false;
-                if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactId)) {
-                    groupInstance.getGroupInstanceArtifacts().remove(artifactId);
-                    isUpdated = true;
-                }
-                if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
-                        .contains(foundArtifact.getArtifactUUID())) {
-                    groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
-                    isUpdated = true;
-                }
-                if (isUpdated) {
-                    updatedGroupInstances.add(groupInstance);
-                }
-            }
+    private List<GroupInstance> getUpdatedGroupInstances(
+        String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances
+    ) {
+        if (CollectionUtils.isEmpty(groupInstances)) {
+            return new ArrayList<>();
         }
-        return updatedGroupInstances;
+        // TODO: A defensive copy should be created here for groupInstances. Modifying
+        // arguments (aka output arguments) is overall a bad practice as explained in
+        // Clean Code by Robert Martin.
+        // A better approach would be to use Lenses.
+
+        return groupInstances.stream().filter(gi -> {
+            boolean groupInstanceArtifactRemoved = gi.getGroupInstanceArtifacts() != null &&
+                gi.getGroupInstanceArtifacts().remove(artifactId);
+            boolean groupInstanceArtifactUUIDRemoved = gi.getGroupInstanceArtifactsUuid() != null &&
+                gi.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
+
+            return groupInstanceArtifactRemoved || groupInstanceArtifactUUIDRemoved;
+        }).collect(Collectors.toList());
     }
 
     private ArtifactDataDefinition deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
@@ -2017,7 +2070,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     private boolean isValidXml(byte[] xmlToParse) {
         boolean isXmlValid = true;
         try {
-            XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
+            SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
+            saxParser.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
+            saxParser.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
+            XMLReader reader = saxParser.getXMLReader();
             setFeatures(reader);
             reader.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
         }
@@ -2459,32 +2515,24 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return Either.left(true);
     }
 
-    private Either<ArtifactDefinition, Operation> updateArtifactFlow(Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, byte[] decodedPayload,
-                                                                     ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationName) {
+    private <T> Either<ArtifactDefinition, T> updateArtifactFlow(Component parent, String parentId, String artifactId,
+        ArtifactDefinition artifactInfo, byte[] decodedPayload,
+        ComponentTypeEnum componentType, AuditingActionEnum auditingAction) {
         DAOArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
         if (artifactData == null) {
             BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
             log.debug("Failed to create artifact object for ES.");
             throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
         }
-        String prevArtifactId;
-        String currArtifactId = artifactId;
-        ArtifactDefinition artifactDefinition = artifactInfo;
-        if (interfaceType != null && operationName != null) {
-            BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
-            log.debug("Received both interface and operation for update artifact - something is wrong");
-            throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
-        }
         log.debug("Entry on graph is updated. Update artifact in ES");
         // Changing previous and current artifactId for auditing
-        prevArtifactId = currArtifactId;
-        currArtifactId = artifactDefinition.getUniqueId();
+        String currArtifactId = artifactInfo.getUniqueId();
 
         NodeTypeEnum parentType = convertParentType(componentType);
 
         if (decodedPayload == null) {
-            if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
-                Either<DAOArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition.getEsId());
+            if (!artifactInfo.getMandatory() || artifactInfo.getEsId() != null) {
+                Either<DAOArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactInfo.getEsId());
                 if (artifactFromCassandra.isRight()) {
                     throw new StorageException(artifactFromCassandra.right().value());
                 }
@@ -2492,9 +2540,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                 artifactData.setData(artifactFromCassandra.left().value().getData());
                 artifactData.setId(artifactFromCassandra.left().value().getId());
             }
-        } else if (artifactDefinition.getEsId() == null) {
-            artifactDefinition.setEsId(artifactDefinition.getUniqueId());
-            artifactData.setId(artifactDefinition.getUniqueId());
+        } else if (artifactInfo.getEsId() == null) {
+            artifactInfo.setEsId(artifactInfo.getUniqueId());
+            artifactData.setId(artifactInfo.getUniqueId());
         }
 
         Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArtifactOnResource(artifactInfo,
@@ -2502,7 +2550,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         if (result.isRight()) {
             throw new StorageException(result.right().value());
         }
-        artifactDefinition = result.left().value();
+        ArtifactDefinition artifactDefinition = result.left().value();
         updateGeneratedIdInHeatEnv(parent, parentId, artifactId, artifactInfo, artifactDefinition, parentType);
 
         StorageOperationStatus storageOperationStatus = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
@@ -2513,74 +2561,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) {
                 artifactData.setId(artifactDefinition.getEsId());
             }
-            saveArtifactInCassandra(artifactData, parent, artifactInfo, currArtifactId, prevArtifactId, auditingAction, componentType);
+            saveArtifactInCassandra(artifactData, parent, artifactInfo, currArtifactId, artifactId, auditingAction, componentType);
         }
         return Either.left(artifactDefinition);
     }
 
-    private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactsFlowForInterfaceOperations(
-            Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user,
-            byte[] decodedPayload, ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType,
-            String operationUuid, DAOArtifactData artifactData, String prevArtifactId, String currArtifactId,
-            ArtifactDefinition artifactDefinition) {
-        StorageOperationStatus error;
-        Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
-        if (decodedPayload == null) {
-            if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
-                Either<DAOArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
-                        .getEsId());
-                if (artifactFromCassandra.isRight()) {
-                    log.debug("Failed to get artifact data from ES for artifact id  {}", artifactId);
-                    error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
-                            .value());
-                    ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
-                    handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
-                    resultOp = Either.right(responseFormat);
-                    return resultOp;
-                }
-                // clone data to new artifact
-                artifactData.setData(artifactFromCassandra.left().value().getData());
-                artifactData.setId(artifactFromCassandra.left().value().getId());
-            } else {
-                // todo if not exist(first time)
-            }
-
-        } else {
-            if (artifactDefinition.getEsId() == null) {
-                artifactDefinition.setEsId(artifactDefinition.getUniqueId());
-                artifactData.setId(artifactDefinition.getUniqueId());
-            }
-        }
-        NodeTypeEnum convertParentType = convertParentType(componentType);
-        // Set additional fields for artifact
-        artifactInfo.setArtifactLabel(artifactInfo.getArtifactName());
-        artifactInfo.setArtifactDisplayName(artifactInfo.getArtifactName());
-
-        Either<ArtifactDefinition, StorageOperationStatus> updateArtifactOnResourceEither =
-                artifactToscaOperation.updateArtifactOnResource(artifactInfo, parent, artifactId, convertParentType, parentId, true);
-        if(updateArtifactOnResourceEither.isRight()){
-            log.debug("Failed to persist operation artifact {} in resource, error is {}",artifactInfo.getArtifactName(), updateArtifactOnResourceEither.right().value());
-            ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(updateArtifactOnResourceEither.right().value());
-            return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
-        }
-        if (artifactData.getData() != null) {
-            CassandraOperationStatus cassandraOperationStatus = artifactCassandraDao.saveArtifact(artifactData);
-            if(cassandraOperationStatus != CassandraOperationStatus.OK){
-                log.debug("Failed to persist operation artifact {}, error is {}",artifactInfo.getArtifactName(),cassandraOperationStatus);
-                StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cassandraOperationStatus);
-                ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
-                return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
-            }
-        }
-
-        Either<ArtifactDefinition, ResponseFormat> updateOprEither = updateOperationArtifact(parentId, interfaceType, operationUuid, updateArtifactOnResourceEither.left().value());
-        if(updateOprEither.isRight()){
-            return Either.right(updateOprEither.right().value());
-        }
-
-        return Either.left(Either.left(updateOprEither.left().value()));
-    }
-
     private String updateGeneratedIdInHeatEnv(Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, ArtifactDefinition artifactDefinition, NodeTypeEnum parentType) {
         if (NodeTypeEnum.Resource == parentType) {
             return updateGeneratedIdInHeatEnv(parent.getDeploymentArtifacts(), parent, parentId, artifactId, artifactInfo, artifactDefinition, parentType, false);
@@ -2674,28 +2659,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return Either.left(decodedPayload);
     }
 
+    public Either<ArtifactDefinition, ResponseFormat> deleteArtifactByInterface(
+        String resourceId, String userUserId, String artifactId, boolean inTransaction) {
 
-    public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String userUserId, String artifactId,
-                                                                       boolean inTransaction) {
-        User user = new User();
-        user.setUserId(userUserId);
-        Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
-        if (parent.isRight()) {
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent
-                    .right()
-                    .value()));
-            return Either.right(responseFormat);
-        }
-        Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent
-                        .left()
-                        .value(),
-                false, inTransaction);
-        if (handleDelete.isRight()) {
-            return Either.right(handleDelete.right().value());
-        }
-        Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
-        return Either.left(result.right().value());
-
+        return toscaOperationFacade
+            .getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata)
+            .right().map(componentsUtils.toResponseFormat())
+            .left().bind(parentComponent -> {
+                User user = new User(userUserId);
+                return handleDelete(resourceId, artifactId, user,
+                    parentComponent,
+                    false, inTransaction);
+            });
     }
 
     private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
@@ -2933,108 +2908,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return downloadArtifact(artifactDefinition);
     }
 
-    private boolean checkArtifactInComponent(Component component, String artifactId) {
-        boolean found = false;
-        Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
-        if (artifactsS != null) {
-            for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
-                if (entry.getValue().getUniqueId().equals(artifactId)) {
-                    found = true;
-                    break;
-                }
-            }
-        }
-        Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
-        if (!found && deploymentArtifactsS != null) {
-            for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
-                if (entry.getValue().getUniqueId().equals(artifactId)) {
-                    found = true;
-                    break;
-                }
-            }
-        }
-        Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
-        if (!found && toscaArtifactsS != null) {
-            for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
-                if (entry.getValue().getUniqueId().equals(artifactId)) {
-                    found = true;
-                    break;
-                }
-            }
-        }
-
-        Map<String, InterfaceDefinition> interfaces = component.getInterfaces();
-        if (!found && interfaces != null) {
-            for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
-                Map<String, Operation> operations = entry.getValue().getOperationsMap();
-                for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
-                    if (entryOp.getValue().getImplementation() != null && entryOp.getValue()
-                            .getImplementation()
-                            .getUniqueId()
-                            .equals(artifactId)) {
-                        found = true;
-                        break;
-                    }
-                }
-            }
-        }
-        switch (component.getComponentType()) {
-            case RESOURCE:
-                break;
-            case SERVICE:
-                Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
-                if (!found && apiArtifacts != null) {
-                    for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
-                        if (entry.getValue().getUniqueId().equals(artifactId)) {
-                            found = true;
-                            break;
-                        }
-                    }
-                }
-                break;
-            default:
-
-        }
-
-        return found;
-    }
-
-    private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
-
-        boolean found = false;
-        List<ComponentInstance> resourceInstances = component.getComponentInstances();
-        ComponentInstance resourceInstance = null;
-        for (ComponentInstance ri : resourceInstances) {
-            if (ri.getUniqueId().equals(resourceInstanceId)) {
-                resourceInstance = ri;
-                break;
-            }
-        }
-        if (resourceInstance != null) {
-            Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
-            if (artifacts != null) {
-                for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
-                    if (entry.getValue().getUniqueId().equals(artifactId)) {
-                        found = true;
-                        break;
-                    }
-                }
-            }
-            if (!found) {
-                artifacts = resourceInstance.getArtifacts();
-                if (artifacts != null) {
-                    for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
-                        if (entry.getValue().getUniqueId().equals(artifactId)) {
-                            found = true;
-                            break;
-                        }
-                    }
-                }
-            }
-        }
-        return found;
-    }
-
     private Component validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
                                               String containerComponentType) {
 
@@ -3965,8 +3838,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     public byte[] downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid,
                                                           String resourceInstanceName, String artifactUUID) {
         ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName);
-        return downloadArtifact(resourceInstance == null ? null : resourceInstance.getDeploymentArtifacts(),
-                artifactUUID, resourceInstance.getName());
+
+        if (resourceInstance != null) {
+            return downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, resourceInstance.getName());
+        } else {
+            return downloadArtifact(null, artifactUUID, null);
+        }
     }
 
     /**
@@ -3989,13 +3866,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         String origMd5 = request.getHeader(Constants.MD5_HEADER);
         String userId = request.getHeader(Constants.USER_ID_HEADER);
 
-        Either<ComponentMetadataData, StorageOperationStatus> getComponentRes =
-                toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
-        if (getComponentRes.isRight()) {
-            StorageOperationStatus status = getComponentRes.right().value();
-            log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
-            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid);
-        }
+        Either<ComponentMetadataData, ActionStatus> getComponentRes =
+            fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
 
         ComponentMetadataDataDefinition componentMetadataDataDefinition = getComponentRes.left().value().getMetadataDataDefinition();
         componentId = componentMetadataDataDefinition.getUniqueId();
@@ -4038,12 +3910,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         String userId = request.getHeader(Constants.USER_ID_HEADER);
 
         ImmutablePair<Component, ComponentInstance> componentRiPair = null;
-        Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
-        if (getComponentRes.isRight()) {
-            StorageOperationStatus status = getComponentRes.right().value();
-            log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
-            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName);
-        }
+
+        Either<ComponentMetadataData, ActionStatus> getComponentRes =
+            fetchLatestComponentMetadataOrThrow(componentType, componentUuid, resourceInstanceName);
         if (!getComponentRes.left()
                 .value()
                 .getMetadataDataDefinition()
@@ -4093,12 +3962,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         String origMd5 = request.getHeader(Constants.MD5_HEADER);
         String userId = request.getHeader(Constants.USER_ID_HEADER);
 
-        Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
-        if (getComponentRes.isRight()) {
-            StorageOperationStatus status = getComponentRes.right().value();
-            log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
-            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status));
-        }
+        Either<ComponentMetadataData, ActionStatus> getComponentRes =
+            fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
         componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
         String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
 
@@ -4150,12 +4015,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         String userId = request.getHeader(Constants.USER_ID_HEADER);
 
         ImmutablePair<Component, ComponentInstance> componentRiPair = null;
-        Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
-        if (getComponentRes.isRight()) {
-            StorageOperationStatus status = getComponentRes.right().value();
-            log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
-            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status));
-        }
+        Either<ComponentMetadataData, ActionStatus> getComponentRes =
+            fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
         if (!getComponentRes.left()
                 .value()
                 .getMetadataDataDefinition()
@@ -4234,7 +4095,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return Either.left(artifactInfo);
     }
 
-
     /**
      * updates an artifact on a component by UUID
      *
@@ -4252,21 +4112,20 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
         Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
-        Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
-        ArtifactDefinition updateArtifact = null;
         String componentId = null;
+        ArtifactDefinition existingArtifactInfo = null;
+        String interfaceName = null;
+
         ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
         String origMd5 = request.getHeader(Constants.MD5_HEADER);
         String userId = request.getHeader(Constants.USER_ID_HEADER);
-        ArtifactDefinition existingArtifactInfo = null;
-        String interfaceName = null;
 
-        Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
-        if (getComponentRes.isRight()) {
-            StorageOperationStatus status = getComponentRes.right().value();
-            log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
-            errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
-        }
+        Either<ComponentMetadataData, ActionStatus> getComponentRes =
+            fetchLatestComponentMetadata(componentType, componentUuid)
+                .right().map(as -> {
+                errorWrapper.setInnerElement(componentsUtils.getResponseFormat(as));
+                return as;
+            });
 
         if (errorWrapper.isEmpty()) {
             componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
@@ -4321,24 +4180,55 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         }
 
         if (errorWrapper.isEmpty()) {
-                try {
-                    actionResult = Either.left(handleArtifactRequest(componentId, userId, componentType, operation,
-                            artifactUUID, artifactInfo, origMd5, data, interfaceName,
-                            operationUUID, null, null));
-                }catch (ComponentException e){
-                    errorWrapper.setInnerElement(e.getResponseFormat());
-            }
+            updateArtifactResult = handleArtifactRequestAndFlatten(componentId, userId, componentType, operation,
+                artifactUUID, artifactInfo, origMd5, data, interfaceName, operationUUID);
+        } else {
+            updateArtifactResult = Either.right(errorWrapper.getInnerElement());
         }
 
-        if (errorWrapper.isEmpty()) {
-            updateArtifact = actionResult.left().value().left().value();
-            updateArtifactResult = Either.left(updateArtifact);
+        return updateArtifactResult;
+    }
 
+    private Either<ArtifactDefinition, ResponseFormat> handleArtifactRequestAndFlatten(
+        String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation,
+        String artifactId, ArtifactDefinition artifactInfo, String origMd5, String originData, String interfaceName,
+        String operationName) {
+        try {
+            return handleArtifactRequest(componentId, userId, componentType, operation,
+                artifactId, artifactInfo, origMd5, originData, interfaceName,
+                operationName, null, null)
+                .right().map(op -> {
+                    log.debug("Unexpected value returned while calling handleArtifactRequest: {}", op);
+                    return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+                });
+        } catch (ComponentException e) {
+            return Either.right(e.getResponseFormat());
         }
-        else {
-            updateArtifactResult = Either.right(errorWrapper.getInnerElement());
-        }
-        return updateArtifactResult;
+    }
+
+    private Either<ComponentMetadataData, ActionStatus> fetchLatestComponentMetadataOrThrow(
+        ComponentTypeEnum componentType, String componentUuid
+    ) {
+        return fetchLatestComponentMetadataOrThrow(componentType, componentUuid, componentUuid);
+    }
+
+    private Either<ComponentMetadataData, ActionStatus> fetchLatestComponentMetadataOrThrow(
+        ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName
+    ) {
+        return fetchLatestComponentMetadata(componentType, componentUuid).right().map(as -> {
+            throw new ByActionStatusComponentException(as, resourceInstanceName);
+        });
+    }
+
+    private Either<ComponentMetadataData, ActionStatus> fetchLatestComponentMetadata(
+        ComponentTypeEnum componentType, String componentUuid
+    ) {
+        return toscaOperationFacade
+            .getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true)
+            .right().map(sos -> {
+                log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, sos);
+                return componentsUtils.convertFromStorageResponse(sos, componentType);
+            });
     }
 
     private Either<String, ResponseFormat> fetchInterfaceName(String componentId, String interfaceUUID) {
@@ -4379,12 +4269,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         String origMd5 = request.getHeader(Constants.MD5_HEADER);
         String userId = request.getHeader(Constants.USER_ID_HEADER);
 
-        Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
-        if (getComponentRes.isRight()) {
-            StorageOperationStatus status = getComponentRes.right().value();
-            log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
-            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid);
-        }
+        Either<ComponentMetadataData, ActionStatus> getComponentRes =
+            fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
         componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
         String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
         if (!getComponentRes.left()
@@ -4427,13 +4313,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         String origMd5 = request.getHeader(Constants.MD5_HEADER);
         String userId = request.getHeader(Constants.USER_ID_HEADER);
         ImmutablePair<Component, ComponentInstance> componentRiPair = null;
-        Either<ComponentMetadataData, StorageOperationStatus> getComponentRes =
-                toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
-        if (getComponentRes.isRight()) {
-            StorageOperationStatus status = getComponentRes.right().value();
-            log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
-            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status));
-        }
+        Either<ComponentMetadataData, ActionStatus> getComponentRes =
+            fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
         if (!getComponentRes.left()
                 .value()
                 .getMetadataDataDefinition()
@@ -4610,7 +4491,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return uploadedArtifacts;
     }
 
-    public Either<ArtifactDefinition, Operation> handleLoadedArtifact(Resource component, User user, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction,
+    public Either<ArtifactDefinition, Operation> handleLoadedArtifact(Component component, User user, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction,
                                                                       ComponentTypeEnum componentType, ArtifactDefinition artifactDefinition) {
         AuditingActionEnum auditingAction = detectAuditingType(operation, "");
         String componentId = component.getUniqueId();
@@ -4662,7 +4543,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         String origMd5;
         try {
             for (ArtifactDefinition artifact : artifactsToHandle) {
-                originData = buildJsonStringForCsarVfcArtifact(artifact);
+                originData = ArtifactUtils.buildJsonStringForCsarVfcArtifact(artifact);
                 origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData);
                 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact
                         .getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
@@ -4678,65 +4559,62 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return handleArtifactsResult;
     }
 
-    private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName) {
-        ComponentInstance componentInstance;
+    private ComponentInstance getRelatedComponentInstance(
+        ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName
+    ) {
         String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
-        Component component = getComponentByUuid(componentType, componentUuid);
-        componentInstance = (component == null) ? null : component.getComponentInstances()
-                .stream()
-                .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
-                        .equals(normalizedName))
-                .findFirst()
-                .orElse(null);
-        if (componentInstance == null) {
-            log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
-            throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName,
-                    RESOURCE_INSTANCE, component.getComponentType().getValue(), component.getName());
-        }
-        return componentInstance;
+        Option<Component> oComponent = Option.of(getComponentByUuid(componentType, componentUuid));
+        return oComponent
+            .toTry(componentNotFound(componentType, componentUuid))
+            .flatMap(component -> findFirstMatching(component,
+                ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)
+            ).toTry(componentInstanceNotFound(componentType, resourceInstanceName, component))
+        ).get();
+    }
+
+    private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(
+        Component component, String resourceInstanceName
+    ) {
+        String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
+        ComponentInstance componentInstance = findFirstMatching(component,
+            ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)
+        ).toTry(componentInstanceNotFound(component.getComponentType(), resourceInstanceName, component)).get();
+        return new ImmutablePair<>(component, componentInstance);
     }
 
-    private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName) {
+    private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(
+        ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName
+    ) {
+        Component component = getLatestComponentByUuid(componentType, componentUuid);
+        ComponentInstance componentInstance = findFirstMatching(component,
+            ci -> ci.getNormalizedName().equals(resourceInstanceName)
+        ).toTry(componentInstanceNotFound(component.getComponentType(), resourceInstanceName, component)).get();
+        return new ImmutablePair<>(component, componentInstance);
+    }
 
-        ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
-        String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
-        ComponentInstance componentInstance = component.getComponentInstances()
-                .stream()
-                .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
-                        .equals(normalizedName))
-                .findFirst()
-                .orElse(null);
-        if (componentInstance == null) {
-            log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
-            throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName,
-                    RESOURCE_INSTANCE, component.getComponentType().getValue(), component.getName());
-        }
-        else {
-            relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
-        }
-        return relatedComponentComponentInstancePair;
+    private Supplier<Throwable> componentNotFound(ComponentTypeEnum componentType, String componentUuid) {
+        return () -> {
+            log.debug(FAILED_FETCH_COMPONENT, componentType.getValue(), componentUuid);
+            return new ByActionStatusComponentException(ActionStatus.COMPONENT_NOT_FOUND, componentUuid);
+        };
     }
 
-    private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType,
-                                                                                             String componentUuid, String resourceInstanceName) {
-        ComponentInstance componentInstance;
-        ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair;
-        Component component = getLatestComponentByUuid(componentType, componentUuid);
-        componentInstance = component.getComponentInstances()
-                .stream()
-                .filter(ci -> ci.getNormalizedName().equals(resourceInstanceName))
-                .findFirst()
-                .orElse(null);
-        if (componentInstance == null) {
+    private Supplier<Throwable> componentInstanceNotFound(
+        ComponentTypeEnum componentType, String resourceInstanceName, Component component
+    ) {
+        return () -> {
             log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
-            throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
-                    resourceInstanceName, RESOURCE_INSTANCE, component
-                    .getComponentType().getValue(), component.getName());
-        }
-        else {
-            relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
-        }
-        return relatedComponentComponentInstancePair;
+            return new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
+                resourceInstanceName,
+                RESOURCE_INSTANCE, componentType.getValue(), component.getName());
+        };
+    }
+
+    private static Option<ComponentInstance> findFirstMatching(Component component, Predicate<ComponentInstance> filter) {
+        return Option.ofOptional(component.getComponentInstances()
+            .stream()
+            .filter(filter)
+            .findFirst());
     }
 
     private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, String componentName) {
@@ -4851,19 +4729,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return checkoutRes.left().value();
     }
 
-    private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
-        Map<String, Object> json = new HashMap<>();
-        String artifactName = artifact.getArtifactName();
-        json.put(Constants.ARTIFACT_NAME, artifactName);
-        json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
-        json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
-        json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
-        json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
-        json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
-        json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
-        return gson.toJson(json);
-    }
-
     @Autowired
     void setNodeTemplateOperation(NodeTemplateOperation nodeTemplateOperation) {
         this.nodeTemplateOperation = nodeTemplateOperation;
@@ -4872,6 +4737,4 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     public List<ArtifactConfiguration> getConfiguration() {
         return ConfigurationManager.getConfigurationManager().getConfiguration().getArtifacts();
     }
-
 }
-