diff options
Diffstat (limited to 'catalog-be/src/main/java/org/openecomp/sdc/be/components/impl')
62 files changed, 10342 insertions, 10394 deletions
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java index f0ccffa633..712cba74b7 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java @@ -32,12 +32,12 @@ import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.AdditionalInformationDefinition; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation; -import org.openecomp.sdc.be.model.operations.api.IAdditionalInformationOperation; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation; import org.openecomp.sdc.be.model.operations.api.IGroupOperation; import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.AdditionalInformationOperation; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; @@ -68,7 +68,7 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { private static final Logger log = Logger.getLogger(AdditionalInformationBusinessLogic.class.getName()); private static final String FAILED_TO_LOCK_COMPONENT_ERROR = "Failed to lock component {} error - {}"; - private final IAdditionalInformationOperation additionalInformationOperation; + private final AdditionalInformationOperation additionalInformationOperation; @Autowired public AdditionalInformationBusinessLogic(IElementOperation elementDao, @@ -77,7 +77,7 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - IAdditionalInformationOperation additionalInformationOperation, + AdditionalInformationOperation additionalInformationOperation, ArtifactsOperations artifactToscaOperation) { super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); @@ -102,7 +102,7 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { */ public Either<AdditionalInfoParameterInfo, ResponseFormat> createAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String userId) { - validateUserExists(userId, "create Additional Information", false); + validateUserExists(userId); Either<AdditionalInfoParameterInfo, ResponseFormat> result = null; ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId); @@ -113,7 +113,7 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { // lock component StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType); - if (!lockResult.equals(StorageOperationStatus.OK)) { + if (lockResult != StorageOperationStatus.OK) { BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId); log.info(FAILED_TO_LOCK_COMPONENT_ERROR, resourceId, lockResult); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -323,7 +323,7 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { */ public Either<AdditionalInfoParameterInfo, ResponseFormat> updateAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String userId) { - validateUserExists(userId, "create Additional Information", false); + validateUserExists(userId); Either<AdditionalInfoParameterInfo, ResponseFormat> result = null; ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId); @@ -333,7 +333,7 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { } // lock component StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType); - if (!lockResult.equals(StorageOperationStatus.OK)) { + if (lockResult != StorageOperationStatus.OK) { BeEcompErrorManager.getInstance().logBeFailedLockObjectError(UPDATE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId); log.info(FAILED_TO_LOCK_COMPONENT_ERROR, resourceId, lockResult); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -389,7 +389,7 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { */ public Either<AdditionalInfoParameterInfo, ResponseFormat> deleteAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String userId) { - validateUserExists(userId, "delete Additional Information", false); + validateUserExists(userId); Either<AdditionalInfoParameterInfo, ResponseFormat> result = null; ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId); @@ -398,7 +398,7 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { } // lock component StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType); - if (!lockResult.equals(StorageOperationStatus.OK)) { + if (lockResult != StorageOperationStatus.OK) { BeEcompErrorManager.getInstance().logBeFailedLockObjectError(DELETE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId); log.info(FAILED_TO_LOCK_COMPONENT_ERROR, resourceId, lockResult); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -450,7 +450,7 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { */ public Either<AdditionalInfoParameterInfo, ResponseFormat> getAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String userId) { - validateUserExists(userId, "get Additional Information", false); + validateUserExists(userId); Either<AdditionalInfoParameterInfo, ResponseFormat> result = null; try { @@ -485,7 +485,7 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { */ public Either<AdditionalInformationDefinition, ResponseFormat> getAllAdditionalInformation(NodeTypeEnum nodeType, String resourceId, String userId) { - validateUserExists(userId, "get All Additional Information", false); + validateUserExists(userId); Either<AdditionalInformationDefinition, ResponseFormat> result = null; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AnnotationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AnnotationBusinessLogic.java index 84a07fca78..b0af789f28 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AnnotationBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AnnotationBusinessLogic.java @@ -30,7 +30,11 @@ import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.operations.impl.AnnotationTypeOperations; import org.springframework.stereotype.Component; -import java.util.*; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import static org.apache.commons.collections.CollectionUtils.isNotEmpty; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogic.java index c836e91b9b..15e9a77b15 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogic.java @@ -23,12 +23,14 @@ package org.openecomp.sdc.be.components.impl; import com.google.common.annotations.VisibleForTesting; import fj.data.Either; +import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.components.validation.AccessValidations; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; +import org.openecomp.sdc.be.facade.operations.CatalogOperation; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentParametersView; @@ -40,10 +42,18 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.exception.ResponseFormat; -import java.util.*; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; import java.util.stream.Collectors; +import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.wrapWithTryCatch; + + @org.springframework.stereotype.Component public class ArchiveBusinessLogic { @@ -54,13 +64,16 @@ public class ArchiveBusinessLogic { private final ArchiveOperation archiveOperation; private final ToscaOperationFacade toscaOperationFacade; private final ComponentsUtils componentUtils; + private final CatalogOperation catalogOperations; - public ArchiveBusinessLogic(JanusGraphDao janusGraphDao, AccessValidations accessValidations, ArchiveOperation archiveOperation, ToscaOperationFacade tof, ComponentsUtils componentsUtils) { + public ArchiveBusinessLogic(JanusGraphDao janusGraphDao, AccessValidations accessValidations, ArchiveOperation archiveOperation, ToscaOperationFacade tof, ComponentsUtils componentsUtils, + CatalogOperation catalogOperations) { this.janusGraphDao = janusGraphDao; this.accessValidations = accessValidations; this.archiveOperation = archiveOperation; this.toscaOperationFacade = tof; this.componentUtils = componentsUtils; + this.catalogOperations = catalogOperations; } public void archiveComponent(String containerComponentType, String userId, String componentId) { @@ -71,6 +84,8 @@ public class ArchiveBusinessLogic { throw new ByActionStatusComponentException(result.right().value(), componentId); } this.auditAction(ArchiveOperation.Action.ARCHIVE, result.left().value(), user, containerComponentType); + // Send Archive Notification To Facade + wrapWithTryCatch(() -> sendNotificationToFacade(componentId, ChangeTypeEnum.ARCHIVE)); } public void restoreComponent(String containerComponentType, String userId, String componentId) { @@ -80,6 +95,8 @@ public class ArchiveBusinessLogic { throw new ByActionStatusComponentException(result.right().value(), componentId); } this.auditAction(ArchiveOperation.Action.RESTORE, result.left().value(), user, containerComponentType); + // Send Archive Notification To Facade + wrapWithTryCatch(() -> sendNotificationToFacade(componentId, ChangeTypeEnum.RESTORE)); } public List<String> onVspArchive(String userId, List<String> csarUuids){ @@ -100,7 +117,7 @@ public class ArchiveBusinessLogic { for (String csarUuid : csarUuids) { try { - if (action.equals(ArchiveOperation.Action.ARCHIVE)) { + if (action == ArchiveOperation.Action.ARCHIVE) { actionStatus = this.archiveOperation.onVspArchived(csarUuid); } else { actionStatus = this.archiveOperation.onVspRestored(csarUuid); @@ -128,8 +145,6 @@ public class ArchiveBusinessLogic { public Map<String, List<CatalogComponent>> getArchiveComponents(String userId, List<OriginTypeEnum> excludeTypes) { try { - accessValidations.validateUserExist(userId, "GET ARCHIVED COMPONENTS"); - Either<List<CatalogComponent>, StorageOperationStatus> components = toscaOperationFacade.getCatalogOrArchiveComponents(false, excludeTypes); if (components.isLeft()) { List<CatalogComponent> comps = components.left().value(); @@ -174,4 +189,16 @@ public class ArchiveBusinessLogic { } } } + protected Either<Component, ResponseFormat> sendNotificationToFacade(String componentId, + ChangeTypeEnum changeStatus) { + log.debug("build {} notification for facade start", changeStatus.name()); + Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaElement(componentId); + Component component = toscaElement.left() + .value(); + ActionStatus status = catalogOperations.updateCatalog(changeStatus, component); + if (status != ActionStatus.OK) { + return Either.right(componentUtils.getResponseFormat(status)); + } + return Either.left(component); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java index d0a1273210..66dce60641 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java @@ -23,9 +23,19 @@ package org.openecomp.sdc.be.components.impl; import org.apache.commons.collections.MapUtils; import org.openecomp.sdc.be.components.ArtifactsResolver; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.InterfaceDefinition; +import org.openecomp.sdc.be.model.Service; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import java.util.stream.Collectors; @org.springframework.stereotype.Component("artifact-resolver") @@ -64,7 +74,7 @@ public class ArtifactResolverImpl implements ArtifactsResolver { } Map<String, ArtifactDefinition> serviceApiArtifacts = Collections.emptyMap(); - if (componentType.equals(ComponentTypeEnum.SERVICE)) { + if (componentType == ComponentTypeEnum.SERVICE) { serviceApiArtifacts = Optional.ofNullable(((Service) component).getServiceApiArtifacts()).orElse(Collections.emptyMap()); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java index 9eae363afb..103edd6497 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java @@ -22,21 +22,23 @@ package org.openecomp.sdc.be.components.impl; +import com.google.common.annotations.VisibleForTesting; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import fj.data.Either; import org.apache.commons.codec.binary.Base64; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; -import org.elasticsearch.common.Strings; import org.openecomp.sdc.be.components.ArtifactsResolver; import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; import org.openecomp.sdc.be.components.impl.artifact.ArtifactTypeToPayloadTypeSelector; 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.lifecycle.LifecycleBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum; @@ -48,11 +50,12 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition; import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ToscaArtifactDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; @@ -76,19 +79,20 @@ import org.openecomp.sdc.be.model.heat.HeatParameterType; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation; +import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation; import org.openecomp.sdc.be.model.operations.api.IGroupOperation; import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation; import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation; import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation; -import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.model.operations.impl.UserAdminOperation; import org.openecomp.sdc.be.resources.data.ComponentMetadataData; -import org.openecomp.sdc.be.resources.data.ESArtifactData; +import org.openecomp.sdc.be.resources.data.DAOArtifactData; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo; import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo; @@ -97,7 +101,6 @@ 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.IUserBusinessLogic; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.be.utils.TypeUtils; @@ -136,10 +139,13 @@ import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collectors; +import static org.openecomp.sdc.be.dao.api.ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE; + @org.springframework.stereotype.Component("artifactBusinessLogic") public class ArtifactsBusinessLogic extends BaseBusinessLogic { private static final String RESOURCE_INSTANCE = "resource instance"; @@ -159,13 +165,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { public static final String HEAT_ENV_SUFFIX = "env"; private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension"; - private static final Logger log = Logger.getLogger(ArtifactsBusinessLogic.class); + private static final Logger log = Logger.getLogger(ArtifactsBusinessLogic.class.getName()); private static final String FAILED_UPDATE_GROUPS = "Failed to update groups of the component {}. "; private static final String FAILED_UPDATE_ARTIFACT = "Failed to delete or update the artifact {}. Parent uniqueId is {}"; private static final String FAILED_SAVE_ARTIFACT = "Failed to save the artifact."; + public static final String ARTIFACT_ACTION_LOCK = "Artifact action - lock "; private static final String UPDATE_ARTIFACT_LOCK = "Update Artifact - lock "; private static final String FAILED_DOWNLOAD_ARTIFACT = "Download artifact {} failed"; - private static final String FAILED_UPLOAD_ARTIFACT_TO_COMPONENT = "Failed to upload artifact to component with type {} and uuid {}. Status is {}. "; + public static final String FAILED_UPLOAD_ARTIFACT_TO_COMPONENT = "Failed to upload artifact to component with type {} and uuid {}. Status is {}. "; private static final String FAILED_UPLOAD_ARTIFACT_TO_INSTANCE = "Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. "; private static final String FAILED_FETCH_COMPONENT = "Could not fetch component with type {} and uuid {}. Status is {}. "; private static final String NULL_PARAMETER = "One of the function parameteres is null"; @@ -180,31 +187,28 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { @javax.annotation.Resource private IInterfaceLifecycleOperation interfaceLifecycleOperation; @javax.annotation.Resource - private IUserAdminOperation userOperaton; + private UserAdminOperation userOperaton; @javax.annotation.Resource private IElementOperation elementOperation; @javax.annotation.Resource - private UserBusinessLogic userAdminManager; - - @javax.annotation.Resource private IHeatParametersOperation heatParametersOperation; - private final ArtifactCassandraDao artifactCassandraDao; - private final ToscaExportHandler toscaExportUtils; - private final CsarUtils csarUtils; - private final LifecycleBusinessLogic lifecycleBusinessLogic; - private final IUserBusinessLogic userBusinessLogic; - private final ArtifactsResolver artifactsResolver; + private ArtifactCassandraDao artifactCassandraDao; + private ToscaExportHandler toscaExportUtils; + private CsarUtils csarUtils; + private LifecycleBusinessLogic lifecycleBusinessLogic; + private UserBusinessLogic userBusinessLogic; + private ArtifactsResolver artifactsResolver; private NodeTemplateOperation nodeTemplateOperation; @Autowired public ArtifactsBusinessLogic(ArtifactCassandraDao artifactCassandraDao, ToscaExportHandler toscaExportUtils, - CsarUtils csarUtils, LifecycleBusinessLogic lifecycleBusinessLogic, IUserBusinessLogic userBusinessLogic, - ArtifactsResolver artifactsResolver, IElementOperation elementDao, IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) { + CsarUtils csarUtils, LifecycleBusinessLogic lifecycleBusinessLogic, UserBusinessLogic userBusinessLogic, + ArtifactsResolver artifactsResolver, IElementOperation elementDao, IGroupOperation groupOperation, + IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation, + InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) { super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); this.artifactCassandraDao = artifactCassandraDao; @@ -250,13 +254,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } // new flow US556184 - public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, - String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType) { - return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, parentId, containerComponentType, true, false); - } - - public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, - String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) { + public Either<ArtifactDefinition, Operation> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, + ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, + String origMd5, String originData, String interfaceName, String operationName, + String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) { // step 1 - detect auditing type AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5); @@ -265,40 +266,33 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId); handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); + throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION); } // step 3 - check user existence - Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction); - if (userResult.isRight()) { - return Either.right(userResult.right().value()); - } - // step 4 - check user's role - User user = userResult.left().value(); - Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation); - if (validateUserRole.isRight()) { - return Either.right(validateUserRole.right().value()); - } + User user = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction); + validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation); // steps 5 - 6 - 7 // 5. check service/resource existence // 6. check service/resource check out // 7. user is owner of checkout state - org.openecomp.sdc.be.model.Component component = null; + Component component = null; String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId; - Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, auditingAction, user, artifactId, componentType, containerComponentType); - if (validateComponent.isRight()) { - return Either.right(validateComponent.right().value()); - } - component = validateComponent.left().value(); - Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation); - if (validateWorkOnResource.isRight()) { - return Either.right(validateWorkOnResource.right().value()); + component = validateComponentExists(realComponentId, auditingAction, user, artifactId, componentType, containerComponentType); + validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation); + if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { + validateResourceInstanceById(component, componentId); } // step 8 - return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, user, component, - shouldLock, inTransaction, true); + return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, + originData, interfaceName, operationName, user, component, shouldLock, inTransaction, true); + } + + public Either<ArtifactDefinition, Operation> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, + String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType) { + return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, containerComponentType, true, false); } /** @@ -308,78 +302,75 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * * @return */ - public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId, - ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceUuid, String operationName, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) { - Component parent = component; - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - + public Either<ArtifactDefinition, Operation> validateAndHandleArtifact( + String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId, + ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceName, + String operationName, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) { AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5); - artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, auditingAction, user, component, parent, errorWrapper, shouldLock, inTransaction); - - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result; - if (errorWrapper.isEmpty()) { - // step 10 - result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceUuid, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup); - } - else { - result = Either.right(errorWrapper.getInnerElement()); - } + artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, + artifactUniqueId, artifactDefinition, auditingAction, user, + component, shouldLock, inTransaction); + + // step 10 + Either<ArtifactDefinition, Operation> result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, + origMd5, originData, interfaceName, operationName, auditingAction, user, component, shouldLock, inTransaction, needUpdateGroup); + //TODO: audit positive action return result; } - private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, - Component component, Component parent, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) { - ArtifactDefinition validatedArtifactInfo = artifactInfo; - if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE || operation - .getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) { - Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component); - if (validateArtifact.isRight()) { - ResponseFormat responseFormat = validateArtifact.right().value(); - handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); - errorWrapper.setInnerElement(validateArtifact.right().value()); - } - else if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) { - validatedArtifactInfo = validateArtifact.left().value(); - handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, errorWrapper, shouldLock, inTransaction); + @VisibleForTesting + ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, + Component component, boolean shouldLock, boolean inTransaction) { + ArtifactDefinition artifactInfoToReturn = artifactInfo; + ArtifactOperationEnum operationEnum = operation.getArtifactOperationEnum(); + if (operationEnum == ArtifactOperationEnum.UPDATE || operationEnum == ArtifactOperationEnum.DELETE || operationEnum == ArtifactOperationEnum.DOWNLOAD) { + ArtifactDefinition dbArtifact = getArtifactIfBelongsToComponent(componentId, componentType, artifactId, component); + if (operationEnum == ArtifactOperationEnum.DOWNLOAD) { + artifactInfoToReturn = dbArtifact; + handleHeatEnvDownload(componentId, componentType, user, component, dbArtifact, shouldLock, inTransaction); } } - return validatedArtifactInfo; + return artifactInfoToReturn; } - private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition, - ResponseFormat> validateArtifact, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) { - ArtifactDefinition validatedArtifact = validateArtifact.left().value(); + @VisibleForTesting + void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, Component component, + ArtifactDefinition artifactDefinition, boolean shouldLock, boolean inTransaction) { - if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) + if (artifactDefinition.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) && ComponentTypeEnum.SERVICE == component.getComponentType()) { ComponentInstance componentInstance = component.getComponentInstances() - .stream() - .filter(p -> p.getUniqueId().equals(componentId)) - .findAny() - .get(); + .stream() + .filter(p -> p.getUniqueId().equals(componentId)) + .findAny() + .orElse(null); + if (componentInstance == null) { + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentId, + "instance", "Service", component.getName()); + } Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts(); ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values() - .stream() - .filter(p -> p.getUniqueId() - .equals(validatedArtifact.getUniqueId())) - .findAny() - .get(); - Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance - .getName(), user, componentId, shouldLock, inTransaction); + .stream() + .filter(p -> p.getUniqueId() + .equals(artifactDefinition.getUniqueId())) + .findAny() + .orElse(null); + Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, + componentType, component, componentInstance.getName(), user, componentId, shouldLock, inTransaction); if (eitherGenerated.isRight()) { - errorWrapper.setInnerElement(eitherGenerated.right().value()); + throw new ByResponseFormatComponentException((eitherGenerated.right().value())); } } } - private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) { + private boolean artifactGenerationRequired(Component component, ArtifactDefinition artifactInfo) { boolean needGenerate; needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component .getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType() - .equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV - .getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo))); + .equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV + .getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo))); return needGenerate; } @@ -389,139 +380,183 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { .equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum()); } - public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact( - ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, + public Either<ArtifactDefinition, Operation> generateAndSaveToscaArtifact( + ArtifactDefinition artifactDefinition, Component component, User user, boolean isInCertificationRequest, boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) { - - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB); - if (generated.isRight()) { - return generated; - } + 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); - + return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition.getUniqueId(), + user, component.getComponentType(), component, decodedPayload, null, null, shouldLock, inTransaction); } - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) { + private ArtifactDefinition generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) { log.debug("tosca artifact generation"); - if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) { + if (ArtifactTypeEnum.TOSCA_CSAR.getType().equals(artifactInfo.getArtifactType())) { Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest); - if (generated.isRight()) { - log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right() - .value()); - - return Either.right(generated.right().value()); + ResponseFormat error = generated.right().value(); + log.debug("Failed to generate tosca csar for component {} error {}", parent.getUniqueId(), error); + throw new ByResponseFormatComponentException(error); } - byte[] value = generated.left().value(); - artifactInfo.setPayload(value); + artifactInfo.setPayload(generated.left().value()); } else { Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent); if (exportComponent.isRight()) { - log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right() - .value()); - ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(status); - return Either.right(responseFormat); + 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()); - String payload = exportComponent.left().value().getMainYaml(); - artifactInfo.setPayloadData(payload); + artifactInfo.setPayloadData(exportComponent.left().value().getMainYaml()); } - return Either.left(Either.left(artifactInfo)); + return artifactInfo; } - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5, - String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) { - switch (operation.getArtifactOperationEnum()) { - case DOWNLOAD: - if (artifactGenerationRequired(parent, artifactInfo)) { - return generateNotSavedArtifact(parent, artifactInfo); - } - return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent); - case DELETE: - return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction); - case UPDATE: - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null; - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); - if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE) - && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) { - result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction); - if (needUpdateGroup && result.isLeft()) { - Either<ArtifactDefinition, Operation> updateResult = result.left().value(); - ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left() - .value(), parent, componentType, componentId); - if (error != ActionStatus.OK) { - result = Either.right(componentsUtils.getResponseFormat(error)); - } - } - } - else { - if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) { - result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup); - } - } - if (result == null) { - result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction); - if (needUpdateGroup && result.isLeft()) { - Either<ArtifactDefinition, Operation> updateResult = result.left().value(); - - ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left() - .value(), parent, componentType); - if (error != ActionStatus.OK) { - result = Either.right(componentsUtils.getResponseFormat(error)); - } + private Either<ArtifactDefinition, Operation> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5, + String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) { + if (interfaceName != null && operationName != null) { + interfaceName = interfaceName.toLowerCase(); + operationName = operationName.toLowerCase(); + } + if (shouldLock) { + lockComponent(componentType, artifactId, auditingAction, user, parent); + } + Either<ArtifactDefinition, Operation> result; + boolean operationSucceeded = false; + try { + switch (operation.getArtifactOperationEnum()) { + case DOWNLOAD: + if (artifactGenerationRequired(parent, artifactInfo)) { + result = Either.left(generateNotSavedArtifact(parent, artifactInfo)); + } else { + result = Either.left(handleDownload(componentId, artifactId, componentType, parent)); } + break; + case DELETE: + result = Either.left(handleDeleteInternal(componentId, artifactId, componentType, parent)); + break; + case UPDATE: + result = handleUpdate(componentId, componentType, operation, artifactId, artifactInfo, null, origMd5, originData, interfaceName, operationName, + auditingAction, user, parent, needUpdateGroup); + break; + case CREATE: + result = handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, + operationName); + break; + case LINK: + result = Either.left(handleLink(componentId, artifactInfo, componentType, parent)); + break; + default: + throw new UnsupportedOperationException("In ArtifactsBusinessLogic received illegal operation: " + operation.getArtifactOperationEnum()); + } + operationSucceeded = true; + return result; + } + finally { + handleLockingAndCommit(parent, shouldLock, inTransaction, operationSucceeded); + } + } + + private void lockComponent(ComponentTypeEnum componentType, String artifactId, AuditingActionEnum auditingAction, User user, Component parent) { + try { + lockComponent(parent, ARTIFACT_ACTION_LOCK); + }catch (ComponentException e){ + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, null, null, artifactId, e.getResponseFormat(), + componentType, null); + throw e; + } + } + + @VisibleForTesting + public Either<ArtifactDefinition, Operation> handleUpdate(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, + ArtifactDefinition artifactInfo, byte[] decodedPayload, String origMd5, String originData, String interfaceName, + String operationName, AuditingActionEnum auditingAction, User user, Component parent, + boolean needUpdateGroup) { + Either<ArtifactDefinition, Operation> result; + ArtifactTypeEnum artifactType = validateAndReturnArtifactType(artifactInfo); + if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE + && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) { + result = handleUpdateHeatEnvAndHeatMeta(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation); + if (needUpdateGroup) { + ActionStatus error = updateGroupInstance(artifactInfo, result.left().value(), parent, componentId); + if (error != ActionStatus.OK) { + throw new ByActionStatusComponentException(error); } - return result; - case CREATE: - return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction); - case LINK: - return handleLink(componentId, artifactInfo, auditingAction, user, componentType, parent, shouldLock, inTransaction); + } + } + else if (componentType == ComponentTypeEnum.RESOURCE && artifactType == ArtifactTypeEnum.HEAT_ENV) { + result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, componentType, parent, originData, origMd5, operation, needUpdateGroup); + } + else { + if (decodedPayload == null) { + 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); + if (needUpdateGroup && result.isLeft()) { + ArtifactDefinition updatedArtifact = result.left().value(); + updateGroupForHeat(artifactInfo, updatedArtifact, parent); + } + } + return result; + } + + private ArtifactTypeEnum validateAndReturnArtifactType(ArtifactDefinition artifactInfo) { + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); + if (artifactType == null) { + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()); } - return null; + return artifactType; + } + + public ActionStatus updateGroupForHeatEnv(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent) { + return ActionStatus.OK; } - private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) { + @VisibleForTesting + public ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent) { List<GroupDefinition> groups = parent.getGroups(); if (groups != null && !groups.isEmpty()) { List<GroupDataDefinition> groupToUpdate = groups.stream() - .filter(g -> g.getArtifacts() != null && g.getArtifacts() - .contains(artifactInfo - .getUniqueId())) - .collect(Collectors.toList()); + .filter(g -> g.getArtifacts() != null && g.getArtifacts() + .contains(artifactInfo + .getUniqueId())) + .collect(Collectors.toList()); if (groupToUpdate != null && !groupToUpdate.isEmpty()) { groupToUpdate.forEach(g -> { g.getArtifacts().remove(artifactInfo.getUniqueId()); g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID()); g.getArtifacts().add(artAfterUpdate.getUniqueId()); g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID()); + if(!artifactInfo.getArtifactUUID().equals(artAfterUpdate.getArtifactUUID())){ + g.setGroupUUID(UniqueIdBuilder.generateUUID()); + } }); Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate); if (status.isRight()) { log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId()); - return componentsUtils.convertFromStorageResponse(status.right().value()); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status.right().value())); } } } return ActionStatus.OK; } - private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) { + @VisibleForTesting + ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent) { List<GroupDefinition> groups = parent.getGroups(); if (groups != null && !groups.isEmpty()) { List<GroupDataDefinition> groupToUpdate = groups.stream() - .filter(g -> g.getArtifacts() != null && g.getArtifacts() - .contains(artifactInfoHeat - .getUniqueId())) - .collect(Collectors.toList()); + .filter(g -> g.getArtifacts() != null && g.getArtifacts() + .contains(artifactInfoHeat + .getUniqueId())) + .collect(Collectors.toList()); if (groupToUpdate != null && !groupToUpdate.isEmpty()) { groupToUpdate.forEach(g -> { g.getArtifacts().remove(artifactInfoHeat.getUniqueId()); @@ -541,13 +576,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return ActionStatus.OK; } - private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) { + private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, String parentId) { List<GroupInstance> updatedGroupInstances = new ArrayList<>(); List<GroupInstance> groupInstances = null; Optional<ComponentInstance> componentInstOp = parent.getComponentInstances() - .stream() - .filter(ci -> ci.getUniqueId().equals(parentId)) - .findFirst(); + .stream() + .filter(ci -> ci.getUniqueId().equals(parentId)) + .findFirst(); if (componentInstOp.isPresent()) { groupInstances = componentInstOp.get().getGroupInstances(); } @@ -556,15 +591,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { for (GroupInstance groupInstance : groupInstances) { isUpdated = false; if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts() - .contains(artifactInfo - .getUniqueId())) { + .contains(artifactInfo + .getUniqueId())) { groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId()); groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId()); isUpdated = true; } if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid() - .contains(artifactInfo - .getArtifactUUID())) { + .contains(artifactInfo + .getArtifactUUID())) { groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID()); groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID()); isUpdated = true; @@ -582,121 +617,77 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return ActionStatus.OK; } - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(Component parent, ArtifactDefinition artifactInfo) { - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result; + ArtifactDefinition generateNotSavedArtifact(Component parent, ArtifactDefinition artifactInfo) { if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) { - result = generateToscaArtifact(parent, artifactInfo, false, false); + return generateToscaArtifact(parent, artifactInfo, false, false); } else { String heatArtifactId = artifactInfo.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()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes - .right() - .value()), ""); - return Either.right(responseFormat); + log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo.getUniqueId()); + throw new StorageException(heatRes.right().value()); } String generatedPayload = generateHeatEnvPayload(heatRes.left().value()); artifactInfo.setPayloadData(generatedPayload); - result = Either.left(Either.left(artifactInfo)); + return artifactInfo; } - return result; } - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, - ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) { - convertParentType(componentType); - String parentId = parent.getUniqueId(); + private Either<ArtifactDefinition, Operation> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, + ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, + boolean needToUpdateGroup) { Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo .getGeneratedFromId()); ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value(); - if (origMd5 != null) { - Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); - if (validateMd5.isRight()) { - ResponseFormat responseFormat = validateMd5.right().value(); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - - if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) { - - Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction)); - if (payloadEither.isRight()) { - ResponseFormat responseFormat = payloadEither.right().value(); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - } - else { // duplicate - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); + validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); + if (ArrayUtils.isNotEmpty(artifactInfo.getPayloadData())) { + handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction)); + } else { // duplicate + throw new ByActionStatusComponentException(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD); } } + return updateHeatParams(componentId, artifactInfo, auditingAction, parent, componentType, currHeatArtifact, needToUpdateGroup); + } - // lock resource - if (shouldLock) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK); - if (lockComponent.isRight()) { - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right() - .value(), componentType, null); - return Either.right(lockComponent.right().value()); + private void handleLockingAndCommit(Component parent, boolean shouldLock, boolean inTransaction, boolean actionSucceeded) { + if (actionSucceeded) { + log.debug(COMMIT); + if (!inTransaction) { + janusGraphDao.commit(); } - } - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; - try { - resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, needToUpdateGroup); - return resultOp; - - } - finally { - // unlock resource - if (resultOp == null || resultOp.isRight()) { - log.debug(ROLLBACK); - if (!inTransaction) { + } else { + log.debug(ROLLBACK); + if (!inTransaction) { janusGraphDao.rollback(); - } - } - else { - log.debug(COMMIT); - if (!inTransaction) { - janusGraphDao.commit(); - } - } - if (shouldLock) { - graphLockOperation.unlockComponent(parent.getUniqueId(), parent.getComponentType().getNodeType()); } } + if (shouldLock) { + graphLockOperation.unlockComponent(parent.getUniqueId(), parent.getComponentType().getNodeType()); + } } - public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) { + public ImmutablePair<String, byte[]> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) { if (artifactGenerationRequired(component, csarArtifact)) { Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false); if (generated.isRight()) { log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right() - .value()); - - return Either.right(generated.right().value()); + .value()); + throw new ByResponseFormatComponentException(generated.right().value()); } - return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left() - .value())); + return new ImmutablePair<>(csarArtifact.getArtifactName(), generated.left().value()); } return downloadArtifact(csarArtifact); } - public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) { + public ImmutablePair<String, byte[]> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) { // perform all validation in common flow - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null, + Either<ArtifactDefinition, Operation> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null, null, parentId, containerComponentType); - if (result.isRight()) { - return Either.right(result.right().value()); - } ArtifactDefinition artifactDefinition; - Either<ArtifactDefinition, Operation> insideValue = result.left().value(); + Either<ArtifactDefinition, Operation> insideValue = result; if (insideValue.isLeft()) { artifactDefinition = insideValue.left().value(); } @@ -705,39 +696,35 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } // for tosca artifacts and heat env on VF level generated on download without saving if (artifactDefinition.getPayloadData() != null) { - return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition + return (new ImmutablePair<>(artifactDefinition.getArtifactName(), artifactDefinition .getPayloadData())); } return downloadArtifact(artifactDefinition); } - public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) { + public Map<String, ArtifactDefinition> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) { // step 1 // detect auditing type Map<String, ArtifactDefinition> resMap = null; - Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null; +// Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null; new Wrapper<>(); // step 2 // check header if (userId == null) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId); - - resultOp = Either.right(responseFormat); - return resultOp; + throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION); } // step 3 // check user existence // step 4 // check user's role - validateUserExists(userId, "get artifacts", false); + validateUserExists(userId); // steps 5 - 6 - 7 // 5. check service/resource existence // 6. check service/resource check out // 7. user is owner of checkout state - org.openecomp.sdc.be.model.Component component = null; String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId; ComponentParametersView componentFilter = new ComponentParametersView(); componentFilter.disableAll(); @@ -746,68 +733,50 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { componentFilter.setIgnoreComponentInstances(false); } - Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum + Component component = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum .findByParamName(containerComponentType), componentFilter); - - if (validateComponent.isRight()) { - resultOp = Either.right(validateComponent.right().value()); - return resultOp; - } - component = validateComponent.left().value(); - Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, UPDATE_ARTIFACT_LOCK); - if (lockComponent.isRight()) { - - resultOp = Either.right(lockComponent.right().value()); - return resultOp; - } - + lockComponent(component, ARTIFACT_ACTION_LOCK); + boolean failed = false; try { ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType); if (groupType == null) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId); - - resultOp = Either.right(responseFormat); - return resultOp; - + log.debug("handleGetArtifactsByType - not failed groupType {} , component id {}", artifactGroupType, componentId); + throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION); } if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) { List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId); if (list != null && !list.isEmpty()) { - resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a)); + resMap = list.stream().collect(Collectors.toMap(ArtifactDataDefinition::getArtifactLabel, Function.identity())); } else { resMap = new HashMap<>(); } - resultOp = Either.left(resMap); - return resultOp; - } - else { + return resMap; + } else { Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType .getNodeType(), groupType, componentId); if (artifactsMapStatus.isRight()) { if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId); - resultOp = Either.right(responseFormat); + log.debug("handleGetArtifactsByType - not failed groupType {} , component id {}", artifactGroupType, componentId); + throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION); } else { resMap = new HashMap<>(); - resultOp = Either.left(resMap); } } else { resMap = artifactsMapStatus.left().value(); - resultOp = Either.left(resMap); } - return resultOp; + return resMap; } - } - finally { + }catch (ComponentException e){ + failed = true; + throw e; + } finally { // unlock resource - if (resultOp == null || resultOp.isRight()) { + if (failed) { log.debug(ROLLBACK); janusGraphDao.rollback(); } @@ -823,30 +792,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } - private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, Component component) { - // step 9 + private ArtifactDefinition getArtifactIfBelongsToComponent(String componentId, ComponentTypeEnum componentType, String artifactId, Component component) { // check artifact existence - Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component - .getUniqueId()); + Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, + componentType, component.getUniqueId()); if (artifactResult.isRight()) { - if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""); - log.debug("addArtifact - artifact {} not found", artifactId); - return Either.right(responseFormat); - - } - else { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult - .right() - .value())); - log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right() - .value()); - return Either.right(responseFormat); - } + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, artifactId, componentId); } - // step 9.1 - // check artifact belong to component - boolean found = false; + // verify artifact belongs to component + boolean found; switch (componentType) { case RESOURCE: case SERVICE: @@ -856,137 +810,86 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { found = checkArtifactInResourceInstance(component, componentId, artifactId); break; default: - + found = false; } if (!found) { - String componentName = componentType.name().toLowerCase(); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName); - log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId); - return Either.right(responseFormat); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, artifactId, componentType.name().toLowerCase()); } - return Either.left(artifactResult.left().value()); + return artifactResult.left().value(); } - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType, - org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { - - String artifactId = null; - - // step 11 - Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName); - if (payloadEither.isRight()) { - return Either.right(payloadEither.right().value()); - } - byte[] decodedPayload = payloadEither.left().value(); - convertParentType(componentType); + private Either<ArtifactDefinition, Operation> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType, + Component parent, String origMd5, String originData, String interfaceType, String operationName) { + byte[] decodedPayload = validateInput(componentId, artifactInfo, operation, auditingAction, null, user, componentType, parent, origMd5, originData, interfaceType, operationName); + return createArtifact(parent, componentId, artifactInfo, decodedPayload, componentType, auditingAction, interfaceType, operationName); + } - if (shouldLock) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock "); - if (lockComponent.isRight()) { - handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right() - .value(), componentType, null); - return Either.right(lockComponent.right().value()); - } + private ArtifactDefinition handleLink(String componentId, ArtifactDefinition artifactInfo, ComponentTypeEnum componentType, + Component parent) { + ComponentInstance foundInstance = findComponentInstance(componentId, parent); + String instanceId = null; + if (foundInstance != null) { + instanceId = foundInstance.getUniqueId(); } - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; - - try { - resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName); - return resultOp; + NodeTypeEnum nodeType = convertParentType(componentType); + Either<ArtifactDefinition, StorageOperationStatus> artifactDefinitionEither = artifactToscaOperation.addArtifactToComponent(artifactInfo, parent, + nodeType, true, instanceId); + if (artifactDefinitionEither.isRight()) { + throw new StorageException(artifactDefinitionEither.right().value(), artifactInfo.getArtifactDisplayName()); } - finally { - if (shouldLock) { - unlockComponent(resultOp, parent, inTransaction); - } - + if (generateCustomizationUUIDOnInstance(parent.getUniqueId(), componentId, componentType) != StorageOperationStatus.OK) { + throw new StorageException(artifactDefinitionEither.right().value(), artifactInfo.getArtifactDisplayName()); } - + return artifactDefinitionEither.left().value(); } - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleLink(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType, - Component parent, boolean shouldLock, boolean inTransaction) { - - if (shouldLock) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock "); - if (lockComponent.isRight()) { - handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right() - .value(), componentType, null); - return Either.right(lockComponent.right().value()); - } - } - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; + 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) { + Either<ArtifactDefinition, Operation> resultOp = null; + boolean failed = false; + boolean writeAudit = true; try { - resultOp = createAndLinkArtifact(parent, componentId, artifactInfo, user, componentType, auditingAction); + lockComponent(parent, shouldLock, ARTIFACT_ACTION_LOCK); + writeAudit = false; + resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, decodedPayload, componentType, auditingAction, interfaceType, operationName); return resultOp; } - finally { - if (shouldLock) { - unlockComponent(resultOp, parent, inTransaction); + catch (ComponentException ce) { + if(writeAudit) { + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, ce.getResponseFormat(), componentType, null); } - + failed = true; + throw ce; } - - } - - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, - ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { - - convertParentType(componentType); - - // lock resource - if (shouldLock) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK); - - if (lockComponent.isRight()) { - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right() - .value(), componentType, null); - return Either.right(lockComponent.right().value()); - } - } - - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; - try { - resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName); - return resultOp; - + catch (StorageException se) { + //TODO: audit + failed = true; + throw se; } finally { if (shouldLock) { - unlockComponent(resultOp, parent, inTransaction); + unlockComponent(failed, parent, inTransaction); } } } - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, - ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { - - Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName); - - if (payloadEither.isRight()) { - return Either.right(payloadEither.right().value()); - } - byte[] decodedPayload = payloadEither.left().value(); - - return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction); + private byte[] validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType, + Component parent, String origMd5, String originData, String interfaceType, String operationName) { + validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); + return getValidPayload(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, interfaceType, operationName); } - private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType, - Component parent, String origMd5, String originData, String interfaceType, String operationName) { - // Md5 validations - Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); - if (validateMd5.isRight()) { - ResponseFormat responseFormat = validateMd5.right().value(); - handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - + private byte[] getValidPayload(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, + String artifactId, User user, ComponentTypeEnum componentType, Component parent, String interfaceType, String operationName) { // step 11 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent); if (validateResult.isRight()) { ResponseFormat responseFormat = validateResult.right().value(); handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(validateResult.right().value()); + throw new ByResponseFormatComponentException(responseFormat); } Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction)); @@ -994,24 +897,24 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { ResponseFormat responseFormat = payloadEither.right().value(); handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); log.debug("Error during handle payload"); - return Either.right(responseFormat); + throw new ByResponseFormatComponentException(responseFormat); } - // validate heat parameters. this part must be after the parameters are // extracted in "handlePayload" - Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo + Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParameters = validateAndConvertHeatParameters(artifactInfo, artifactInfo .getArtifactType()); - if (validateAndConvertHeatParamers.isRight()) { - ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value(); + if (validateAndConvertHeatParameters.isRight()) { + ResponseFormat responseFormat = validateAndConvertHeatParameters.right().value(); handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null); log.debug("Error during handle payload"); - return Either.right(responseFormat); + throw new ByResponseFormatComponentException(responseFormat); } - return payloadEither; + return payloadEither.left().value(); } - public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat, - ComponentTypeEnum componentTypeEnum, String resourceInstanceName) { + public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, + ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, + ResponseFormat responseFormat, ComponentTypeEnum componentTypeEnum, String resourceInstanceName) { if (componentsUtils.isExternalApiEvent(auditingActionEnum)) { return; @@ -1077,10 +980,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private String getResourceInstanceNameFromComponent(Component component, String componentId) { ComponentInstance resourceInstance = component.getComponentInstances() - .stream() - .filter(p -> p.getUniqueId().equals(componentId)) - .findFirst() - .orElse(null); + .stream() + .filter(p -> p.getUniqueId().equals(componentId)) + .findFirst() + .orElse(null); String resourceInstanceName = null; if (resourceInstance != null) { resourceInstanceName = resourceInstance.getName(); @@ -1088,83 +991,40 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return resourceInstanceName; } - private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) { - StringBuilder sb = new StringBuilder(); - if (artifactDefinition != null) { - sb.append(artifactDefinition.getArtifactGroupType().getType()) - .append(",") - .append("'") - .append(artifactDefinition.getArtifactLabel()) - .append("'") - .append(",") - .append(artifactDefinition.getArtifactType()) - .append(",") - .append(artifactDefinition.getArtifactName()) - .append(",") - .append(artifactDefinition.getTimeout()) - .append(",") - .append(artifactDefinition.getEsId()); - - sb.append(","); - if (artifactDefinition.getArtifactVersion() != null) { - - sb.append(artifactDefinition.getArtifactVersion()); - } - else { - sb.append(" "); - } - sb.append(","); - if (artifactDefinition.getArtifactUUID() != null) { - sb.append(artifactDefinition.getArtifactUUID()); + private void validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) { + if (origMd5 == null) { + if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && ArrayUtils.isNotEmpty(payload)) { + log.debug("Missing md5 header during artifact create"); + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_INVALID_MD5); } - else { - sb.append(" "); + // Update metadata + if (ArrayUtils.isNotEmpty(payload)) { + log.debug("Cannot have payload while md5 header is missing"); + throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); } - } - return sb.toString(); - } - - private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) { - - if (origMd5 != null) { + } else { String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData); if (!encodeBase64Str.equals(origMd5)) { log.debug("The calculated md5 is different then the received one"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5)); - } - } - else { - if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && payload != null && payload.length != 0) { - log.debug("Missing md5 header during artifact create"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5)); - } - // Update metadata - if (payload != null && payload.length != 0) { - log.debug("Cannot have payload while md5 header is missing"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_INVALID_MD5); } } - return Either.left(true); } private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName, ComponentTypeEnum componentType, Component parentComponent) { - Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId); - if (artifactById.isRight()) { - return Either.right(artifactById.right().value()); - } - ArtifactDefinition currentArtifactInfo = artifactById.left().value(); - + ArtifactDefinition currentArtifactInfo = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId); ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo); - Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent); - if (validateInformationalArtifactRes.isRight()) { - return Either.right(validateInformationalArtifactRes.right().value()); - } - Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo); + validateInformationalArtifact(artifactInfo, parentComponent); + Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactName( + artifactInfo); if (validateAndSetArtifactname.isRight()) { return Either.right(validateAndSetArtifactname.right().value()); } + if (!validateArtifactNameUniqueness(componentId, parentComponent, artifactInfo, componentType)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST)); + } if (operationName != null && interfaceName != null) { operationName = operationName.toLowerCase(); interfaceName = interfaceName.toLowerCase(); @@ -1196,15 +1056,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.right(validateGroupType.right().value()); } } + // TODO TEMP !!! NodeTypeEnum parentType = convertParentType(componentType); + // TODO TEMP !!! boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()); if (isDeploymentArtifact(artifactInfo)) { - Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, isCreate, artifactInfo, currentArtifactInfo, parentType); - if (deploymentValidationResult.isRight()) { - return Either.right(deploymentValidationResult.right().value()); - } + validateDeploymentArtifact(parentComponent, componentId, isCreate, artifactInfo, currentArtifactInfo, parentType); } else { artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT); @@ -1215,8 +1074,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.right(descriptionResult.right().value()); } - if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType() - .equals(ArtifactGroupTypeEnum.SERVICE_API)) { + if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.SERVICE_API) { Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType); if (validateServiceApiType.isRight()) { return Either.right(validateServiceApiType.right().value()); @@ -1256,32 +1114,28 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) { - if (operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.UPDATE)) { + if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) { artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType()); artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType()); artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel()); } } - private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) { + private ArtifactDefinition findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) { - Either<ArtifactDefinition, ResponseFormat> result = null; ArtifactDefinition foundArtifact = null; if (StringUtils.isNotEmpty(artifactId)) { foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId); } if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { log.debug("Artifact {} already exist", artifactId); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel())); + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()); } if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "")); + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, ""); } - if (result == null) { - result = Either.left(foundArtifact); - } - return result; + return foundArtifact; } private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) { @@ -1296,41 +1150,38 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return foundArtifact; } - private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) { + private void validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) { ComponentTypeEnum parentComponentType = parentComponent.getComponentType(); ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType(); - Either<Boolean, ResponseFormat> validationResult = Either.left(true); ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); if (artifactType == null) { - validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo - .getArtifactType())); + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()); } else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) { String artifactTypeName = artifactType.getType(); ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType(); Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager() - .getConfiguration() - .getResourceInformationalArtifacts(); + .getConfiguration() + .getResourceInformationalArtifacts(); Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet(); if (!validArtifactTypes.contains(artifactTypeName)) { - validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName)); + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName); } else { List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName) - .getValidForResourceTypes(); + .getValidForResourceTypes(); if (!validResourceType.contains(parentResourceType.name())) { - validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName)); + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName); } } } - return validationResult; } private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) { - if (componentType.equals(ComponentTypeEnum.RESOURCE)) { + if (componentType == ComponentTypeEnum.RESOURCE) { return NodeTypeEnum.Resource; } - else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) { + else if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { return NodeTypeEnum.ResourceInstance; } else { @@ -1338,213 +1189,133 @@ 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) { + ResponseFormat responseFormat; + boolean operationSucceeded = false; + if (shouldLock) { + lockComponent(componentType, artifactId, auditingAction, user, parent); + } + try { + ArtifactDefinition artifactDefinition = handleDeleteInternal(parentId, artifactId, componentType, parent); + operationSucceeded = true; + return Either.left(Either.left(artifactDefinition)); + } + catch (ComponentException ce) { + responseFormat = componentsUtils.getResponseFormat(ce); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + catch (StorageException se) { + responseFormat = componentsUtils.getResponseFormat(se); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } finally { + handleLockingAndCommit(parent, shouldLock, inTransaction, operationSucceeded); + } + } + private ArtifactDefinition handleDeleteInternal(String parentId, String artifactId, ComponentTypeEnum componentType, Component parent) { NodeTypeEnum parentType = convertParentType(componentType); - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; - Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null; - ArtifactDefinition foundArtifact = null; - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null; - org.openecomp.sdc.be.model.Component fetchedContainerComponent = null; + log.debug("Going to find the artifact {} on the component {}", artifactId, parent.getUniqueId()); + 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()); + throw new ByActionStatusComponentException(getArtifactRes.right().value(), artifactId); + } + ArtifactDefinition foundArtifact = getArtifactRes.left().value().getLeft(); + ComponentInstance foundInstance = getArtifactRes.left().value().getRight(); + String esId = foundArtifact.getEsId(); + 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()); + } + } + boolean isNeedToDeleteArtifactFromDB = true; boolean isDuplicated = false; - String esId = null; - Either<Boolean, StorageOperationStatus> needCloneRes = null; - try { - if (shouldLock) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: "); - if (lockComponent.isRight()) { - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right() - .value(), componentType, null); - resultOp = Either.right(lockComponent.right().value()); - } - } - if (resultOp == null) { - log.debug("Going to fetch the container component {}. ", parent.getUniqueId()); - getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId()); - if (getContainerRes.isRight()) { - log.debug("Failed to fetch the container component {}. ", parentId); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes - .right() - .value()), artifactId); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } - } - if (resultOp == null) { - fetchedContainerComponent = getContainerRes.left().value(); - log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId()); - getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType); - if (getArtifactRes.isRight()) { - log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent - .getUniqueId()); - responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right() - .value(), artifactId); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } - else { - foundArtifact = getArtifactRes.left().value().getLeft(); - esId = foundArtifact.getEsId(); - } - } - if (resultOp == null && StringUtils.isNotEmpty(esId)) { - needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent - .getComponentType())); - if (needCloneRes.isRight()) { - log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes - .right() - .value()), foundArtifact.getArtifactDisplayName()); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } - } - boolean isNeedToDeleteArtifactFromDB = true; - if (resultOp == null) { - - if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { - String instanceId = parentId; - Either<Boolean, ActionStatus> isOnlyResourceInstanceArtifact = isArtifactOnlyResourceInstanceArtifact(foundArtifact, fetchedContainerComponent, instanceId); - - if (isOnlyResourceInstanceArtifact.isRight()) { - log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId); - responseFormat = componentsUtils.getResponseFormatByArtifactId(isOnlyResourceInstanceArtifact.right() - .value(), foundArtifact - .getArtifactDisplayName()); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - isNeedToDeleteArtifactFromDB = isOnlyResourceInstanceArtifact.left().value(); - } - - Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes - .left() - .value()); - if (updatedArtifactRes.isRight()) { - log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes - .right() - .value()), foundArtifact.getArtifactDisplayName()); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } - else { - isDuplicated = updatedArtifactRes.left().value().getDuplicated(); - } - } + if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { + isNeedToDeleteArtifactFromDB = isArtifactOnlyResourceInstanceArtifact(foundArtifact, parent, parentId); + } + ArtifactDataDefinition updatedArtifact = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needToClone); + isDuplicated = updatedArtifact.getDuplicated(); - if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated) && isNeedToDeleteArtifactFromDB) { - log.debug("Going to delete the artifact {} from the database. ", artifactId); - CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId); - if (cassandraStatus != CassandraOperationStatus.OK) { - log.debug("Failed to delete the artifact {} from the database. ", artifactId); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(componentsUtils.convertToStorageOperationStatus(cassandraStatus)), foundArtifact - .getArtifactDisplayName()); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } + if (!needToClone && !isDuplicated && isNeedToDeleteArtifactFromDB) { + log.debug("Going to delete the artifact {} from the database. ", artifactId); + CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId); + if (cassandraStatus != CassandraOperationStatus.OK) { + log.debug("Failed to delete the artifact {} from the database. ", artifactId); + throw new StorageException(convertToStorageOperationStatus(cassandraStatus), foundArtifact.getArtifactDisplayName()); } - if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { - - List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes - .left() - .value() - .getRight() - .getGroupInstances()); - if (CollectionUtils.isNotEmpty(updatedGroupInstances)) { - Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, parentId, updatedGroupInstances); - if (status.isRight()) { - log.debug(FAILED_UPDATE_GROUPS, fetchedContainerComponent.getUniqueId()); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status - .right() - .value()), foundArtifact.getArtifactDisplayName()); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } + } + if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { + List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, foundInstance.getGroupInstances()); + if (CollectionUtils.isNotEmpty(updatedGroupInstances)) { + Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances); + if (status.isRight()) { + log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId()); + throw new StorageException(status.right().value(), foundArtifact.getArtifactDisplayName()); } } - if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { - StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType); - if (status != StorageOperationStatus.OK) { - log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact - .getArtifactDisplayName()); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } + StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType); + if (status != StorageOperationStatus.OK) { + log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId); + throw new StorageException(status, foundArtifact.getArtifactDisplayName()); } - if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) { - List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent - .getGroups()); - if (CollectionUtils.isNotEmpty(updatedGroups)) { - Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, updatedGroups); - if (status.isRight()) { - log.debug(FAILED_UPDATE_GROUPS, fetchedContainerComponent.getUniqueId()); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status - .right() - .value()), foundArtifact.getArtifactDisplayName()); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } + } else { + List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, parent.getGroups()); + if (CollectionUtils.isNotEmpty(updatedGroups)) { + Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, updatedGroups); + if (status.isRight()) { + log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId()); + throw new StorageException(status.right().value(), foundArtifact.getArtifactDisplayName()); } } - if (resultOp == null) { - resultOp = Either.left(Either.left(foundArtifact)); - handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null); - } - return resultOp; - } - finally { - if (shouldLock) { - unlockComponent(resultOp, parent, inTransaction); - } } + return foundArtifact; } - private Either<Boolean, ActionStatus> isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) { - Either<Boolean, ActionStatus> result = Either.left(true); - ComponentInstance foundInstance = null; - Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstances() - .stream() - .filter(i -> i.getUniqueId().equals(instanceId)) - .findFirst(); + private boolean isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) { + Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstanceById(instanceId); if (!componentInstanceOpt.isPresent()) { - result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER); - } - else { - foundInstance = componentInstanceOpt.get(); - String componentUid = foundInstance.getComponentUid(); - Either<Component, StorageOperationStatus> getContainerRes = toscaOperationFacade.getToscaElement(componentUid); - if (getContainerRes.isRight()) { - log.debug("Failed to fetch the container component {}. ", componentUid); - return Either.right(componentsUtils.convertFromStorageResponse(getContainerRes.right().value())); - } - Component origComponent = getContainerRes.left().value(); - Map<String, ArtifactDefinition> deploymentArtifacts = origComponent.getDeploymentArtifacts(); - if (deploymentArtifacts != null && !deploymentArtifacts.isEmpty()) { - Optional<String> op = deploymentArtifacts.keySet() - .stream() - .filter(a -> a.equals(foundArtifact.getArtifactLabel())) - .findAny(); - if (op.isPresent()) { - return Either.left(false); - } + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "", "", parent.getName()); + } + ComponentInstance foundInstance = componentInstanceOpt.get(); + String componentUid = foundInstance.getComponentUid(); + Either<Component, StorageOperationStatus> getContainerRes = toscaOperationFacade.getToscaElement(componentUid); + if (getContainerRes.isRight()) { + log.debug("Failed to fetch the container component {}. ", componentUid); + throw new StorageException(getContainerRes.right().value()); + } + Component origComponent = getContainerRes.left().value(); + Map<String, ArtifactDefinition> deploymentArtifacts = origComponent.getDeploymentArtifacts(); + if (MapUtils.isNotEmpty(deploymentArtifacts)) { + Optional<String> op = deploymentArtifacts.keySet() + .stream() + .filter(a -> a.equals(foundArtifact.getArtifactLabel())) + .findAny(); + if (op.isPresent()) { + return false; } - Map<String, ArtifactDefinition> artifacts = origComponent.getArtifacts(); - if (artifacts != null && !artifacts.isEmpty()) { - Optional<String> op = artifacts.keySet() - .stream() - .filter(a -> a.equals(foundArtifact.getArtifactLabel())) - .findAny(); - if (op.isPresent()) { - return Either.left(false); - } + } + Map<String, ArtifactDefinition> artifacts = origComponent.getArtifacts(); + if (MapUtils.isNotEmpty(artifacts)) { + Optional<String> op = artifacts.keySet() + .stream() + .filter(a -> a.equals(foundArtifact.getArtifactLabel())) + .findAny(); + if (op.isPresent()) { + return false; } - } - return result; + return true; } private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) { @@ -1558,7 +1329,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { isUpdated = true; } if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid() - .contains(foundArtifact.getArtifactUUID())) { + .contains(foundArtifact.getArtifactUUID())) { group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID()); isUpdated = true; } @@ -1576,14 +1347,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { boolean isUpdated = false; for (GroupInstance groupInstance : groupInstances) { isUpdated = false; - if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts() - .contains(artifactId)) { + 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())) { + .contains(foundArtifact.getArtifactUUID())) { groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID()); isUpdated = true; } @@ -1595,7 +1364,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return updatedGroupInstances; } - private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) { + private ArtifactDataDefinition deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) { Either<ArtifactDataDefinition, StorageOperationStatus> result; boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi(); @@ -1604,7 +1373,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (isMandatory) { log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId); resetMandatoryArtifactFields(foundArtifact); - result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true, true); + result = artifactToscaOperation.updateArtifactOnGraph(component, foundArtifact, parentType, artifactId, instanceId, true, true); } else if (cloneIsNeeded) { log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId); @@ -1614,7 +1383,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId); result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false); } - return result; + if (result.isRight()) { + throw new StorageException(result.right().value(), foundArtifact.getArtifactDisplayName()); + } + return result.left().value(); } private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) { @@ -1624,10 +1396,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { ComponentInstance foundInstance = null; if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) { Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances() - .stream() - .filter(i -> i.getUniqueId() - .equals(parentId)) - .findFirst(); + .stream() + .filter(i -> i.getUniqueId() + .equals(parentId)) + .findFirst(); if (!componentInstanceOpt.isPresent()) { result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER); } @@ -1654,27 +1426,27 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { Map<String, ArtifactDefinition> currArtifacts; if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) { currArtifacts = component.getDeploymentArtifacts() - .values() - .stream() - .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); + .values() + .stream() + .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, i -> i)); if (MapUtils.isNotEmpty(currArtifacts)) { artifacts.putAll(currArtifacts); } } if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) { currArtifacts = component.getArtifacts() - .values() - .stream() - .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); + .values() + .stream() + .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity())); if (MapUtils.isNotEmpty(currArtifacts)) { artifacts.putAll(currArtifacts); } } if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) { currArtifacts = component.getToscaArtifacts() - .values() - .stream() - .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); + .values() + .stream() + .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity())); if (MapUtils.isNotEmpty(currArtifacts)) { artifacts.putAll(currArtifacts); } @@ -1685,24 +1457,44 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { Map<String, ArtifactDefinition> currArtifacts; if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) { currArtifacts = instance.getDeploymentArtifacts() - .values() - .stream() - .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); + .values() + .stream() + .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity())); if (MapUtils.isNotEmpty(currArtifacts)) { artifacts.putAll(currArtifacts); } } if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) { currArtifacts = instance.getArtifacts() - .values() - .stream() - .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); + .values() + .stream() + .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity())); if (MapUtils.isNotEmpty(currArtifacts)) { artifacts.putAll(currArtifacts); } } } + private StorageOperationStatus convertToStorageOperationStatus(CassandraOperationStatus cassandraStatus) { + StorageOperationStatus result; + switch (cassandraStatus) { + case OK: + result = StorageOperationStatus.OK; + break; + case NOT_FOUND: + result = StorageOperationStatus.NOT_FOUND; + break; + case CLUSTER_NOT_CONNECTED: + case KEYSPACE_NOT_CONNECTED: + result = StorageOperationStatus.CONNECTION_FAILURE; + break; + default: + result = StorageOperationStatus.GENERAL_ERROR; + break; + } + return result; + } + private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) { if (fetchedArtifact != null) { log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId()); @@ -1729,29 +1521,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return error; } - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, - Component parent) { - Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent - .getUniqueId()); + private ArtifactDefinition handleDownload(String componentId, String artifactId, ComponentTypeEnum componentType, + Component parent) { + Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, + parent.getUniqueId()); if (artifactById.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value()); - log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, ""); - handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); + throw new StorageException(artifactById.right().value()); } ArtifactDefinition artifactDefinition = artifactById.left().value(); if (artifactDefinition == null) { - log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""); - handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactId); } - - Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null); - return Either.left(insideEither); + return artifactDefinition; } private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, String operationName, @@ -1759,9 +1540,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String artifactLabel = artifactInfo.getArtifactLabel(); if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel() - .isEmpty())) { + .isEmpty())) { BeEcompErrorManager.getInstance() - .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel"); + .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel"); log.debug("missing artifact logical name for component {}", componentId); return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL)); } @@ -1812,7 +1593,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) { boolean isUnique = true; Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts; - if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) { + if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId); } else { @@ -1827,21 +1608,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } } - if (componentType.equals(ComponentTypeEnum.RESOURCE)) { - Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation - .getAllInterfacesOfResource(componentId, true, true); - if (allInterfacesOfResource.isLeft()) { - for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) { - for (Operation operation : interace.getOperationsMap().values()) { - if (operation.getImplementation() != null && operation.getImplementation() - .getArtifactLabel() - .equals(artifactLabel)) { - isUnique = false; - break; - } - } - } - } + if (componentType == ComponentTypeEnum.RESOURCE && isUnique) { + isUnique = isUniqueLabelInResourceInterfaces(componentId, artifactLabel); } return isUnique; } @@ -1859,7 +1627,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return false; } } - if (ComponentTypeEnum.RESOURCE.equals(componentType)) { + if (ComponentTypeEnum.RESOURCE == componentType) { return isUniqueArtifactNameInResourceInterfaces(componentId, artifactName, artifactInfo.getArtifactLabel()); } return true; @@ -1869,14 +1637,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation .getAllInterfacesOfResource(componentId, true, true); - if (allInterfacesOfResource.isLeft() && Objects.nonNull(allInterfacesOfResource)){ - return !allInterfacesOfResource.left().value() + if (allInterfacesOfResource.isLeft()){ + return allInterfacesOfResource.left().value() .values() .stream().map(InterfaceDefinition :: getOperationsMap) .flatMap(map -> map.values().stream()) .map(OperationDataDefinition::getImplementation) .filter(Objects::nonNull) - .anyMatch(add -> artifactName.equals(add.getArtifactName()) + .noneMatch(add -> artifactName.equals(add.getArtifactName()) && !artifactLabel.equals(add.getArtifactLabel())); } return true; @@ -1887,13 +1655,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { .getAllInterfacesOfResource(componentId, true, true); if (allInterfacesOfResource.isLeft()){ - return !allInterfacesOfResource.left().value() + return allInterfacesOfResource.left().value() .values() .stream().map(InterfaceDefinition :: getOperationsMap) .flatMap(map -> map.values().stream()) .map(OperationDataDefinition::getImplementation) .filter(Objects::nonNull) - .anyMatch(add -> artifactLabel.equals(add.getArtifactLabel())); + .noneMatch(add -> artifactLabel.equals(add.getArtifactLabel())); } return true; } @@ -1901,349 +1669,196 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(ComponentTypeEnum componentType, Component parentComponent, String componentId, ArtifactGroupTypeEnum artifactGroupType) { Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse; - if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) { + if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { artifactsResponse = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId); } else { artifactsResponse = artifactToscaOperation.getArtifacts(componentId); } - if (artifactsResponse.isRight() && artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + if (artifactsResponse.isRight() && artifactsResponse.right().value() == StorageOperationStatus.NOT_FOUND) { log.debug("failed to retrieve artifacts for {} ", componentId); return Either.right(artifactsResponse.right().value()); } return Either.left(artifactsResponse.left().value().entrySet() .stream() - .filter(x -> artifactGroupType.equals(x.getValue().getArtifactGroupType())) + .filter(x -> artifactGroupType == x.getValue().getArtifactGroupType()) .collect(Collectors.toMap(Entry::getKey, Entry::getValue))); } - private List<String> getListOfArtifactName(Map<String, ArtifactDefinition> artifacts) { - return artifacts.entrySet() - .stream() - .map(x -> x.getValue().getArtifactName()) - .collect(Collectors.toList()); - } - // *************************************************************** - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user, - ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum) { - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; - Either<ArtifactDefinition, Operation> insideEither = null; - ComponentInstance foundInstance = findComponentInstance(parentId, parent); - String instanceId = null; - String instanceName = null; - if (foundInstance != null) { - instanceId = foundInstance.getUniqueId(); - instanceName = foundInstance.getName(); - } - boolean isLeft = false; - String artifactUniqueId = null; - StorageOperationStatus error = null; - // information/deployment/api aritfacts - log.trace("Try to create entry on graph"); - NodeTypeEnum nodeType = convertParentType(componentTypeEnum); - Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent - .getUniqueId(), nodeType, true, instanceId); - - isLeft = result.isLeft(); - if (isLeft) { - artifactUniqueId = result.left().value().getUniqueId(); - result.left().value(); - - insideEither = Either.left(result.left().value()); - resultOp = Either.left(insideEither); - - error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum); - if (error != StorageOperationStatus.OK) { - isLeft = false; - } - - } - if (isLeft) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName); - return resultOp; - } - else { - log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo - .getArtifactDisplayName()); - handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName); - resultOp = Either.right(responseFormat); - return resultOp; + private Either<ArtifactDefinition, Operation> createArtifact(Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, + ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) { + DAOArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload); + if (artifactData == null) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact"); + log.debug("Failed to create artifact object for ES."); + throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } - } - - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user, - ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) { - - ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload); - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; - Either<ArtifactDefinition, Operation> insideEither = null; ComponentInstance foundInstance = findComponentInstance(parentId, parent); String instanceId = null; - String instanceName = null; if (foundInstance != null) { if (foundInstance.isArtifactExists(artifactInfo.getArtifactGroupType(), artifactInfo.getArtifactLabel())) { log.debug("Failed to create artifact, already exists"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactInfo - .getArtifactLabel()); - handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactInfo.getUniqueId(), responseFormat, componentTypeEnum, foundInstance - .getName()); - resultOp = Either.right(responseFormat); - return resultOp; + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_EXIST, artifactInfo.getArtifactLabel()); } - instanceId = foundInstance.getUniqueId(); - instanceName = foundInstance.getName(); - } - if (artifactData == null) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact"); - log.debug("Failed to create artifact object for ES."); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null); - resultOp = Either.right(responseFormat); - return resultOp; - } // set on graph object id of artifact in ES! artifactInfo.setEsId(artifactData.getId()); - boolean isLeft = false; - String artifactUniqueId = null; - StorageOperationStatus error = null; + Either<ArtifactDefinition, Operation> operationResult; if (interfaceType != null && operationName != null) { // lifecycle artifact Operation operation = convertToOperation(artifactInfo, operationName); - Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation); - - isLeft = result.isLeft(); - if (isLeft) { - artifactUniqueId = result.left().value().getImplementation().getUniqueId(); - result.left().value().getImplementation(); - - insideEither = Either.right(result.left().value()); - resultOp = Either.left(insideEither); - } - else { - error = result.right().value(); + if (result.isRight()) { + throw new StorageException(result.right().value()); } + operationResult = Either.right(result.left().value()); } else { - // information/deployment/api aritfacts - log.trace("Try to create entry on graph"); + // information/deployment/api artifacts NodeTypeEnum nodeType = convertParentType(componentTypeEnum); - Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent - .getUniqueId(), nodeType, true, instanceId); - - isLeft = result.isLeft(); - if (isLeft) { - artifactUniqueId = result.left().value().getUniqueId(); - artifactData.setId(result.left().value().getEsId()); - insideEither = Either.left(result.left().value()); - resultOp = Either.left(insideEither); - - error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum); - if (error != StorageOperationStatus.OK) { - isLeft = false; - } - - } - else { - error = result.right().value(); - } - } - if (isLeft) { - boolean res = saveArtifacts(artifactData, parentId); - - if (res) { - log.debug(ARTIFACT_SAVED, artifactUniqueId); - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName); - return resultOp; + Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArtifactToComponent( + artifactInfo, parent, nodeType, true, instanceId); + if (result.isRight()) { + throw new StorageException(result.right().value()); } - else { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact"); - log.debug(FAILED_SAVE_ARTIFACT); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName); + ArtifactDefinition artifactDefinition = result.left().value(); + artifactData.setId(artifactDefinition.getEsId()); + operationResult = Either.left(artifactDefinition); - resultOp = Either.right(responseFormat); - return resultOp; + if (generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum) != StorageOperationStatus.OK) { + throw new StorageException(generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum)); } } - else { - log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo - .getArtifactDisplayName()); - handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName); - resultOp = Either.right(responseFormat); - return resultOp; - } - + saveArtifactInCassandra(artifactData, parent, artifactInfo, "", "", auditingActionEnum, componentTypeEnum); + return operationResult; } private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) { ComponentInstance foundInstance = null; if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) { foundInstance = containerComponent.getComponentInstances() - .stream() - .filter(i -> i.getUniqueId().equals(componentInstanceId)) - .findFirst() - .orElse(null); + .stream() + .filter(i -> i.getUniqueId().equals(componentInstanceId)) + .findFirst() + .orElse(null); } return foundInstance; } - private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) { - - Either<Boolean, ResponseFormat> result = Either.left(true); - Wrapper<ResponseFormat> responseWrapper = new Wrapper<>(); - - validateArtifactTypeExists(responseWrapper, artifactInfo); - - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); + private void validateDeploymentArtifact(Component parentComponent, String parentId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) { + ArtifactTypeEnum artifactType = getValidArtifactType(artifactInfo); Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType); - - if (responseWrapper.isEmpty()) { - validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts); + validateDeploymentArtifactTypeIsLegalForParent(artifactInfo, artifactType, resourceDeploymentArtifacts); + if (!isCreate) { + validateArtifactTypeNotChanged(artifactInfo, currentArtifact); } - - // Common code for all types - // not allowed to change artifactType - if (responseWrapper.isEmpty() && !isCreate) { - Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact); - if (validateServiceApiType.isRight()) { - responseWrapper.setInnerElement(validateServiceApiType.right().value()); - } - } - if (responseWrapper.isEmpty()) { - if (parentType.equals(NodeTypeEnum.Resource)) { - Resource resource = (Resource) parentComponent; - ResourceTypeEnum resourceType = resource.getResourceType(); - ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType()); - if (config == null) { - responseWrapper.setInnerElement(ResponseFormatManager.getInstance() - .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo - .getArtifactType())); - } - else { - List<String> myList = config.getValidForResourceTypes(); - Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList); - if (either.isRight()) { - responseWrapper.setInnerElement(either.right().value()); - } - } + if (parentType == NodeTypeEnum.Resource) { + Resource resource = (Resource) parentComponent; + ResourceTypeEnum resourceType = resource.getResourceType(); + ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType()); + if (config == null) { + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()); } - - validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType); + List<String> myList = config.getValidForResourceTypes(); + validateResourceType(resourceType, artifactInfo, myList); } - if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) { + validateFileExtension(() -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType); + + if (NodeTypeEnum.ResourceInstance != parentType) { String artifactName = artifactInfo.getArtifactName(); if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) { - validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType); + validateSingleDeploymentArtifactName(artifactName, parentComponent, parentType); } } - if (responseWrapper.isEmpty()) { - switch (artifactType) { - case HEAT: - case HEAT_VOL: - case HEAT_NET: - result = validateHeatDeploymentArtifact(isCreate, artifactInfo, currentArtifact); - break; - case HEAT_ENV: - result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, artifactInfo, parentType); - artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT); - break; - case DCAE_INVENTORY_TOSCA: - case DCAE_INVENTORY_JSON: - case DCAE_INVENTORY_POLICY: - // Validation is done in handle payload. - case DCAE_INVENTORY_DOC: - case DCAE_INVENTORY_BLUEPRINT: - case DCAE_INVENTORY_EVENT: - // No specific validation - default: - artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT); - break; - } - - } - - if (!responseWrapper.isEmpty()) { - result = Either.right(responseWrapper.getInnerElement()); + switch (artifactType) { + case HEAT: + case HEAT_VOL: + case HEAT_NET: + validateHeatTimeoutValue(isCreate, artifactInfo, currentArtifact); + break; + case HEAT_ENV: + validateHeatEnvDeploymentArtifact(parentComponent, parentId, artifactInfo, parentType); + artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT); + break; + case DCAE_INVENTORY_TOSCA: + case DCAE_INVENTORY_JSON: + case DCAE_INVENTORY_POLICY: + // Validation is done in handle payload. + case DCAE_INVENTORY_DOC: + case DCAE_INVENTORY_BLUEPRINT: + case DCAE_INVENTORY_EVENT: + // No specific validation + default: + artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT); + break; } - return result; } - private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) { + @VisibleForTesting + void validateDeploymentArtifactTypeIsLegalForParent(ArtifactDefinition artifactInfo, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) { if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance() - .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo - .getArtifactType()); - responseWrapper.setInnerElement(responseFormat); log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType()); + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()); } } private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) { - Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null; - if (parentType.equals(NodeTypeEnum.Resource)) { + Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts; + if (parentType == NodeTypeEnum.Resource) { resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager() - .getConfiguration() - .getResourceDeploymentArtifacts(); + .getConfiguration() + .getResourceDeploymentArtifacts(); } - else if (parentType.equals(NodeTypeEnum.ResourceInstance)) { + else if (parentType == NodeTypeEnum.ResourceInstance) { resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager() - .getConfiguration() - .getResourceInstanceDeploymentArtifacts(); + .getConfiguration() + .getResourceInstanceDeploymentArtifacts(); } else { resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager() - .getConfiguration() - .getServiceDeploymentArtifacts(); + .getConfiguration() + .getServiceDeploymentArtifacts(); } return resourceDeploymentArtifacts; } - public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) { + public ArtifactTypeEnum getValidArtifactType(ArtifactDefinition artifactInfo) { ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); if (artifactType == null) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance() - .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo - .getArtifactType()); - responseWrapper.setInnerElement(responseFormat); log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType()); + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()); } + return artifactType; } private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) { ArtifactTypeConfig retConfig = null; String fileType = artifactType.getType(); - if (parentType.equals(NodeTypeEnum.Resource)) { + if (parentType == NodeTypeEnum.Resource) { retConfig = ConfigurationManager.getConfigurationManager() - .getConfiguration() - .getResourceDeploymentArtifacts() - .get(fileType); + .getConfiguration() + .getResourceDeploymentArtifacts() + .get(fileType); } - else if (parentType.equals(NodeTypeEnum.Service)) { + else if (parentType == NodeTypeEnum.Service) { retConfig = ConfigurationManager.getConfigurationManager() - .getConfiguration() - .getServiceDeploymentArtifacts() - .get(fileType); + .getConfiguration() + .getServiceDeploymentArtifacts() + .get(fileType); } - else if (parentType.equals(NodeTypeEnum.ResourceInstance)) { + else if (parentType == NodeTypeEnum.ResourceInstance) { retConfig = ConfigurationManager.getConfigurationManager() - .getConfiguration() - .getResourceInstanceDeploymentArtifacts() - .get(fileType); + .getConfiguration() + .getResourceInstanceDeploymentArtifacts() + .get(fileType); } return retConfig; } @@ -2254,9 +1869,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData())); Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo .getArtifactType()); - if (heatParameters.isRight() && (!heatParameters.right() - .value() - .equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) { + if (heatParameters.isRight() && (heatParameters.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND)) { log.info("failed to parse heat parameters "); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo .getArtifactType()); @@ -2270,82 +1883,63 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } - // Valid extension - public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) { - String fileType = artifactType.getType(); - List<String> acceptedTypes = null; - ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig(); - if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) { + @VisibleForTesting + public void validateFileExtension(IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) { + if (parentType != NodeTypeEnum.Resource && parentType != NodeTypeEnum.Service && parentType != NodeTypeEnum.ResourceInstance) { log.debug("parent type of artifact can be either resource or service"); - responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - return; + throw new ByActionStatusComponentException(MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactType.name(), "Service, Resource or ResourceInstance", parentType.getName()); } + String fileType = artifactType.getType(); + ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig(); if (deploymentAcceptedTypes == null) { - log.debug("parent type of artifact can be either resource or service"); - responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo - .getArtifactType())); - return; - } - else { - acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes(); + log.debug("invalid artifact type {}", fileType); + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, fileType); } /* * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted. */ + List<String> acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes(); String artifactName = artifactInfo.getArtifactName(); String fileExtension = GeneralUtility.getFilenameExtension(artifactName); // Pavel - File extension validation is case-insensitive - Ella, // 21/02/2016 - if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) { + if (CollectionUtils.isNotEmpty(acceptedTypes) && !acceptedTypes.contains(fileExtension.toLowerCase())) { log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType); - responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType)); - return; + throw new ByActionStatusComponentException(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType); } } - private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) { + @VisibleForTesting + void validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) { - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<>(); Wrapper<byte[]> payloadWrapper = new Wrapper<>(); - if (errorWrapper.isEmpty()) { - validateValidYaml(errorWrapper, artifactInfo); - } - - if (errorWrapper.isEmpty()) { - // Validate Heat Exist - validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent - .getComponentType()); - } + validateYaml(artifactInfo); + validateHeatExist(parentComponent.getUniqueId(), parentId, heatMDWrapper, artifactInfo, + parentType, parentComponent.getComponentType()); - if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) { - fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement()); + if (!heatMDWrapper.isEmpty()) { + fillArtifactPayload(payloadWrapper, heatMDWrapper.getInnerElement()); } - if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) { - validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement()); + if (!heatMDWrapper.isEmpty()) { + validateEnvVsHeat(artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement()); } - - // init Response - Either<Boolean, ResponseFormat> eitherResponse; - if (errorWrapper.isEmpty()) { - eitherResponse = Either.left(true); - } - else { - eitherResponse = Either.right(errorWrapper.getInnerElement()); - } - return eitherResponse; } - public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) { - if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) { - Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition); - if (fillArtifactPayload.isRight()) { - errorWrapper.setInnerElement(fillArtifactPayload.right().value()); + public void fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) { + if (ArrayUtils.isEmpty(artifactDefinition.getPayloadData())) { + Either<DAOArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactDefinition.getEsId()); + if (eitherArtifactData.isLeft()) { + byte[] data = eitherArtifactData.left().value().getDataAsArray(); + payloadWrapper.setInnerElement(Base64.encodeBase64(data)); + } + else { log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName()); + throw new StorageException(DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData.right().value())); } } else { @@ -2353,71 +1947,37 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } - public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) { - Either<Boolean, ResponseFormat> result = Either.left(true); - Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD - .getEsId()); - if (eitherArtifactData.isLeft()) { - byte[] data = eitherArtifactData.left().value().getDataAsArray(); - data = Base64.encodeBase64(data); - payloadWrapper.setInnerElement(data); - } - else { - StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData - .right() - .value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus)); - result = Either.right(responseFormat); - } - return result; - - } - - @SuppressWarnings("unchecked") - private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) { + private void validateEnvVsHeat(ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) { String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData())); Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload); String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData)); Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload); Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS); - Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS); if (eitherHeatEnvProperties.isRight()) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance() - .getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env"); - errorWrapper.setInnerElement(responseFormat); log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName()); + throw new ByActionStatusComponentException(ActionStatus.CORRUPTED_FORMAT, "Heat Env"); } - else if (eitherHeatProperties.isRight()) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance() - .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact - .getArtifactName(), heatArtifact.getArtifactName()); - errorWrapper.setInnerElement(responseFormat); - log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact - .getArtifactName()); + Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS); + if (eitherHeatProperties.isRight()) { + log.debug("Invalid heat format for file:{}", heatArtifact.getArtifactName()); + throw new ByActionStatusComponentException(ActionStatus.CORRUPTED_FORMAT, "Heat"); } - else { - Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet(); - Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet(); - heatEnvPropertiesKeys.removeAll(heatPropertiesKeys); - if (!heatEnvPropertiesKeys.isEmpty()) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance() - .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact - .getArtifactName(), heatArtifact.getArtifactName()); - errorWrapper.setInnerElement(responseFormat); - } + Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet(); + Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet(); + heatEnvPropertiesKeys.removeAll(heatPropertiesKeys); + if (!heatEnvPropertiesKeys.isEmpty()) { + log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact.getArtifactName()); + throw new ByActionStatusComponentException(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName()); } } - private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) { - YamlToObjectConverter yamlConvertor = new YamlToObjectConverter(); - boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData()); + private void validateYaml(ArtifactDefinition artifactInfo) { + YamlToObjectConverter yamlConverter = new YamlToObjectConverter(); + boolean isYamlValid = yamlConverter.isValidYamlEncoded64(artifactInfo.getPayloadData()); if (!isYamlValid) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance() - .getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo - .getArtifactType()); - errorWrapper.setInnerElement(responseFormat); log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName()); + throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML, artifactInfo.getArtifactType()); } } @@ -2445,7 +2005,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } - private void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) { + private void validateSingleDeploymentArtifactName(String artifactName, Component parentComponent, NodeTypeEnum parentType) { boolean artifactNameFound = false; Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null) .iterator(); @@ -2454,36 +2014,24 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { artifactNameFound = artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName()); } if (artifactNameFound) { - String parentName = parentComponent.getName(); - ResponseFormat responseFormat = ResponseFormatManager.getInstance() - .getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType - .name(), parentName, artifactName); - - errorWrapper.setInnerElement(responseFormat); log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName); - + throw new ByActionStatusComponentException(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType.name(), + parentComponent.getName(), artifactName); } } - private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType, + private void validateHeatExist(String componentId, String parentRiId, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType, ComponentTypeEnum componentType) { Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType); if (res.isRight()) { - ResponseFormat responseFormat; - if (res.right().value() == StorageOperationStatus.NOT_FOUND) { - responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT); - } - else { - responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT); - } - errorWrapper.setInnerElement(responseFormat); - return; + throw new ByActionStatusComponentException(ActionStatus.MISSING_HEAT); + } else { + heatArtifactMDWrapper.setInnerElement(res.left().value()); } - ArtifactDefinition heatArtifact = res.left().value(); - heatArtifactMDWrapper.setInnerElement(heatArtifact); } - private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) { + @VisibleForTesting + void validateHeatTimeoutValue(boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) { log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel()); // timeout > 0 for HEAT artifacts Integer timeout = artifactInfo.getTimeout(); @@ -2493,28 +2041,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { // HEAT artifact but timeout is invalid } else if (timeout < 1) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT)); + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_INVALID_TIMEOUT); } - // US649856 - Allow several HEAT files on Resource log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel()); - return Either.left(true); } - private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) { - String listToString = (typeList != null) ? typeList.toString() : ""; - ResponseFormat responseFormat = ResponseFormatManager.getInstance() - .getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo - .getArtifactName(), listToString, resourceType.getValue()); - Either<Boolean, ResponseFormat> either = Either.right(responseFormat); - String resourceTypeName = resourceType.name(); - if (typeList != null && typeList.contains(resourceTypeName)) { - either = Either.left(true); + @VisibleForTesting + void validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) { + if (typeList == null || !typeList.contains(resourceType.name())) { + String listToString = (typeList != null) ? typeList.toString() : ""; + throw new ByActionStatusComponentException(MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo.getArtifactName(), + listToString, resourceType.getValue()); } - return either; } - private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) { + @VisibleForTesting + Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParameters(ArtifactDefinition artifactInfo, String artifactType) { if (artifactInfo.getHeatParameters() != null) { for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) { String parameterType = heatParam.getType(); @@ -2642,9 +2185,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) { - if (Strings.isNullOrEmpty(artifactInfo.getArtifactType())) { + if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) { BeEcompErrorManager.getInstance() - .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel"); + .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel"); log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE)); } @@ -2653,7 +2196,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null; ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType(); - if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) { + if ((artifactGroupType != null) && artifactGroupType == ArtifactGroupTypeEnum.DEPLOYMENT) { allArtifactTypes = getDeploymentArtifactTypes(parentType); } else { @@ -2662,12 +2205,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } if (allArtifactTypes.isRight()) { BeEcompErrorManager.getInstance() - .logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes - .right() - .value() - .name()); + .logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes + .right() + .value() + .name()); log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right() - .value()); + .value()); return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId)); } @@ -2681,8 +2224,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (!artifactTypeExist) { BeEcompErrorManager.getInstance() - .logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo - .getArtifactType(), "Artifact " + artifactInfo.getArtifactName()); + .logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo + .getArtifactType(), "Artifact " + artifactInfo.getArtifactName()); log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo .getArtifactType())); @@ -2696,20 +2239,20 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { Map<String, ArtifactTypeConfig> deploymentArtifacts ; List<ArtifactType> artifactTypes = new ArrayList<>(); - if (parentType.equals(NodeTypeEnum.Service)) { + if (parentType == NodeTypeEnum.Service) { deploymentArtifacts = ConfigurationManager.getConfigurationManager() - .getConfiguration() - .getServiceDeploymentArtifacts(); + .getConfiguration() + .getServiceDeploymentArtifacts(); } - else if (parentType.equals(NodeTypeEnum.ResourceInstance)) { + else if (parentType == NodeTypeEnum.ResourceInstance) { deploymentArtifacts = ConfigurationManager.getConfigurationManager() - .getConfiguration() - .getResourceInstanceDeploymentArtifacts(); + .getConfiguration() + .getResourceInstanceDeploymentArtifacts(); } else { deploymentArtifacts = ConfigurationManager.getConfigurationManager() - .getConfiguration() - .getResourceDeploymentArtifacts(); + .getConfiguration() + .getResourceDeploymentArtifacts(); } if (deploymentArtifacts != null) { for (String artifactType : deploymentArtifacts.keySet()) { @@ -2733,11 +2276,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } - private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) { + @VisibleForTesting + Either<Boolean, ResponseFormat> validateAndSetArtifactName(ArtifactDefinition artifactInfo) { if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME)); } - String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName()); if (normalizeFileName == null || normalizeFileName.isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME)); @@ -2751,29 +2294,29 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.left(true); } - private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) { - if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) { + private void validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) { + if (StringUtils.isEmpty(artifactInfo.getArtifactType())) { log.info("artifact type is missing operation ignored"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE)); + throw new ByActionStatusComponentException(ActionStatus.MISSING_ARTIFACT_TYPE); } if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) { log.info("artifact type cannot be changed operation ignored"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); } - return Either.left(true); } private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) { - if (artifactInfo.getArtifactGroupType() == null) { - artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType()); - } - else if (!currentArtifact.getArtifactGroupType() - .getType() - .equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) { - log.info("artifact group type cannot be changed. operation failed"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + if (Objects.nonNull(artifactInfo) && Objects.nonNull(currentArtifact)) { + if (artifactInfo.getArtifactGroupType() == null) { + artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType()); + } else if (!currentArtifact.getArtifactGroupType() + .getType() + .equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) { + log.info("artifact group type cannot be changed. operation failed"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } } return Either.left(artifactInfo); } @@ -2791,56 +2334,56 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { artifactInfo.setUniqueId(currentArtifact.getUniqueId()); if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef() - .equals(artifactInfo.getArtifactRef())) { + .equals(artifactInfo.getArtifactRef())) { log.error("artifact ref cannot be set ignoring"); } artifactInfo.setArtifactRef(currentArtifact.getArtifactRef()); if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository() - .equals(artifactInfo.getArtifactRepository())) { + .equals(artifactInfo.getArtifactRepository())) { log.error("artifact repository cannot be set ignoring"); } artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository()); if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator() - .equals(artifactInfo.getUserIdCreator())) { + .equals(artifactInfo.getUserIdCreator())) { log.error("creator uuid cannot be set ignoring"); } artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator()); if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator() - .equals(artifactInfo.getArtifactCreator())) { + .equals(artifactInfo.getArtifactCreator())) { log.error("artifact creator cannot be set ignoring"); } artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator()); if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater() - .equals(artifactInfo.getUserIdLastUpdater())) { + .equals(artifactInfo.getUserIdLastUpdater())) { log.error("userId of last updater cannot be set ignoring"); } artifactInfo.setUserIdLastUpdater(user.getUserId()); if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName() - .equals(artifactInfo.getCreatorFullName())) { + .equals(artifactInfo.getCreatorFullName())) { log.error("creator Full name cannot be set ignoring"); } artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName()); if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName() - .equals(artifactInfo.getUpdaterFullName())) { + .equals(artifactInfo.getUpdaterFullName())) { log.error("updater Full name cannot be set ignoring"); } String fullName = user.getFirstName() + " " + user.getLastName(); artifactInfo.setUpdaterFullName(fullName); if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate() - .equals(artifactInfo.getCreationDate())) { + .equals(artifactInfo.getCreationDate())) { log.error("Creation Date cannot be set ignoring"); } artifactInfo.setCreationDate(currentArtifact.getCreationDate()); if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate() - .equals(artifactInfo.getLastUpdateDate())) { + .equals(artifactInfo.getLastUpdateDate())) { log.error("Last Update Date cannot be set ignoring"); } long time = System.currentTimeMillis(); @@ -2852,19 +2395,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { artifactInfo.setEsId(currentArtifact.getUniqueId()); if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName() - .equals(artifactInfo.getArtifactDisplayName())) { + .equals(artifactInfo.getArtifactDisplayName())) { log.error(" Artifact Display Name cannot be set ignoring"); } artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName()); if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi() - .equals(artifactInfo.getServiceApi())) { + .equals(artifactInfo.getServiceApi())) { log.debug("serviceApi cannot be set. ignoring."); } artifactInfo.setServiceApi(currentArtifact.getServiceApi()); - if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType() - .equals(artifactInfo.getArtifactGroupType())) { + if (artifactInfo.getArtifactGroupType() != null && currentArtifact.getArtifactGroupType() != artifactInfo.getArtifactGroupType()) { log.debug("artifact group cannot be set. ignoring."); } artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType()); @@ -2872,8 +2414,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion()); if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID() - .isEmpty() && !currentArtifact.getArtifactUUID() - .equals(artifactInfo.getArtifactUUID())) { + .isEmpty() && !currentArtifact.getArtifactUUID() + .equals(artifactInfo.getArtifactUUID())) { log.debug("artifact UUID cannot be set. ignoring."); } artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID()); @@ -2898,7 +2440,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { parameter.setName(currentParam.getName()); } if (parameter.getDefaultValue() != null && !parameter.getDefaultValue() - .equalsIgnoreCase(currentParam.getDefaultValue())) { + .equalsIgnoreCase(currentParam.getDefaultValue())) { log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue()); parameter.setDefaultValue(currentParam.getDefaultValue()); } @@ -2907,7 +2449,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { parameter.setType(currentParam.getType()); } if (parameter.getDescription() != null && !parameter.getDescription() - .equalsIgnoreCase(currentParam.getDescription())) { + .equalsIgnoreCase(currentParam.getDescription())) { log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription()); parameter.setDescription(currentParam.getDescription()); } @@ -2923,7 +2465,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) { - Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>(); + Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<>(); for (HeatParameterDefinition param : currentParameters) { currentParamsMap.put(param.getUniqueId(), param); } @@ -2968,136 +2510,75 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.left(true); } - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload, - ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationUuid) { - ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload); - String prevArtifactId = null; + private Either<ArtifactDefinition, Operation> updateArtifactFlow(Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, byte[] decodedPayload, + ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationName) { + 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; - - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; - Either<ArtifactDefinition, Operation> insideEither = null; - - log.trace("Try to update entry on graph"); - String artifactUniqueId = null; ArtifactDefinition artifactDefinition = artifactInfo; - StorageOperationStatus error; - - boolean isLeft; - if (interfaceType == null || operationUuid == null) { - log.debug("Entity on graph is updated. Update artifact in ES"); - boolean res = true; - // Changing previous and current artifactId for auditing - prevArtifactId = currArtifactId; - currArtifactId = artifactDefinition.getUniqueId(); - - - if (decodedPayload == null) { - if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) { - Either<ESArtifactData, 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 { - if (artifactDefinition.getEsId() == null) { - artifactDefinition.setEsId(artifactDefinition.getUniqueId()); - artifactData.setId(artifactDefinition.getUniqueId()); - } - } + 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(); - NodeTypeEnum convertParentType = convertParentType(componentType); - Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArtifactOnResource(artifactInfo, parent - .getUniqueId(), artifactId, convertParentType, parentId); - isLeft = result.isLeft(); - if (isLeft) { - artifactUniqueId = result.left().value().getUniqueId(); - artifactDefinition = result.left().value(); - String artifactType = artifactInfo.getArtifactType(); - if (NodeTypeEnum.Resource == convertParentType - && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) - || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) - || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType)) - && !artifactUniqueId.equals(artifactId)) { - // need to update the generated id in heat env - Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts(); - Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet() - .stream() - .filter(a -> a.getValue() - .getGeneratedFromId() != null && a - .getValue() - .getGeneratedFromId() - .equals(artifactId)) - .findFirst(); - if (findFirst.isPresent()) { - ArtifactDefinition artifactEnvInfo = findFirst.get().getValue(); - artifactEnvInfo.setArtifactChecksum(null); - artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId); - } - } - error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType); + NodeTypeEnum parentType = convertParentType(componentType); - insideEither = Either.left(result.left().value()); - resultOp = Either.left(insideEither); - if (error != StorageOperationStatus.OK) { - isLeft = false; + if (decodedPayload == null) { + if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) { + Either<DAOArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition.getEsId()); + if (artifactFromCassandra.isRight()) { + throw new StorageException(artifactFromCassandra.right().value()); } - - } else { - error = result.right().value(); + // clone data to new artifact + artifactData.setData(artifactFromCassandra.left().value().getData()); + artifactData.setId(artifactFromCassandra.left().value().getId()); } - if (isLeft) { - - // create new entry in ES - res = true; - if (artifactData.getData() != null) { - if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) { - artifactData.setId(artifactDefinition.getEsId()); - } - res = saveArtifacts(artifactData, parentId); + } else if (artifactDefinition.getEsId() == null) { + artifactDefinition.setEsId(artifactDefinition.getUniqueId()); + artifactData.setId(artifactDefinition.getUniqueId()); + } - } - } + Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArtifactOnResource(artifactInfo, + parent, artifactId, parentType, parentId, true); + if (result.isRight()) { + throw new StorageException(result.right().value()); + } + artifactDefinition = result.left().value(); + updateGeneratedIdInHeatEnv(parent, parentId, artifactId, artifactInfo, artifactDefinition, parentType); - if (res) { - log.debug(ARTIFACT_SAVED, artifactUniqueId); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); - } else { - BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT); - log.debug(FAILED_SAVE_ARTIFACT); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); + StorageOperationStatus storageOperationStatus = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType); + if (storageOperationStatus != StorageOperationStatus.OK) { + throw new StorageException(storageOperationStatus); + } + if (artifactData.getData() != null) { + if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) { + artifactData.setId(artifactDefinition.getEsId()); } - } else { - return updateArtifactsFlowForInterfaceOperations(parent, parentId, artifactId, artifactInfo, user, - decodedPayload, componentType, auditingAction, interfaceType, operationUuid, artifactData, prevArtifactId, - currArtifactId, artifactDefinition); + saveArtifactInCassandra(artifactData, parent, artifactInfo, currArtifactId, prevArtifactId, auditingAction, componentType); } - - return resultOp; + 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, ESArtifactData artifactData, String prevArtifactId, String currArtifactId, + 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<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition + Either<DAOArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition .getEsId()); if (artifactFromCassandra.isRight()) { log.debug("Failed to get artifact data from ES for artifact id {}", artifactId); @@ -3127,7 +2608,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { artifactInfo.setArtifactDisplayName(artifactInfo.getArtifactName()); Either<ArtifactDefinition, StorageOperationStatus> updateArtifactOnResourceEither = - artifactToscaOperation.updateArtifactOnResource(artifactInfo, parent.getUniqueId(), artifactId, convertParentType, parentId); + 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()); @@ -3151,6 +2632,45 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { 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); + } + return artifactDefinition.getUniqueId(); + } + + private String updateGeneratedIdInHeatEnv(Map<String, ArtifactDefinition> deploymentArtifacts, Component parentComponent, String parentId, String artifactId, ArtifactDefinition artifactInfo, ArtifactDefinition artifactDefinition, NodeTypeEnum parentType, boolean isInstanceArtifact) { + String artifactUniqueId; + artifactUniqueId = artifactDefinition.getUniqueId(); + String artifactType = artifactInfo.getArtifactType(); + if ((ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || + ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || + ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType)) + && !artifactUniqueId.equals(artifactId)) { + // need to update the generated id in heat env + Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet() + .stream() + .filter(a -> artifactId.equals(a.getValue().getGeneratedFromId())) + .findFirst(); + if (findFirst.isPresent()) { + ArtifactDefinition artifactEnvInfo = findFirst.get().getValue(); + artifactEnvInfo.setIsFromCsar(artifactDefinition.getIsFromCsar()); + artifactEnvInfo.setArtifactChecksum(null); + if (isInstanceArtifact) { + artifactToscaOperation.updateHeatEnvArtifactOnInstance(parentComponent, artifactEnvInfo, artifactId, artifactUniqueId, parentType, parentId); + } else { + artifactToscaOperation.updateHeatEnvArtifact(parentComponent, artifactEnvInfo, artifactId, artifactUniqueId, parentType, parentId); + } + } + } + return artifactUniqueId; + } + + private String updateGeneratedIdInHeatEnvOnInstance(ComponentInstance parent, Component parentComponent, String artifactId, ArtifactDefinition artifactInfo, ArtifactDefinition artifactDefinition, NodeTypeEnum parentType) { + return updateGeneratedIdInHeatEnv(parent.getDeploymentArtifacts(), parentComponent, parent.getUniqueId(),artifactId, artifactInfo, artifactDefinition, parentType, true); + } + + @VisibleForTesting private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) { log.trace("Starting payload handling"); byte[] payload = artifactInfo.getPayloadData(); @@ -3205,6 +2725,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.left(decodedPayload); } + public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String userUserId, String artifactId, boolean inTransaction) { User user = new User(); @@ -3248,43 +2769,35 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } // download by MSO - public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) { + public byte[] downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) { // General validation if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) { log.debug(NULL_PARAMETER); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); } // Normalizing artifact name artifactName = ValidationUtils.normalizeFileName(artifactName); // Resource validation - Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion); - if (validateResourceNameAndVersion.isRight()) { - return Either.right(validateResourceNameAndVersion.right().value()); - } - - Resource resource = validateResourceNameAndVersion.left().value(); + Resource resource = validateResourceNameAndVersion(resourceName, resourceVersion); String resourceId = resource.getUniqueId(); // Service validation - Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion); - if (validateServiceNameAndVersion.isRight()) { - return Either.right(validateServiceNameAndVersion.right().value()); - } + Service validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion); Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts(); if (artifacts == null || artifacts.isEmpty()) { log.debug("Deployment artifacts of resource {} are not found", resourceId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName)); + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactName); } ArtifactDefinition deploymentArtifact = null; for (ArtifactDefinition artifactDefinition : artifacts.values()) { if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName() - .equals(artifactName)) { + .equals(artifactName)) { log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName); deploymentArtifact = artifactDefinition; break; @@ -3293,100 +2806,91 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (deploymentArtifact == null) { log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName)); + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactName); } // Downloading the artifact - Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact); - if (downloadArtifactEither.isRight()) { - log.debug(FAILED_DOWNLOAD_ARTIFACT, artifactName); - return Either.right(downloadArtifactEither.right().value()); - } + ImmutablePair<String, byte[]> downloadArtifactEither = downloadArtifact(deploymentArtifact); log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId()); - return Either.left(downloadArtifactEither.left().value().getRight()); + return downloadArtifactEither.getRight(); } // download by MSO - public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) { + public byte[] downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) { // General validation if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) { log.debug(NULL_PARAMETER); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); } // Normalizing artifact name artifactName = ValidationUtils.normalizeFileName(artifactName); // Service validation - Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion); - if (validateServiceNameAndVersion.isRight()) { - return Either.right(validateServiceNameAndVersion.right().value()); - } - - Service service = validateServiceNameAndVersion.left().value(); + Service service = validateServiceNameAndVersion(serviceName, serviceVersion); // ResourceInstance validation - Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName); - if (validateResourceInstance.isRight()) { - return Either.right(validateResourceInstance.right().value()); - } - - ComponentInstance resourceInstance = validateResourceInstance.left().value(); + ComponentInstance resourceInstance = validateResourceInstance(service, resourceInstanceName); Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts(); final String finalArtifactName = artifactName; Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName); - boolean hasDeploymentArtifacts = artifacts != null && artifacts.values() - .stream() - .anyMatch(filterArtifactByName); - ArtifactDefinition deployableArtifact; + ArtifactDefinition deployableArtifact = artifacts==null ? null : + artifacts.values().stream() + .filter(filterArtifactByName) + .findFirst() + .orElse(null); - if (!hasDeploymentArtifacts) { + if (deployableArtifact == null) { log.debug("Deployment artifact with name {} not found", artifactName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName)); + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName)); } log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName); - deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get(); - // Downloading the artifact - Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact); + ImmutablePair<String, byte[]> downloadArtifactEither = downloadArtifact(deployableArtifact); - if (downloadArtifactEither.isRight()) { - log.debug(FAILED_DOWNLOAD_ARTIFACT, artifactName); - return Either.right(downloadArtifactEither.right().value()); - } log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId()); - return Either.left(downloadArtifactEither.left().value().getRight()); + return downloadArtifactEither.getRight(); } - private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) { + private ComponentInstance validateResourceInstance(Service service, String resourceInstanceName) { List<ComponentInstance> riList = service.getComponentInstances(); for (ComponentInstance ri : riList) { if (ri.getNormalizedName().equals(resourceInstanceName)) { - return Either.left(ri); + return ri; } } + throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName); + } - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName)); + private ComponentInstance validateResourceInstanceById(Component component, String resourceInstanceId) { + + List<ComponentInstance> riList = component.getComponentInstances(); + for (ComponentInstance ri : riList) { + if (ri.getUniqueId().equals(resourceInstanceId)) { + return ri; + } + } + throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, resourceInstanceId); } - private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) { + private Service validateServiceNameAndVersion(String serviceName, String serviceVersion) { Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName); if (serviceListBySystemName.isRight()) { log.debug("Couldn't fetch any service with name {}", serviceName); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceListBySystemName .right() - .value(), ComponentTypeEnum.SERVICE), serviceName)); + .value(), ComponentTypeEnum.SERVICE), serviceName); } List<Service> serviceList = serviceListBySystemName.left().value(); if (serviceList == null || serviceList.isEmpty()) { log.debug("Couldn't fetch any service with name {}", serviceName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName)); + throw new ByActionStatusComponentException(ActionStatus.SERVICE_NOT_FOUND, serviceName); } Service foundService = null; @@ -3400,13 +2904,25 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (foundService == null) { log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE - .getValue(), serviceVersion)); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE + .getValue(), serviceVersion); + } + return foundService; + } + + private Resource validateResourceNameAndVersion(String resourceName, String resourceVersion) { + + Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata); + if (resourceListBySystemName.isRight()) { + log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(resourceListBySystemName + .right() + .value()), resourceName); } - return Either.left(foundService); + return resourceListBySystemName.left().value(); } - private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) { + /*private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) { Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata); if (resourceListBySystemName.isRight()) { @@ -3416,81 +2932,71 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { .value()), resourceName)); } return Either.left(resourceListBySystemName.left().value()); - } + }*/ - public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) { + public byte[] downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) { // Validation log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName); if (serviceName == null || serviceVersion == null || artifactName == null) { log.debug(NULL_PARAMETER); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); } // Normalizing artifact name final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName); // Service validation - Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion); - if (validateServiceNameAndVersion.isRight()) { - return Either.right(validateServiceNameAndVersion.right().value()); - } - - String serviceId = validateServiceNameAndVersion.left().value().getUniqueId(); - + Service service = validateServiceNameAndVersion(serviceName, serviceVersion); // Looking for deployment or tosca artifacts - Service service = validateServiceNameAndVersion.left().value(); + String serviceId = service.getUniqueId(); if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) { log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName)); + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName); } - Optional<ArtifactDefinition> foundArtifactOptl = null; + Optional<ArtifactDefinition> foundArtifactOptl = Optional.empty(); if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) { foundArtifactOptl = service.getDeploymentArtifacts().values().stream() - // filters artifact by name - .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny(); + // filters artifact by name + .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny(); } - if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) { + if ((!foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) { foundArtifactOptl = service.getToscaArtifacts().values().stream() - // filters TOSCA artifact by name - .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny(); + // filters TOSCA artifact by name + .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny(); } if (!foundArtifactOptl.isPresent()) { log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName)); + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName); } log.debug(FOUND_DEPLOYMENT_ARTIFACT, normalizedArtifactName); // Downloading the artifact - Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl + ImmutablePair<String, byte[]> downloadArtifactEither = downloadArtifact(foundArtifactOptl .get()); - if (downloadArtifactEither.isRight()) { - log.debug(FAILED_DOWNLOAD_ARTIFACT, normalizedArtifactName); - return Either.right(downloadArtifactEither.right().value()); - } log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId()); - return Either.left(downloadArtifactEither.left().value().getRight()); + return downloadArtifactEither.getRight(); } - public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) { + public ImmutablePair<String, byte[]> downloadArtifact(String parentId, String artifactUniqueId) { log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId); Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId); if (artifactById.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value()); log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus); - return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, "")); + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByArtifactId(actionStatus, "")); } ArtifactDefinition artifactDefinition = artifactById.left().value(); if (artifactDefinition == null) { log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "")); + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "")); } return downloadArtifact(artifactDefinition); } - private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) { + private boolean checkArtifactInComponent(Component component, String artifactId) { boolean found = false; Map<String, ArtifactDefinition> artifactsS = component.getArtifacts(); if (artifactsS != null) { @@ -3535,7 +3041,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } } - switch (component.getComponentType()) { case RESOURCE: break; @@ -3593,41 +3098,41 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return found; } - private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType, - String containerComponentType) { + private Component validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType, + String containerComponentType) { ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType); componentForAudit.getNodeType(); - Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade + Either<? extends Component, StorageOperationStatus> componentResult = toscaOperationFacade .getToscaFullElement(componentId); if (componentResult.isRight()) { - ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND; + ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentForAudit == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND; ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId); log.debug("Service not found, serviceId {}", componentId); handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null); - return Either.right(responseFormat); + throw new ByActionStatusComponentException(status, componentId); } - return Either.left(componentResult.left().value()); + return componentResult.left().value(); } - private Either<Boolean, ResponseFormat> validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation) { + private Boolean validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation) { if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD && !operation.ignoreLifecycleState()) { - Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId); - if (canWork.isRight()) { + try { + validateCanWorkOnComponent(component, userId); + }catch (ComponentException e) { String uniqueId = component.getUniqueId(); log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId); - handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right() - .value(), component - .getComponentType(), null); - return Either.right(canWork.right().value()); + handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, e.getResponseFormat(), + component.getComponentType(), null); + throw e; } } - return Either.left(true); + return true; } - private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) { + private void validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) { if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD) { String role = user.getRole(); @@ -3635,16 +3140,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role); handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); + throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION); } } - return Either.left(true); } - private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) { + private User validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) { User user; try{ - user = validateUserExists(userId, auditingAction.getName(), inTransaction); + user = validateUserExists(userId); } catch(ByResponseFormatComponentException e){ ResponseFormat responseFormat = e.getResponseFormat(); handleComponentException(auditingAction, componentId, artifactId, responseFormat, componentType, userId); @@ -3654,7 +3158,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { handleComponentException(auditingAction, componentId, artifactId, responseFormat, componentType, userId); throw e; } - return Either.left(user); + return user; } private void handleComponentException(AuditingActionEnum auditingAction, String componentId, String artifactId, @@ -3685,75 +3189,62 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return auditingAction; } - private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) { + private ImmutablePair<String, byte[]> downloadArtifact(ArtifactDefinition artifactDefinition) { String esArtifactId = artifactDefinition.getEsId(); - Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId); + Either<DAOArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId); if (artifactfromES.isRight()) { CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value(); StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus); ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse); log.debug("Error when getting artifact from ES, error: {}", actionStatus); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition - .getArtifactDisplayName()); - - return Either.right(responseFormat); + throw new ByActionStatusComponentException(actionStatus, artifactDefinition.getArtifactDisplayName()); } - ESArtifactData esArtifactData = artifactfromES.left().value(); - byte[] data = esArtifactData.getDataAsArray(); + DAOArtifactData DAOArtifactData = artifactfromES.left().value(); + byte[] data = DAOArtifactData.getDataAsArray(); if (data == null) { - log.debug("Artifact data from ES is null"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName())); + log.debug("Artifact data from cassandra is null"); + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()); } String artifactName = artifactDefinition.getArtifactName(); log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName); - return Either.left(new ImmutablePair<String, byte[]>(artifactName, data)); + return new ImmutablePair<>(artifactName, data); } - public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) { - return new ESArtifactData(artifactInfo.getEsId(), artifactPayload); + public DAOArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) { + return new DAOArtifactData(artifactInfo.getEsId(), artifactPayload); } - private boolean saveArtifacts(ESArtifactData artifactData, String resourceId) { + private void saveArtifactInCassandra(DAOArtifactData artifactData, Component parent, ArtifactDefinition artifactInfo, + String currArtifactId, String prevArtifactId, AuditingActionEnum auditingAction, ComponentTypeEnum componentType) { CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData); - if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) { - log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId); + if (resourceUploadStatus == CassandraOperationStatus.OK) { + log.debug("Artifact {} was saved in component {}.", artifactData.getId(), parent.getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleAuditing(auditingAction, parent, parent.getUniqueId(), null, artifactInfo, prevArtifactId, + currArtifactId, responseFormat, componentType, null); } else { - log.info("Failed to save artifact {}.", artifactData.getId()); - return false; + BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT); + log.info(FAILED_SAVE_ARTIFACT); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleAuditing(auditingAction, parent, parent.getUniqueId(), null, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); + throw new StorageException(resourceUploadStatus); } - return true; } private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) { - return auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE); + return auditingActionEnum == AuditingActionEnum.ARTIFACT_METADATA_UPDATE; } private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) { - return ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType()); + return ArtifactGroupTypeEnum.DEPLOYMENT == artifactInfo.getArtifactGroupType(); } - public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) { - Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction); - if (user.isRight()) { - ResponseFormat responseFormat; - if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) { - log.debug("create artifact placeholder - not authorized user, userId {}", userUserId); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - } - else { - log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId); - responseFormat = componentsUtils.getResponseFormat(user.right().value()); - } - return Either.right(responseFormat); - } - - ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user - .left() - .value(), groupType); - return Either.left(artifactDefinition); + public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) { + User user = userBusinessLogic.getUser(userUserId, inTransaction); + return createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user, groupType); } public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) { @@ -3780,7 +3271,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (resourceId != null) { uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel() - .toLowerCase()); + .toLowerCase()); artifactInfo.setUniqueId(uniqueId); } artifactInfo.setUserIdCreator(user.getUserId()); @@ -3802,15 +3293,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId); } - public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) { - return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId); + public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, Component component, NodeTypeEnum parentType, String instanceId) { + return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, component, parentType, true, instanceId); } - private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) { + private Either<DAOArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) { byte[] payload = payloadStr.getBytes(); - ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload); + DAOArtifactData artifactData = createEsArtifactData(artifactDefinition, payload); return Either.left(artifactData); } @@ -3818,34 +3309,35 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param artifactDefinition * @return */ - public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, + public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, Component component, String resourceInstanceName, User modifier, String instanceId, boolean shouldLock, boolean inTransaction) { String payload = generateHeatEnvPayload(artifactDefinition); String prevUUID = artifactDefinition.getArtifactUUID(); ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition); return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction) .left() - .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef)); + .bind(artifactDef -> updateArtifactOnGroupInstance(component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef)); } - public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, + public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, Component component, String resourceInstanceName, User modifier, boolean shouldLock, boolean inTransaction, String instanceId) { String payload = generateHeatEnvPayload(artifactDefinition); String prevUUID = artifactDefinition.getArtifactUUID(); ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition); return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction) .left() - .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef)); + .bind(artifactDef -> updateArtifactOnGroupInstance(component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef)); } - private Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(ComponentTypeEnum componentType, Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) { + @VisibleForTesting + Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) { if (prevUUID == null || !prevUUID.equals(updatedArtDef.getArtifactUUID())) { List<ComponentInstance> componentInstances = component.getComponentInstances(); if (componentInstances != null) { Optional<ComponentInstance> findFirst = componentInstances.stream() - .filter(ci -> ci.getUniqueId() - .equals(instanceId)) - .findFirst(); + .filter(ci -> ci.getUniqueId() + .equals(instanceId)) + .findFirst(); if (findFirst.isPresent()) { ComponentInstance relevantInst = findFirst.get(); List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst @@ -3861,7 +3353,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { log.debug(FAILED_UPDATE_GROUPS, component.getUniqueId()); ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils .convertFromStorageResponse(status.right() - .value()), clonedBeforeGenerate.getArtifactDisplayName()); + .value()), clonedBeforeGenerate.getArtifactDisplayName()); return Either.right(responseFormat); } } @@ -3877,7 +3369,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader()); sb.append("parameters:\n"); if (heatParameters != null) { - heatParameters.sort(Comparator.comparing(e -> e.getName())); + heatParameters.sort(Comparator.comparing(HeatParameterDataDefinition::getName)); List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>(); @@ -3896,28 +3388,28 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { switch (type) { case BOOLEAN: sb.append(" ") - .append(heatParameterDefinition.getName()) - .append(":") - .append(" ") - .append(Boolean.parseBoolean(heatValue)) - .append("\n"); + .append(heatParameterDefinition.getName()) + .append(":") + .append(" ") + .append(Boolean.parseBoolean(heatValue)) + .append("\n"); break; case NUMBER: sb.append(" ") - .append(heatParameterDefinition.getName()) - .append(":") - .append(" ") - .append(new BigDecimal(heatValue).toPlainString()) - .append("\n"); + .append(heatParameterDefinition.getName()) + .append(":") + .append(" ") + .append(new BigDecimal(heatValue).toPlainString()) + .append("\n"); break; case COMMA_DELIMITED_LIST: case JSON: sb.append(" ") - .append(heatParameterDefinition.getName()) - .append(":") - .append(" ") - .append(heatValue) - .append("\n"); + .append(heatParameterDefinition.getName()) + .append(":") + .append(" ") + .append(heatValue) + .append("\n"); break; default: String value = heatValue; @@ -3931,10 +3423,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } sb.append(" ") - .append(heatParameterDefinition.getName()) - .append(":") - .append(" ") - .append(value); + .append(heatParameterDefinition.getName()) + .append(":") + .append(" ") + .append(value); sb.append("\n"); break; @@ -3942,7 +3434,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } if (!empltyHeatValues.isEmpty()) { - empltyHeatValues.sort(Comparator.comparing(e -> e.getName())); + empltyHeatValues.sort(Comparator.comparing(HeatParameterDataDefinition::getName)); empltyHeatValues.forEach(hv -> { sb.append(" ").append(hv.getName()).append(":"); HeatParameterType type = HeatParameterType.isValidType(hv.getType()); @@ -3967,23 +3459,22 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param payload * @return */ - public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, + public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, Component component, String resourceInstanceName, User modifier, String instanceId, boolean shouldLock, boolean inTransaction) { - return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, () -> artifactDefinition - .getHeatParamsUpdateDate(), + return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, artifactDefinition::getHeatParamsUpdateDate, () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId); } - public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, + public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, Component component, String resourceInstanceName, User modifier, String instanceId, boolean shouldLock, boolean inTransaction) { return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, System::currentTimeMillis, () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId); } - protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, - boolean shouldLock, boolean inTransaction, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) { + protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, Component component, String resourceInstanceName, User modifier, + boolean shouldLock, boolean inTransaction, Supplier<Long> payloadUpdateDateGen, Supplier<Either<DAOArtifactData, ResponseFormat>> esDataCreator, String instanceId) { log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition .getEsId()); @@ -3991,8 +3482,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { .getPayloadUpdateDate() <= payloadUpdateDateGen.get()) { log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId()); - Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get(); - ESArtifactData artifactData = null; + Either<DAOArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get(); + DAOArtifactData artifactData = null; if (artifactDataRes.isLeft()) { artifactData = artifactDataRes.left().value(); @@ -4008,8 +3499,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray()); String oldCheckSum; String esArtifactId = artifactDefinition.getEsId(); - Either<ESArtifactData, CassandraOperationStatus> artifactfromES; - ESArtifactData esArtifactData; + Either<DAOArtifactData, CassandraOperationStatus> artifactfromES; + DAOArtifactData DAOArtifactData; if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) { log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId); artifactfromES = artifactCassandraDao.getArtifact(esArtifactId); @@ -4020,8 +3511,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus, esArtifactId); return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName())); } - esArtifactData = artifactfromES.left().value(); - oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray()); + DAOArtifactData = artifactfromES.left().value(); + oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(DAOArtifactData.getDataAsArray()); } else { oldCheckSum = artifactDefinition.getArtifactChecksum(); @@ -4030,11 +3521,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null; if (shouldLock) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: "); - if (lockComponent.isRight()) { + try { + lockComponent(component, "Update Artifact - lock resource: "); + }catch (ComponentException e){ handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition - .getUniqueId(), lockComponent.right().value(), component.getComponentType(), null); - return Either.right(lockComponent.right().value()); + .getUniqueId(), e.getResponseFormat(), component.getComponentType(), null); + throw e; } } try { @@ -4042,7 +3534,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get()); updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component - .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId); + ,artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId, true); log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition .getArtifactType(), artifactDefinition.getEsId()); if (updateArifactDefinitionStatus.isRight()) { @@ -4058,28 +3550,27 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } else { - - oldCheckSum = artifactDefinition.getArtifactChecksum(); + artifactDefinition.getArtifactChecksum(); artifactDefinition.setArtifactChecksum(newCheckSum); artifactDefinition.setEsId(artifactDefinition.getUniqueId()); log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition .getArtifactType(), artifactDefinition.getEsId()); - updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component - .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId); + updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component, + artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId, true); - log.trace("Update Payload ", artifactDefinition.getEsId()); + log.trace("Update Payload {}", artifactDefinition.getEsId()); } - if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) { + if (updateArifactDefinitionStatus.isLeft()) { artifactDefinition = updateArifactDefinitionStatus.left().value(); artifactData.setId(artifactDefinition.getUniqueId()); CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData); - if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) { + if (saveArtifactStatus == CassandraOperationStatus.OK) { if (!inTransaction) { janusGraphDao.commit(); } - log.debug("Artifact Saved In ES {}", artifactData.getId()); + log.debug("Artifact Saved In cassandra {}", artifactData.getId()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, @@ -4115,7 +3606,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { finally { if (shouldLock) { graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType() - .getNodeType()); + .getNodeType()); } } } @@ -4153,259 +3644,208 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType()); json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>() : updatedRequiredArtifacts.stream() - .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e - .getType() - .equals(ArtifactTypeEnum.HEAT_NESTED.getType())) - .map(e -> e.getFileName()) - .collect(Collectors.toList())); + .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e + .getType() + .equals(ArtifactTypeEnum.HEAT_NESTED.getType())) + .map(ArtifactTemplateInfo::getFileName) + .collect(Collectors.toList())); json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>() : heatParameters); return json; } - public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map<String, Object> json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) { + public Either<ArtifactDefinition, Operation> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map<String, Object> json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) { String jsonStr = gson.toJson(json); - ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class) : artifactInfo; + ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class, false) : artifactInfo; String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId(); - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId, + Either<ArtifactDefinition, Operation> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId, artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true); - if (uploadArtifactToService.isRight()) { - return Either.right(uploadArtifactToService.right().value()); - } return Either.left(uploadArtifactToService.left().value()); } - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType, - org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) { - convertParentType(componentType); - String parentId = parent.getUniqueId(); - ArtifactDefinition currArtifact = artifactInfo; - + private Either<ArtifactDefinition, Operation> handleUpdateHeatEnvAndHeatMeta(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType, + Component parent, String originData, String origMd5, ArtifactOperationInfo operation) { if (origMd5 != null) { - Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); - if (validateMd5.isRight()) { - ResponseFormat responseFormat = validateMd5.right().value(); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - - if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) { - Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance); - if (deploymentValidationResult.isRight()) { - ResponseFormat responseFormat = deploymentValidationResult.right().value(); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - - Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction)); - if (payloadEither.isRight()) { - ResponseFormat responseFormat = payloadEither.right().value(); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - } - else { // duplicate - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); + validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); + if (ArrayUtils.isNotEmpty(artifactInfo.getPayloadData())) { + validateDeploymentArtifact(parent, componentId, false, artifactInfo, artifactInfo, NodeTypeEnum.ResourceInstance); + handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction)); + } else { // duplicate + throw new ByActionStatusComponentException(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD); } } - - // lock resource - if (shouldLock) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK); - if (lockComponent.isRight()) { - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right() - .value(), componentType, null); - return Either.right(lockComponent.right().value()); - } - } - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; - try { - resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5); - return resultOp; - - } - finally { - // unlock resource - if (resultOp == null || resultOp.isRight()) { - log.debug(ROLLBACK); - if (!inTransaction) { - janusGraphDao.rollback(); - } - } - else { - log.debug(COMMIT); - if (!inTransaction) { - janusGraphDao.commit(); - } - } - if (shouldLock) { - componentType = parent.getComponentType(); - } - NodeTypeEnum nodeType = componentType.getNodeType(); - graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType); - } + return updateHeatEnvParamsAndMetadata(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5); } - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent, - ComponentTypeEnum componentType, String origMd5) { - - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; - Either<ArtifactDefinition, Operation> insideEither = null; + private Either<ArtifactDefinition, Operation> updateHeatEnvParamsAndMetadata(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent, + ComponentTypeEnum componentType, String origMd5) { Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user); if (getRI.isRight()) { - return Either.right(getRI.right().value()); + throw new ByResponseFormatComponentException(getRI.right().value()); } ComponentInstance ri = getRI.left().value(); Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user); if (getArtifactRes.isRight()) { - return Either.right(getArtifactRes.right().value()); + throw new ByResponseFormatComponentException(getArtifactRes.right().value()); } ArtifactDefinition currArtifact = getArtifactRes.left().value(); - if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType() - .equals(ArtifactTypeEnum.HEAT_VOL - .getType()) || currArtifact - .getArtifactType() - .equals(ArtifactTypeEnum.HEAT_NET.getType())) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri - .getName()); - return Either.right(responseFormat); + if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || + currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType()) || + currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType())) { + throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION); } List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters(); List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters(); - new ArrayList<HeatParameterDefinition>(); // upload if (origMd5 != null) { - Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri - .getName(), currentHeatEnvParams, - updatedHeatEnvParams, currArtifact.getArtifactName()); + Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, + artifactId, componentType, ri.getName(), currentHeatEnvParams, updatedHeatEnvParams, currArtifact.getArtifactName()); if (uploadParamsValidationResult.isRight()) { - ResponseFormat responseFormat = uploadParamsValidationResult.right().value(); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri - .getName()); - return Either.right(responseFormat); + throw new ByResponseFormatComponentException(uploadParamsValidationResult.right().value()); } artifactInfo.setListHeatParameters(updatedHeatEnvParams); } - Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV - .getType()); + Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParameters(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType()); if (validateAndConvertHeatParamers.isRight()) { - ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value(); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri - .getName()); - return Either.right(responseFormat); + throw new ByResponseFormatComponentException(validateAndConvertHeatParamers.right().value()); } if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) { // fill reduced heat env parameters List for updating - replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams); - currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis()); - currArtifact.setListHeatParameters(currentHeatEnvParams); - - Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArtifactOnResource(currArtifact, parent - .getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId); - if (updateArifactRes.isRight()) { - log.debug("Failed to update artifact on graph - {}", artifactId); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes - .right() - .value())); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri - .getName()); - return Either.right(responseFormat); - } - StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType); - if (error != StorageOperationStatus.OK) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error)); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri - .getName()); - return Either.right(responseFormat); + boolean updateRequired = replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams); + if (updateRequired) { + currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis()); + currArtifact.setListHeatParameters(currentHeatEnvParams); + Either<ArtifactDefinition, StorageOperationStatus> updateArtifactRes = artifactToscaOperation.updateArtifactOnResource( + currArtifact, parent, currArtifact.getUniqueId(), componentType.getNodeType(), componentId, true); + if (updateArtifactRes.isRight()) { + log.debug("Failed to update artifact on graph - {}", artifactId); + throw new StorageException(updateArtifactRes.right().value()); + } + StorageOperationStatus error = generateCustomizationUUIDOnGroupInstance(ri, updateArtifactRes.left().value().getUniqueId(), parent.getUniqueId()); + if (error != StorageOperationStatus.OK) { + throw new StorageException(error); + } } + } + updateHeatMetaDataIfNeeded(componentId,user,auditingAction,componentType, parent,ri,artifactInfo); + StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType); + if (error != StorageOperationStatus.OK) { + throw new StorageException(error); + } - error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left() - .value() - .getUniqueId(), parent.getUniqueId()); + return Either.left(currArtifact); + } + + private void + updateHeatMetaDataIfNeeded(String componentId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent, ComponentInstance resourceInstance, ArtifactDefinition updatedHeatEnvArtifact) { + String heatArtifactId = updatedHeatEnvArtifact.getGeneratedFromId(); + Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, resourceInstance, componentId, heatArtifactId, auditingAction, user); + if (getArtifactRes.isRight()) { + throw new ByResponseFormatComponentException(getArtifactRes.right().value()); + } + ArtifactDefinition heatArtifactToUpdate = getArtifactRes.left().value(); + if (isUpdateHeatMetaDataNeeded(updatedHeatEnvArtifact, heatArtifactToUpdate)) { + validateHeatMetaData(updatedHeatEnvArtifact); + updateHeatMetadataFromHeatEnv(updatedHeatEnvArtifact, heatArtifactToUpdate); + Either<ArtifactDefinition, StorageOperationStatus> updateArtifactRes = artifactToscaOperation.updateArtifactOnResource(heatArtifactToUpdate, parent, + heatArtifactToUpdate.getUniqueId(), componentType.getNodeType(), componentId, false); + + if (updateArtifactRes.isRight()) { + log.debug("Failed to update artifact on graph - {}", heatArtifactId); + throw new StorageException(updateArtifactRes.right().value()); + } + ArtifactDefinition artifactDefinition = updateArtifactRes.left().value(); + updateGeneratedIdInHeatEnvOnInstance(resourceInstance, parent, heatArtifactId, heatArtifactToUpdate, artifactDefinition, componentType.getNodeType()); + StorageOperationStatus error = generateCustomizationUUIDOnGroupInstance(resourceInstance, artifactDefinition.getUniqueId(), parent.getUniqueId()); if (error != StorageOperationStatus.OK) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error)); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri - .getName()); - return Either.right(responseFormat); + throw new StorageException(error); } + } + } + private void validateHeatMetaData(ArtifactDefinition updatedHeatEnv) { + Integer maxMinutes = ConfigurationManager.getConfigurationManager().getConfiguration().getHeatArtifactDeploymentTimeout().getMaxMinutes(); + Integer minMinutes = ConfigurationManager.getConfigurationManager().getConfiguration().getHeatArtifactDeploymentTimeout().getMinMinutes(); + Integer updateTimeout = updatedHeatEnv.getTimeout(); + if (updateTimeout > maxMinutes || updateTimeout < minMinutes) { + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_INVALID_TIMEOUT); } - insideEither = Either.left(currArtifact); - resultOp = Either.left(insideEither); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri - .getName()); - return resultOp; } - private void replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) { + private boolean isUpdateHeatMetaDataNeeded(ArtifactDefinition updatedHeatEnv, ArtifactDefinition origHeat) { + // currently only timeout metadata can be updated + return !origHeat.getTimeout().equals(updatedHeatEnv.getTimeout()); + } + + private void updateHeatMetadataFromHeatEnv(ArtifactDefinition updatedHeatEnv, ArtifactDefinition origHeat) { + // currently only timeout metadata can be updated + origHeat.setTimeout(updatedHeatEnv.getTimeout()); + } + + private boolean replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) { + boolean isUpdate = false; + List<String> currentParamsNames = currentHeatEnvParams.stream().map(x -> x.getName()).collect(Collectors.toList()); for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) { String paramName = heatEnvParam.getName(); + validateParamName(paramName, currentParamsNames); for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { if (paramName.equalsIgnoreCase(currHeatParam.getName())) { String updatedParamValue = heatEnvParam.getCurrentValue(); - currHeatParam.setCurrentValue(updatedParamValue); + if (!Objects.equals(updatedParamValue, currHeatParam.getCurrentValue())) { + currHeatParam.setCurrentValue(updatedParamValue); + isUpdate = true; + } } } } + return isUpdate; } - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent, - ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, boolean needToUpdateGroup) { + private void validateParamName(String paramName, List<String> heatParamsNames) { + if (!heatParamsNames.contains(paramName)) { + throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, paramName); + } + } - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp; + private Either<ArtifactDefinition, Operation> updateHeatParams(String componentId, ArtifactDefinition artifactEnvInfo, AuditingActionEnum auditingAction, Component parent, + ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, boolean needToUpdateGroup) { Either<ArtifactDefinition, Operation> insideEither = null; String currentHeatId = currHeatArtifact.getUniqueId(); String esArtifactId = currHeatArtifact.getEsId(); - Either<ESArtifactData, CassandraOperationStatus> artifactFromES = artifactCassandraDao.getArtifact(esArtifactId); + Either<DAOArtifactData, CassandraOperationStatus> artifactFromES = artifactCassandraDao.getArtifact(esArtifactId); if (artifactFromES.isRight()) { - CassandraOperationStatus resourceUploadStatus = artifactFromES.right().value(); - StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse); - log.debug("Error when getting artifact from ES, error: {}", actionStatus); - return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName())); + StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromES.right().value()); + throw new StorageException(storageResponse, currHeatArtifact.getArtifactDisplayName()); } - ESArtifactData esArtifactData = artifactFromES.left().value(); - + DAOArtifactData DAOArtifactData = artifactFromES.left().value(); ArtifactDefinition updatedHeatArt = currHeatArtifact; - List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters(); List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters(); - List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>(); - - if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams - .isEmpty()) { + List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<>(); + if (CollectionUtils.isNotEmpty(updatedHeatEnvParams) && CollectionUtils.isNotEmpty(currentHeatEnvParams)) { + //TODO: improve complexity - currently N^2 String paramName; for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) { - paramName = heatEnvParam.getName(); for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { if (paramName.equalsIgnoreCase(currHeatParam.getName())) { - String updatedParamValue = heatEnvParam.getCurrentValue(); if (updatedParamValue == null) { updatedParamValue = heatEnvParam.getDefaultValue(); } HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType()); if (!paramType.getValidator().isValid(updatedParamValue, null)) { - ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE; - ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV - .getType(), paramType.getType(), paramName); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, ""); - return Either.right(responseFormat); - + throw new ByActionStatusComponentException(ActionStatus.INVALID_HEAT_PARAMETER_VALUE, + ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName); } currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null)); newHeatEnvParams.add(currHeatParam); @@ -4415,78 +3855,45 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } if (!newHeatEnvParams.isEmpty()) { currHeatArtifact.setListHeatParameters(currentHeatEnvParams); - Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArtifactOnResource(currHeatArtifact, parent - .getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId); + Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArtifactOnResource( + currHeatArtifact, parent, currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId, true); if (operationStatus.isRight()) { log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId()); - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus - .right() - .value())); - return Either.right(responseFormat); - + throw new StorageException(operationStatus.right().value()); } updatedHeatArt = operationStatus.left().value(); - boolean res = true; - if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null) { - esArtifactData.setId(updatedHeatArt.getEsId()); + if (!updatedHeatArt.getDuplicated() || DAOArtifactData.getId() == null) { + DAOArtifactData.setId(updatedHeatArt.getEsId()); } - res = saveArtifacts(esArtifactData, parent.getUniqueId()); - - if (res) { - log.debug(ARTIFACT_SAVED, updatedHeatArt.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt - .getUniqueId(), responseFormat, componentType, null); - } - else { - BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT); - log.debug(FAILED_SAVE_ARTIFACT); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt - .getUniqueId(), responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } - + saveArtifactInCassandra(DAOArtifactData, parent, artifactEnvInfo, currentHeatId, updatedHeatArt + .getUniqueId(), auditingAction, componentType); insideEither = Either.left(updatedHeatArt); } } Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact; if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) { artifactEnvInfo.setArtifactChecksum(null); - updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt + updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent, artifactEnvInfo, currentHeatId, updatedHeatArt .getUniqueId(), componentType.getNodeType(), componentId); } else { - updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType + //TODO Andrey check if componentId = parent.getUniqeId + updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, parent, componentType .getNodeType()); } if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) { - ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact - .left() - .value(), parent, componentType); + ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, + updateHeatEnvArtifact.left().value(), parent); if (result != ActionStatus.OK) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(result); - return Either.right(responseFormat); + throw new ByActionStatusComponentException(result); } } - if (updatedHeatEnvParams.isEmpty()) { - return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, user, currHeatArtifact, artifactId, componentType); + throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName()); } - resultOp = Either.left(insideEither); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, ""); - return resultOp; - - } - - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName()); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, ""); - return Either.right(responseFormat); + return insideEither; } @@ -4497,10 +3904,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { List<String> groupInstancesId = null; if (groupsInstances != null && !groupsInstances.isEmpty()) { groupInstancesId = groupsInstances.stream() - .filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts() - .contains(artifactId)) - .map(GroupInstanceDataDefinition::getUniqueId) - .collect(Collectors.toList()); + .filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts() + .contains(artifactId)) + .map(GroupInstanceDataDefinition::getUniqueId) + .collect(Collectors.toList()); } if (groupInstancesId != null && !groupInstancesId.isEmpty()) { toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId); @@ -4581,31 +3988,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return ret; } - /** - * downloads artifact of component by UUIDs - * - * @param componentType - * @param componentUuid - * @param artifactUUID - * @param resourceCommonInfo - * @return - */ - public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo) { - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Either<byte[], ResponseFormat> result; - byte[] downloadedArtifact = null; - Component component = getComponentByUuid(componentType, componentUuid, errorWrapper); - if (errorWrapper.isEmpty() && component != null) { - resourceCommonInfo.setResourceName(component.getName()); - downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName()); - } - if (errorWrapper.isEmpty()) { - result = Either.left(downloadedArtifact); - } - else { - result = Either.right(errorWrapper.getInnerElement()); - } - return result; + public byte[] downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo) { + Component component = getComponentByUuid(componentType, componentUuid); + resourceCommonInfo.setResourceName(component.getName()); + return downloadArtifact(component.getAllArtifacts(), artifactUUID, component.getName()); } /** @@ -4617,22 +4003,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param artifactUUID * @return */ - public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID) { - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Either<byte[], ResponseFormat> result; - byte[] downloadedArtifact = null; - ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper); - if (errorWrapper.isEmpty()) { - downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance - .getName()); - } - if (errorWrapper.isEmpty()) { - result = Either.left(downloadedArtifact); - } - else { - result = Either.right(errorWrapper.getInnerElement()); - } - return result; + 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()); } /** @@ -4646,50 +4021,43 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param operation * @return */ - public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) { - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null; - Component component = null; - String componentId = null; - ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); + public ArtifactDefinition uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, + String componentUuid, ResourceCommonInfo resourceCommonInfo, ArtifactOperationInfo operation) { + Either<ArtifactDefinition, Operation> actionResult; + Component component; + String componentId; + ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class, false); 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); + 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, componentType), componentUuid)); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid); } - if (errorWrapper.isEmpty()) { - componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); - String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName(); - if (!getComponentRes.left() - .value() - .getMetadataDataDefinition() - .getState() - .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - component = checkoutParentComponent(componentType, componentId, userId, errorWrapper); - if (component != null) { - componentId = component.getUniqueId(); - componentName = component.getName(); - } - } - resourceCommonInfo.setResourceName(componentName); - } - if (errorWrapper.isEmpty()) { - actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null); - if (actionResult.isRight()) { - log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult - .right() - .value()); - return Either.right(actionResult.right().value()); + ComponentMetadataDataDefinition componentMetadataDataDefinition = getComponentRes.left().value().getMetadataDataDefinition(); + componentId = componentMetadataDataDefinition.getUniqueId(); + String componentName = componentMetadataDataDefinition.getName(); + + if (!componentMetadataDataDefinition + .getState() + .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + component = checkoutParentComponent(componentType, componentId, userId); + if (component != null) { + componentId = component.getUniqueId(); + componentName = component.getName(); } - return Either.left(actionResult.left().value().left().value()); } - return Either.right(errorWrapper.getInnerElement()); + resourceCommonInfo.setResourceName(componentName); + + actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, + origMd5, data, null, null, null, null); + return actionResult.left().value(); } + /** * upload an artifact to a resource instance by UUID * @@ -4701,12 +4069,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param operation * @return */ - public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, - ArtifactOperationInfo operation) { - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult; - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null; - ArtifactDefinition uploadArtifact = null; + public ArtifactDefinition uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, + ArtifactOperationInfo operation) { + Either<ArtifactDefinition, Operation> actionResult; Component component = null; String componentInstanceId; String componentId; @@ -4717,49 +4082,34 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); - log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName)); + log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName); } - if (errorWrapper.isEmpty() && !getComponentRes.left() - .value() - .getMetadataDataDefinition() - .getState() - .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + if (!getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getState() + .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { component = checkoutParentComponent(componentType, getComponentRes.left() - .value() - .getMetadataDataDefinition() - .getUniqueId(), userId, errorWrapper); - } - if (errorWrapper.isEmpty()) { - if (component == null) { - componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper); - } - else { - componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper); - } - } - if (errorWrapper.isEmpty()) { - componentInstanceId = componentRiPair.getRight().getUniqueId(); - componentId = componentRiPair.getLeft().getUniqueId(); - ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); - - actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum - .findParamByType(componentType)); - if (actionResult.isRight()) { - log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult - .right() - .value()); - errorWrapper.setInnerElement(actionResult.right().value()); - } + .value() + .getMetadataDataDefinition() + .getUniqueId(), userId); } - if (errorWrapper.isEmpty()) { - uploadArtifact = actionResult.left().value().left().value(); - uploadArtifactResult = Either.left(uploadArtifact); + if (component == null) { + componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName); } else { - uploadArtifactResult = Either.right(errorWrapper.getInnerElement()); + componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName); } - return uploadArtifactResult; + componentInstanceId = componentRiPair.getRight().getUniqueId(); + componentId = componentRiPair.getLeft().getUniqueId(); + ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class, false); + + actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, + operation, null, artifactInfo, origMd5, data, null, null, + componentId, ComponentTypeEnum.findParamByType(componentType)); + + return actionResult.left().value(); } /** @@ -4770,18 +4120,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param componentType * @param componentUuid * @param artifactUUID - * @param operation + * @param resourceCommonInfo + * @param operation TODO * @return */ - public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, - ResourceCommonInfo resourceCommonInfo, ArtifactOperationInfo operation) { - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Either<ArtifactDefinition, ResponseFormat> updateArtifactResult; - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null; - ArtifactDefinition updateArtifact = null; - Component component = null; - String componentId = null; - String artifactId = null; + public ArtifactDefinition updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, + ResourceCommonInfo resourceCommonInfo, ArtifactOperationInfo operation) { + Either<ArtifactDefinition, Operation> actionResult; + Component component; + String componentId; + String artifactId ; ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class); String origMd5 = request.getHeader(Constants.MD5_HEADER); String userId = request.getHeader(Constants.USER_ID_HEADER); @@ -4789,47 +4137,34 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); - log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); - } - if (errorWrapper.isEmpty()) { - componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); - String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName(); - - if (!getComponentRes.left() - .value() - .getMetadataDataDefinition() - .getState() - .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - component = checkoutParentComponent(componentType, componentId, userId, errorWrapper); - if (component != null) { - componentId = component.getUniqueId(); - componentName = component.getName(); - } - } - resourceCommonInfo.setResourceName(componentName); - } - if (errorWrapper.isEmpty()) { - artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType); - } - if (errorWrapper.isEmpty()) { - actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null); - if (actionResult.isRight()) { - log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult - .right() - .value()); - errorWrapper.setInnerElement(actionResult.right().value()); - } + log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status)); + } + componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); + String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName(); + + if (!getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getState() + .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + component = checkoutParentComponent(componentType, componentId, userId); + if (component != null) { + componentId = component.getUniqueId(); + componentName = component.getName(); + } + } + resourceCommonInfo.setResourceName(componentName); + artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, componentId, componentType); + actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, + origMd5, data, null, null, null, null); + if (actionResult.isRight()) { + log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult + .right() + .value()); } - if (errorWrapper.isEmpty()) { - updateArtifact = actionResult.left().value().left().value(); - updateArtifactResult = Either.left(updateArtifact); - } - else { - updateArtifactResult = Either.right(errorWrapper.getInnerElement()); - } - return updateArtifactResult; + return actionResult.left().value(); } /** @@ -4844,17 +4179,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param operation TODO * @return */ - public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, - ArtifactOperationInfo operation) { + public ArtifactDefinition updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, + ArtifactOperationInfo operation) { - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Either<ArtifactDefinition, ResponseFormat> updateArtifactResult; - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null; - ArtifactDefinition updateArtifact = null; + Either<ArtifactDefinition, Operation> actionResult; Component component = null; - String componentInstanceId = null; - String componentId = null; - String artifactId = null; + String componentInstanceId; + String componentId; + String artifactId; String origMd5 = request.getHeader(Constants.MD5_HEADER); String userId = request.getHeader(Constants.USER_ID_HEADER); @@ -4862,52 +4194,33 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); - log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); + log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status)); } - if (errorWrapper.isEmpty() && !getComponentRes.left() - .value() - .getMetadataDataDefinition() - .getState() - .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + if (!getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getState() + .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { component = checkoutParentComponent(componentType, getComponentRes.left() - .value() - .getMetadataDataDefinition() - .getUniqueId(), userId, errorWrapper); - } - if (errorWrapper.isEmpty()) { - if (component == null) { - componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper); - } - else { - componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper); - } - } - if (errorWrapper.isEmpty()) { - componentInstanceId = componentRiPair.getRight().getUniqueId(); - componentId = componentRiPair.getLeft().getUniqueId(); - artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper); - } - if (errorWrapper.isEmpty()) { - ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); - - actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum - .findParamByType(componentType)); - if (actionResult.isRight()) { - log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult - .right() - .value()); - errorWrapper.setInnerElement(actionResult.right().value()); - } + .value() + .getMetadataDataDefinition() + .getUniqueId(), userId); } - if (errorWrapper.isEmpty()) { - updateArtifact = actionResult.left().value().left().value(); - updateArtifactResult = Either.left(updateArtifact); + if (component == null) { + componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName); } else { - updateArtifactResult = Either.right(errorWrapper.getInnerElement()); + componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName); } - return updateArtifactResult; + componentInstanceId = componentRiPair.getRight().getUniqueId(); + componentId = componentRiPair.getLeft().getUniqueId(); + artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID); + ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class, false); + + actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum + .findParamByType(componentType)); + return actionResult.left().value(); } private Either<ArtifactDefinition, ResponseFormat> updateOperationArtifact(String componentId, String interfaceType, String operationUuid, ArtifactDefinition artifactInfo){ @@ -4929,9 +4242,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { InterfaceDefinition gotInterface = optionalInterface.get(); Map<String, Operation> operationsMap = gotInterface.getOperationsMap(); Optional<Operation> optionalOperation = operationsMap.values() - .stream() - .filter(o -> o.getUniqueId().equals(operationUuid)) - .findFirst(); + .stream() + .filter(o -> o.getUniqueId().equals(operationUuid)) + .findFirst(); if (!optionalOperation.isPresent()) { log.debug("Failed to get resource interface operation for resource Id {} and operationId {}", componentId, operationUuid); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentId); @@ -4962,6 +4275,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.left(artifactInfo); } + /** * updates an artifact on a component by UUID * @@ -5003,7 +4317,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { .getMetadataDataDefinition() .getState() .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - Component component = checkoutParentComponent(componentType, componentId, userId, errorWrapper); + Component component = checkoutParentComponent(componentType, componentId, userId); if (component != null) { componentId = component.getUniqueId(); componentName = component.getName(); @@ -5047,14 +4361,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } if (errorWrapper.isEmpty()) { - actionResult = handleArtifactRequest(componentId, userId, componentType, operation, - artifactUUID, artifactInfo, origMd5, data, interfaceName, - operationUUID, null, null); - if (actionResult.isRight()) { - log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult - .right() - .value()); - errorWrapper.setInnerElement(actionResult.right().value()); + try { + actionResult = Either.left(handleArtifactRequest(componentId, userId, componentType, operation, + artifactUUID, artifactInfo, origMd5, data, interfaceName, + operationUUID, null, null)); + }catch (ComponentException e){ + errorWrapper.setInnerElement(e.getResponseFormat()); } } @@ -5086,7 +4398,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.left(optionalInterface.get().getType()); } - /** * deletes an artifact on a component by UUID * @@ -5098,61 +4409,39 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param operation TODO * @return */ - public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo, - ArtifactOperationInfo operation) { + public ArtifactDefinition deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo, + ArtifactOperationInfo operation) { - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult; - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null; - ArtifactDefinition deleteArtifact = null; - Component component = null; - String componentId = null; - String artifactId = null; + Either<ArtifactDefinition, Operation> actionResult; + Component component; + String componentId ; + String artifactId; 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("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid)); - } - if (errorWrapper.isEmpty()) { - componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); - String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName(); - if (!getComponentRes.left() - .value() - .getMetadataDataDefinition() - .getState() - .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - component = checkoutParentComponent(componentType, componentId, userId, errorWrapper); - if (component != null) { - componentId = component.getUniqueId(); - componentName = component.getName(); - } - } - resourceCommonInfo.setResourceName(componentName); - } - if (errorWrapper.isEmpty()) { - artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType); + log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid); } - if (errorWrapper.isEmpty()) { - actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null); - if (actionResult.isRight()) { - log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult - .right() - .value()); - errorWrapper.setInnerElement(actionResult.right().value()); + componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); + String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName(); + if (!getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getState() + .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + component = checkoutParentComponent(componentType, componentId, userId); + if (component != null) { + componentId = component.getUniqueId(); + componentName = component.getName(); } } - if (errorWrapper.isEmpty()) { - deleteArtifact = actionResult.left().value().left().value(); - deleteArtifactResult = Either.left(deleteArtifact); - } - else { - deleteArtifactResult = Either.right(errorWrapper.getInnerElement()); - } - return deleteArtifactResult; + resourceCommonInfo.setResourceName(componentName); + artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, componentId, componentType); + actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null); + return actionResult.left().value(); } /** @@ -5166,95 +4455,74 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param operation TODO * @return */ - public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, - ArtifactOperationInfo operation) { + public ArtifactDefinition deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, + String componentUuid, String resourceInstanceName, + String artifactUUID, ArtifactOperationInfo operation) { - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult; - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null; - ArtifactDefinition deleteArtifact = null; + Either<ArtifactDefinition, Operation> actionResult; Component component = null; - String componentInstanceId = null; - String componentId = null; - String artifactId = null; + String componentInstanceId; + String componentId; + String artifactId; 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); + Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = + toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); - log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); + log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status)); } - if (errorWrapper.isEmpty() && !getComponentRes.left() - .value() - .getMetadataDataDefinition() - .getState() - .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + if (!getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getState() + .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { component = checkoutParentComponent(componentType, getComponentRes.left() - .value() - .getMetadataDataDefinition() - .getUniqueId(), userId, errorWrapper); - } - if (errorWrapper.isEmpty()) { - if (component == null) { - componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper); - } - else { - componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper); - } - } - if (errorWrapper.isEmpty()) { - componentInstanceId = componentRiPair.getRight().getUniqueId(); - componentId = componentRiPair.getLeft().getUniqueId(); - artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper); - } - if (errorWrapper.isEmpty()) { - - actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum - .findParamByType(componentType)); - - if (actionResult.isRight()) { - log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult - .right() - .value()); - errorWrapper.setInnerElement(actionResult.right().value()); - } + .value() + .getMetadataDataDefinition() + .getUniqueId(), userId); } - if (errorWrapper.isEmpty()) { - deleteArtifact = actionResult.left().value().left().value(); - deleteArtifactResult = Either.left(deleteArtifact); + if (component == null) { + componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName); } else { - deleteArtifactResult = Either.right(errorWrapper.getInnerElement()); + componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName); } - return deleteArtifactResult; + componentInstanceId = componentRiPair.getRight().getUniqueId(); + componentId = componentRiPair.getLeft().getUniqueId(); + artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID); + + actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum + .findParamByType(componentType)); + return actionResult.left().value(); } - private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) { + private String findArtifactId(ComponentInstance instance, String artifactUUID) { String artifactId = null; ArtifactDefinition foundArtifact = null; if (instance.getDeploymentArtifacts() != null) { foundArtifact = instance.getDeploymentArtifacts() - .values() - .stream() - .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID() - .equals(artifactUUID)) - .findFirst() - .orElse(null); + .values() + .stream() + .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID() + .equals(artifactUUID)) + .findFirst() + .orElse(null); } if (foundArtifact == null && instance.getArtifacts() != null) { foundArtifact = instance.getArtifacts() - .values() - .stream() - .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID() - .equals(artifactUUID)) - .findFirst() - .orElse(null); + .values() + .stream() + .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID() + .equals(artifactUUID)) + .findFirst() + .orElse(null); } if (foundArtifact == null) { log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId()); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID)); + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID); } else { artifactId = foundArtifact.getUniqueId(); @@ -5263,63 +4531,64 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } @SuppressWarnings("unchecked") - public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition heatArtifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component, - Map<String, String> existingEnvVersions) { + public ArtifactDefinition createHeatEnvPlaceHolder(List<ArtifactDefinition> createdArtifacts, ArtifactDefinition heatArtifact, + String envType, String parentId, NodeTypeEnum parentType, + String parentName, User user, Component component, + Map<String, String> existingEnvVersions) { Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager() - .getConfiguration() - .getDeploymentResourceInstanceArtifacts(); + .getConfiguration() + .getDeploymentResourceInstanceArtifacts(); if (deploymentResourceArtifacts == null) { log.debug("no deployment artifacts are configured for generated artifacts"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType); if (placeHolderData == null) { log.debug("no env type {} are configured for generated artifacts", envType); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase(); - Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user + ArtifactDefinition createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user .getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true); - if (createArtifactPlaceHolder.isRight()) { - return Either.right(createArtifactPlaceHolder.right().value()); - } - ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value(); + ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder; artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId()); artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis()); artifactHeatEnv.setTimeout(0); + artifactHeatEnv.setIsFromCsar(heatArtifact.getIsFromCsar()); buildHeatEnvFileName(heatArtifact, artifactHeatEnv, placeHolderData); // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions); ArtifactDefinition heatEnvPlaceholder; // Evg : for resource instance artifact will be added later as block with other env artifacts from BL if (parentType != NodeTypeEnum.ResourceInstance) { - Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component - .getUniqueId(), parentType, parentId); + String checkSum = artifactToscaOperation.sortAndCalculateChecksumForHeatParameters(heatArtifact.getHeatParameters()); + artifactHeatEnv.setArtifactChecksum(checkSum); + Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component, parentType, parentId); if (addHeatEnvArtifact.isRight()) { log.debug("failed to create heat env artifact on resource instance"); - return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact .right() .value(), false), "", null)); } - heatEnvPlaceholder = createArtifactPlaceHolder.left().value(); + heatEnvPlaceholder = createArtifactPlaceHolder; } else { heatEnvPlaceholder = artifactHeatEnv; artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion()); setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder); } - ComponentTypeEnum componentType = component.getComponentType(); if (parentType == NodeTypeEnum.ResourceInstance) { componentType = ComponentTypeEnum.RESOURCE_INSTANCE; } + createdArtifacts.add(heatEnvPlaceholder); componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.ARTIFACT_UPLOAD, new ResourceCommonInfo(parentName, componentType.getValue()), ResourceVersionInfo.newBuilder().build(), ResourceVersionInfo.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(), null, heatEnvPlaceholder, null); - return Either.left(heatEnvPlaceholder); + return heatEnvPlaceholder; } private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) { @@ -5360,26 +4629,75 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } - /** - * Handles Artifacts Request For Inner Component - * - * @param artifactsToHandle - * @param component - * @param user - * @param vfcsNewCreatedArtifacts - * @param operation - * @param shouldLock - * @param inTransaction - * @return - */ - public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts, - ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) { - - Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null; + public List<ArtifactDefinition> handleArtifactsForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts, + ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) { ComponentTypeEnum componentType = component.getComponentType(); List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>(); + Either<ArtifactDefinition, Operation> result; + try { + for (ArtifactDefinition artifactDefinition : artifactsToHandle) { + result = handleLoadedArtifact(component, user, operation, shouldLock, inTransaction, componentType, artifactDefinition); + uploadedArtifacts.add(result.left().value()); + } + } catch (ComponentException e) { + log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, component + .getName(), e.getResponseFormat()); + if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { + vfcsNewCreatedArtifacts.addAll(uploadedArtifacts); + } + throw e; + } + return uploadedArtifacts; + } + + public Either<ArtifactDefinition, Operation> handleLoadedArtifact(Resource component, User user, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, + ComponentTypeEnum componentType, ArtifactDefinition artifactDefinition) { + AuditingActionEnum auditingAction = detectAuditingType(operation, ""); + String componentId = component.getUniqueId(); + String artifactId = artifactDefinition.getUniqueId(); + Either<ArtifactDefinition, Operation> result; Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult; + //artifact validation + artifactDefinition = validateArtifact(componentId, componentType, operation, + artifactId, artifactDefinition, auditingAction, user, + component, shouldLock, inTransaction); + switch (operation.getArtifactOperationEnum()) { + case CREATE: + byte[] validPayload = getValidPayload(componentId, artifactDefinition, operation, auditingAction, artifactId, user, componentType, component, null, null); + result = createArtifact(component, componentId, artifactDefinition, validPayload, + componentType, auditingAction, null, null); + break; + case UPDATE: + validPayload = getValidPayload(componentId, artifactDefinition, operation, auditingAction, artifactId, user, componentType, component, null, null); + result = handleUpdate(componentId, componentType, operation, artifactId, artifactDefinition, validPayload, null, null, null, null, + auditingAction, user, component, true); + break; + case DELETE: + result = Either.left(handleDeleteInternal(componentId, artifactId, componentType, component)); + break; + case DOWNLOAD: + if (artifactGenerationRequired(component, artifactDefinition)) { + result = Either.left(generateNotSavedArtifact(component, artifactDefinition)); + } else { + result = Either.left(handleDownload(componentId, artifactId, componentType, component)); + } + break; + case LINK: + result = Either.left(handleLink(componentId, artifactDefinition, componentType, component)); + break; + default: + throw new UnsupportedOperationException("In ArtifactsBusinessLogic received illegal operation: " + operation.getArtifactOperationEnum()); + } + return result; + } + + public List<ArtifactDefinition> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts, + ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) { + + List<ArtifactDefinition> handleArtifactsResult; + ComponentTypeEnum componentType = component.getComponentType(); + List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>(); + Either<ArtifactDefinition, Operation> actionResult; String originData; String origMd5; try { @@ -5388,68 +4706,50 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData); actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact .getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction); - if (actionResult.isRight()) { - log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component - .getName(), actionResult.right().value()); - errorWrapper.setInnerElement(actionResult.right().value()); - if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { - vfcsNewCreatedArtifacts.addAll(uploadedArtifacts); - } - break; - } - uploadedArtifacts.add(actionResult.left().value().left().value()); + uploadedArtifacts.add(actionResult.left().value()); } - if (errorWrapper.isEmpty()) { - handleArtifactsResult = Either.left(uploadedArtifacts); - } - else { - handleArtifactsResult = Either.right(errorWrapper.getInnerElement()); + handleArtifactsResult = uploadedArtifacts; + }catch (ComponentException e){ + if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { + vfcsNewCreatedArtifacts.addAll(uploadedArtifacts); } - } - catch (Exception e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleArtifactsResult = Either.right(responseFormat); - log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e); + throw e; } return handleArtifactsResult; } - private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) { - ComponentInstance componentInstance = null; + private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName) { + ComponentInstance componentInstance; String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName); - Component component = getComponentByUuid(componentType, componentUuid, errorWrapper); - if (errorWrapper.isEmpty()) { - componentInstance = component.getComponentInstances() - .stream() - .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()) - .equals(normalizedName)) - .findFirst() - .orElse(null); - if (componentInstance == null) { - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component - .getComponentType() - .getValue(), component.getName())); - log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName()); - } + 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; } - private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) { + private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName) { 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); + .stream() + .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()) + .equals(normalizedName)) + .findFirst() + .orElse(null); if (componentInstance == null) { - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component - .getComponentType() - .getValue(), component.getName())); 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); @@ -5457,68 +4757,57 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return relatedComponentComponentInstancePair; } - private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) { + private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, + String componentUuid, String resourceInstanceName) { ComponentInstance componentInstance; - ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null; - Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper); - if (errorWrapper.isEmpty()) { - componentInstance = component.getComponentInstances() - .stream() - .filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)) - .findFirst() - .orElse(null); - if (componentInstance == null) { - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component - .getComponentType() - .getValue(), component.getName())); - log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName()); - } - else { - relatedComponentComponentInstancePair = new ImmutablePair<>(component, 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) { + 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 byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) { + private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, String componentName) { - byte[] downloadedArtifact = null; - Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null; + ImmutablePair<String, byte[]> downloadArtifact; List<ArtifactDefinition> artifactsList = null; - ArtifactDefinition deploymentArtifact = null; + ArtifactDefinition deploymentArtifact; if (artifacts != null && !artifacts.isEmpty()) { artifactsList = artifacts.values() - .stream() - .filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID() - .equals(artifactUUID)) - .collect(Collectors.toList()); + .stream() + .filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID() + .equals(artifactUUID)) + .collect(Collectors.toList()); } if (artifactsList == null || artifactsList.isEmpty()) { log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID)); - } - if (errorWrapper.isEmpty()) { - deploymentArtifact = artifactsList.get(0); - downloadArtifactEither = downloadArtifact(deploymentArtifact); - if (downloadArtifactEither.isRight()) { - log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName()); - errorWrapper.setInnerElement(downloadArtifactEither.right().value()); - } + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID); } - if (errorWrapper.isEmpty()) { - log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId()); - downloadedArtifact = downloadArtifactEither.left().value().getRight(); - } - return downloadedArtifact; + deploymentArtifact = artifactsList.get(0); + downloadArtifact = downloadArtifact(deploymentArtifact); + log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId()); + return downloadArtifact.getRight(); } - private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) { - Component component = null; + private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid) { + Component component; Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); - log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); + log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status)); } else { component = getComponentRes.left().value(); @@ -5526,20 +4815,20 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return component; } - private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) { - Component component = null; + private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid) { + Component component; Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); - log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); + log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status)); } else { List<Component> value = getComponentRes.left().value(); if (value.isEmpty()) { log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid); ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND; - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status)); + throw new ByActionStatusComponentException(status); } else { component = value.get(0); @@ -5548,78 +4837,58 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return component; } - private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) { - String artifactId = null; + private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, String parentId, ComponentTypeEnum componentType) { ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND; StorageOperationStatus storageStatus; - ArtifactDefinition latestArtifact = null; - List<ArtifactDefinition> artifacts = null; + ArtifactDefinition latestArtifact; + List<ArtifactDefinition> artifacts; Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId); if (getArtifactsRes.isRight()) { storageStatus = getArtifactsRes.right().value(); log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType, parentId, storageStatus); - if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) { + if (storageStatus != StorageOperationStatus.NOT_FOUND) { actionStatus = componentsUtils.convertFromStorageResponse(storageStatus); } - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID)); + throw new ByActionStatusComponentException(actionStatus, artifactUUID); } - if (errorWrapper.isEmpty()) { - artifacts = getArtifactsRes.left() - .value() - .values() - .stream() - .filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID() - .equals(artifactUUID)) - .collect(Collectors.toList()); - if (artifacts == null || artifacts.isEmpty()) { - log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID)); - } + artifacts = getArtifactsRes.left() + .value() + .values() + .stream() + .filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID() + .equals(artifactUUID)) + .collect(Collectors.toList()); + if (artifacts == null || artifacts.isEmpty()) { + log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus); + throw new ByActionStatusComponentException(actionStatus, artifactUUID); } - if (errorWrapper.isEmpty()) { - latestArtifact = artifacts.stream().max((a1, a2) -> { - int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion())); - if (compareRes == 0) { - compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2 - .getLastUpdateDate()); - } - return compareRes; - }).get(); - if (latestArtifact == null) { - log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID)); + latestArtifact = artifacts.stream().max((a1, a2) -> { + int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion())); + if (compareRes == 0) { + compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2 + .getLastUpdateDate()); } + return compareRes; + }).get(); + if (latestArtifact == null) { + log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus); + throw new ByActionStatusComponentException(actionStatus, artifactUUID); } - if (errorWrapper.isEmpty()) { - artifactId = latestArtifact.getUniqueId(); - } - return artifactId; + return latestArtifact.getUniqueId(); } - private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) { + private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId) { Component component = null; - Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false); - if (getUserRes.isRight()) { - log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes - .right() - .value()); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value())); + User modifier = userBusinessLogic.getUser(userId, false); + LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API); + Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true); + if (checkoutRes.isRight()) { + log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType + .getNodeType(), parentId, checkoutRes.right().value().getStatus()); + throw new ByResponseFormatComponentException(checkoutRes.right().value()); } - if (errorWrapper.isEmpty()) { - User modifier = getUserRes.left().value(); - LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API); - Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true); - if (checkoutRes.isRight()) { - log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType - .getNodeType(), parentId, checkoutRes.right().value().getStatus()); - errorWrapper.setInnerElement(checkoutRes.right().value()); - } - else { - component = checkoutRes.left().value(); - } - } - return component; + return checkoutRes.left().value(); } private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) { @@ -5639,4 +4908,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { void setNodeTemplateOperation(NodeTemplateOperation nodeTemplateOperation) { this.nodeTemplateOperation = nodeTemplateOperation; } + } + diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java index c20a2b3b28..c0f08b0bb3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java @@ -84,7 +84,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { */ public Either<PropertyDefinition, ResponseFormat> createAttribute(String resourceId, PropertyDefinition newAttributeDef, String userId) { Either<PropertyDefinition, ResponseFormat> result = null; - validateUserExists(userId, "create Attribute", false); + validateUserExists(userId); StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); if (lockResult != StorageOperationStatus.OK) { @@ -110,17 +110,14 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { if (isAttributeExist(resource.getAttributes(), resourceId, newAttributeDef.getName())) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_ALREADY_EXIST, newAttributeDef.getName())); } - Either<Map<String, DataTypeDefinition>, ResponseFormat> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache); - if (eitherAllDataTypes.isRight()) { - return Either.right(eitherAllDataTypes.right().value()); - } + Map<String, DataTypeDefinition> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache); // validate property default values - Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newAttributeDef, eitherAllDataTypes.left().value()); + Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newAttributeDef, eitherAllDataTypes); if (defaultValuesValidation.isRight()) { return Either.right(defaultValuesValidation.right().value()); } - handleDefaultValue(newAttributeDef, eitherAllDataTypes.left().value()); + handleDefaultValue(newAttributeDef, eitherAllDataTypes); // add the new attribute to resource on graph // need to get StorageOpaerationStatus and convert to ActionStatus from @@ -157,7 +154,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { */ public Either<PropertyDefinition, ResponseFormat> getAttribute(String resourceId, String attributeId, String userId) { - validateUserExists(userId, "get Attribute", false); + validateUserExists(userId); // Get the resource from DB Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId); @@ -213,19 +210,16 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { if (eitherAttribute.isRight()) { return Either.right(eitherAttribute.right().value()); } - Either<Map<String, DataTypeDefinition>, ResponseFormat> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache); - if (eitherAllDataTypes.isRight()) { - return Either.right(eitherAllDataTypes.right().value()); - } + Map<String, DataTypeDefinition> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache); // validate attribute default values - Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newAttDef, eitherAllDataTypes.left().value()); + Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newAttDef, eitherAllDataTypes); if (defaultValuesValidation.isRight()) { return Either.right(defaultValuesValidation.right().value()); } // add the new property to resource on graph - StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty(newAttDef, eitherAllDataTypes.left().value()); + StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty(newAttDef, eitherAllDataTypes); if (validateAndUpdateAttribute != StorageOperationStatus.OK) { log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, validateAndUpdateAttribute); result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(validateAndUpdateAttribute), resource.getName())); @@ -261,7 +255,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { Either<PropertyDefinition, ResponseFormat> result = null; - validateUserExists(userId, "delete Attribute", false); + validateUserExists(userId); StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); if (lockResult != StorageOperationStatus.OK) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java index b1356fc11b..42e8d9bad1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java @@ -26,21 +26,18 @@ import com.google.gson.JsonElement; import fj.data.Either; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.function.Function; import org.apache.commons.lang3.tuple.ImmutablePair; 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.validation.UserValidations; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyRule; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; @@ -48,13 +45,17 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstInputsMap; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.IComplexDefaultValue; import org.openecomp.sdc.be.model.IPropertyInputCommon; import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.PolicyDefinition; import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.User; @@ -79,30 +80,36 @@ import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter; import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter; import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator; -import org.openecomp.sdc.be.user.IUserBusinessLogic; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.function.Function; + public abstract class BaseBusinessLogic { private static final String FAILED_TO_LOCK_COMPONENT_ERROR = "Failed to lock component {} error - {}"; - private static final Logger log = Logger.getLogger(BaseBusinessLogic.class.getName()); - + private static final Logger log = Logger.getLogger(BaseBusinessLogic.class.getName()); private static final String EMPTY_VALUE = null; private static final String SCHEMA_DOESN_T_EXISTS_FOR_PROPERTY_OF_TYPE = "Schema doesn't exists for property of type {}"; private static final String PROPERTY_IN_SCHEMA_DEFINITION_INSIDE_PROPERTY_OF_TYPE_DOESN_T_EXIST = "Property in Schema Definition inside property of type {} doesn't exist"; private static final String ADD_PROPERTY_VALUE = "Add property value"; private static final String THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID = "The value {} of property from type {} is invalid"; - protected final IGroupTypeOperation groupTypeOperation; - protected final InterfaceOperation interfaceOperation; - protected final IElementOperation elementDao; + protected IGroupTypeOperation groupTypeOperation; + protected InterfaceOperation interfaceOperation; + protected IElementOperation elementDao; protected ComponentsUtils componentsUtils; - protected IUserBusinessLogic userAdmin; + protected UserBusinessLogic userAdmin; protected IGraphLockOperation graphLockOperation; protected JanusGraphDao janusGraphDao; protected JanusGraphGenericDao janusGraphGenericDao; @@ -110,12 +117,12 @@ public abstract class BaseBusinessLogic { protected ApplicationDataTypeCache applicationDataTypeCache; protected ToscaOperationFacade toscaOperationFacade; protected ApplicationDataTypeCache dataTypeCache; - final IGroupOperation groupOperation; - final IGroupInstanceOperation groupInstanceOperation; - final InterfaceLifecycleOperation interfaceLifecycleTypeOperation; - PolicyTypeOperation policyTypeOperation; - protected final ArtifactsOperations artifactToscaOperation; - private UserValidations userValidations; + protected IGroupOperation groupOperation; + protected IGroupInstanceOperation groupInstanceOperation; + protected InterfaceLifecycleOperation interfaceLifecycleTypeOperation; + protected PolicyTypeOperation policyTypeOperation; + protected ArtifactsOperations artifactToscaOperation; + protected UserValidations userValidations; DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); @@ -190,154 +197,157 @@ public abstract class BaseBusinessLogic { return userValidations.validateUserNotEmpty(user, ecompErrorContext); } - protected User validateUserExists(User user, String ecompErrorContext, boolean inTransaction) { - return userValidations.validateUserExists(user.getUserId(), ecompErrorContext, inTransaction); - } - - protected void validateUserExist(String userId, String ecompErrorContext) { - userValidations.validateUserExist(userId, ecompErrorContext); + protected User validateUserExists(String userId) { + return userValidations.validateUserExists(userId); } - Either<User, ActionStatus> validateUserExistsActionStatus(String userId, String ecompErrorContext) { - return userValidations.validateUserExistsActionStatus(userId, ecompErrorContext); + public User validateUserExists(User user) { + return userValidations.validateUserExists(user); } - public User validateUserExists(String userId, String ecompErrorContext, boolean inTransaction) { - return userValidations.validateUserExists(userId, ecompErrorContext, inTransaction); + ActionStatus validateUserExistsActionStatus(String userId) { + return userValidations.validateUserExistsActionStatus(userId); } protected void validateUserRole(User user, List<Role> roles) { userValidations.validateUserRole(user, roles); } - protected Either<Boolean, ResponseFormat> lockComponent(Component component, String ecompErrorContext) { - return lockComponent(component.getUniqueId(), component, ecompErrorContext); + protected void lockComponent(Component component, String ecompErrorContext) { + lockComponent(component.getUniqueId(), component, ecompErrorContext); } - protected Either<Component, ResponseFormat> lockComponent(Component component, boolean shoulLock, String ecompErrorContext) { - return shoulLock ? lockComponent(component.getUniqueId(), component, ecompErrorContext) - .either(l -> Either.left(component), Either::right) : Either.left(component); + protected boolean isVolumeGroup(List<String> artifactsInGroup,List <ArtifactDefinition> deploymentArtifacts) { + for (String artifactId : artifactsInGroup) { + ArtifactDefinition artifactDef = ArtifactUtils.findArtifactInList(deploymentArtifacts, artifactId); + if (artifactDef != null + && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) { + return true; + } + } + return false; } - protected Either<Boolean, ResponseFormat> lockComponent(String componentId, Component component, String ecompErrorContext) { - return lockElement( componentId, component, ecompErrorContext) - .right() - .map(r -> logAndConvertError(r, component.getUniqueId(), component.getName()) ); + protected void lockComponent(Component component, boolean shouldLock, String ecompErrorContext) { + if(shouldLock){ + lockComponent(component.getUniqueId(), component, ecompErrorContext); + } } - protected void lockComponent(String componentId, Component component, boolean needLock, String ecompErrorContext) { - if (needLock){ - lockElement( componentId, component, ecompErrorContext) - .left() - .on(r -> logAndThrowException(r, component.getUniqueId(), component.getName()) ); + protected void lockComponent(String componentId, Component component, String ecompErrorContext) { + ActionStatus lock = lockElement(componentId, component, ecompErrorContext); + if ( lock!= ActionStatus.OK ) { + logAndThrowComponentException(lock, component.getUniqueId(), component.getName()); } } - private Boolean logAndThrowException(ActionStatus status, String componentId, String name){ - log.debug(FAILED_TO_LOCK_COMPONENT_ERROR, componentId, status); - throw new ByActionStatusComponentException(status, name); + protected void lockComponent(String componentId, Component component, boolean needLock, String ecompErrorContext) { + if (needLock) { + lockComponent(componentId, component, ecompErrorContext); + } } - private ResponseFormat logAndConvertError(ActionStatus status, String componentId, String name){ - ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, name); + private ResponseFormat logAndThrowComponentException(ActionStatus status, String componentId, String name){ log.debug(FAILED_TO_LOCK_COMPONENT_ERROR, componentId, status); - return responseFormat; + throw new ByActionStatusComponentException(status, name); } - private Either<Boolean, ActionStatus> lockElement(String componentId, Component component, String ecompErrorContext) { + private ActionStatus lockElement(String componentId, Component component, String ecompErrorContext) { ComponentTypeEnum componentType = component.getComponentType(); NodeTypeEnum nodeType = componentType.getNodeType(); StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponent(componentId, nodeType); - if (lockResourceStatus.equals(StorageOperationStatus.OK)) { - return Either.left(true); + if (lockResourceStatus == StorageOperationStatus.OK) { + return ActionStatus.OK; } else { BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), componentId); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType); - return Either.right(actionStatus); + return componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType); } } - protected void unlockComponent(Either<?, ?> either, Component component, boolean inTransaction) { - ComponentTypeEnum componentType = component.getComponentType(); - NodeTypeEnum nodeType = componentType.getNodeType(); - if (!inTransaction) { - if (either == null || either.isRight()) { - janusGraphDao.rollback(); - } else { - janusGraphDao.commit(); + protected void unlockComponent(boolean failed, Component component, boolean inTransaction) { + if (component != null) { + ComponentTypeEnum componentType = component.getComponentType(); + NodeTypeEnum nodeType = componentType.getNodeType(); + if (!inTransaction) { + if (failed) { + janusGraphDao.rollback(); + } else { + janusGraphDao.commit(); + } } + // unlock resource + graphLockOperation.unlockComponent(component.getUniqueId(), nodeType); } - // unlock resource - graphLockOperation.unlockComponent(component.getUniqueId(), nodeType); + else log.debug("component is NULL"); } - protected void unlockComponent(Either<?, ?> either, Component component) { - unlockComponent(either, component, false); + protected void unlockComponent(boolean failed, Component component) { + unlockComponent(failed, component, false); } - void unlockComponentById(Either<?, ?> either, String componentId) { + void unlockComponentById(boolean failed, String componentId) { Either<Component, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(componentId); if(component.isLeft()) { - unlockComponent(either, component.left().value(), false); + unlockComponent(failed, component.left().value(), false); } } - <T> Either<Boolean, ResponseFormat> validateJsonBody(T bodyObject, Class<T> clazz) { + <T> Boolean validateJsonBody(T bodyObject, Class<T> clazz) { if (bodyObject == null) { log.debug("Invalid JSON received for object of type {}", clazz.getSimpleName()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); } else { - return Either.left(true); + return true; } } - Either<ComponentTypeEnum, ResponseFormat> validateComponentType(String componentType) { + + ComponentTypeEnum validateComponentType(String componentType) { ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); if (componentTypeEnum == null) { log.debug("Invalid component type {}", componentType); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, componentType)); + throw new ByActionStatusComponentException(ActionStatus.UNSUPPORTED_ERROR, componentType); } else { - return Either.left(componentTypeEnum); + return componentTypeEnum; } } - protected Either<Component, ResponseFormat> validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView filter) { - return toscaOperationFacade.getToscaElement(componentId, filter == null ? new ComponentParametersView() : filter) - .right() - .map(err -> handleGetComponentError(componentId, componentType, err)) - .left() - .bind(cmpt -> validateComponentType(cmpt, componentType)); + Component validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView filter) { + + Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaElement(componentId, filter == null ? new ComponentParametersView() : filter); + if(toscaElement.isRight()){ + handleGetComponentError(componentId, componentType, toscaElement.right().value()); + } + return validateComponentType(toscaElement.left().value(), componentType); } - private Either<Component, ResponseFormat> validateComponentType(Component cmpt, ComponentTypeEnum componentType) { + private Component validateComponentType(Component cmpt, ComponentTypeEnum componentType) { if (componentType != cmpt.getComponentType()) { log.debug("component {} is not of requested type {}", cmpt.getUniqueId(), componentType); - ActionStatus cmptNotFoundError = componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType); - return Either.right(componentsUtils.getResponseFormat(cmptNotFoundError)); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType)); } - return Either.left(cmpt); + return cmpt; } - <T extends PropertyDataDefinition> Either<String, ResponseFormat> updateInputPropertyObjectValue(T property) { + <T extends PropertyDataDefinition> String updateInputPropertyObjectValue(T property) { Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll(); if (allDataTypesEither.isRight()) { JanusGraphOperationStatus status = allDataTypesEither.right().value(); BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)))); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))); } Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value(); String propertyType = property.getType(); String innerType = getInnerType(property); // Specific Update Logic Either<Object, Boolean> isValid = - propertyOperation.validateAndUpdatePropertyValue(propertyType, (String) property.getValue(), true, - innerType, allDataTypes); + propertyOperation.validateAndUpdatePropertyValue(propertyType, (String) property.getValue(), true, + innerType, allDataTypes); String newValue = property.getValue(); if (isValid.isRight()) { Boolean res = isValid.right().value(); if (Boolean.FALSE.equals(res)) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus( - JanusGraphOperationStatus.ILLEGAL_ARGUMENT)))); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))); } } else { Object object = isValid.left().value(); @@ -345,10 +355,10 @@ public abstract class BaseBusinessLogic { newValue = object.toString(); } } - return Either.left(newValue); + return newValue; } - private <T extends PropertyDataDefinition> String getInnerType(T property){ + <T extends PropertyDataDefinition> String getInnerType(T property){ ToscaPropertyType type = ToscaPropertyType.isValidType(property.getType()); log.debug("#getInnerType - The type of the property {} is {}", property.getUniqueId(), property.getType()); String innerType = null; @@ -367,35 +377,41 @@ public abstract class BaseBusinessLogic { return innerType; } - public Either<Boolean, ResponseFormat> validateCanWorkOnComponent(Component component, String userId) { - Either<Boolean, ResponseFormat> canWork = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + public void validateCanWorkOnComponent(Component component, String userId) { + ActionStatus actionStatus = ActionStatus.RESTRICTED_OPERATION; + // verify resource is not archived + if (component.isArchived() == true){ + actionStatus = ActionStatus.COMPONENT_IS_ARCHIVED; + throw new ByActionStatusComponentException(actionStatus, component.getName()); + } + if (component.getLifecycleState() != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) { log.debug("Component {} is not checked-out", component.getName()); - return canWork; + throw new ByActionStatusComponentException(actionStatus); } // verify userId is not null if (userId == null) { log.debug("Current user userId is null"); - return canWork; + throw new ByActionStatusComponentException(actionStatus); } // verify component last update user is the current user String lastUpdaterUserId = component.getLastUpdaterUserId(); if (!userId.equals(lastUpdaterUserId)) { log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}", lastUpdaterUserId, userId); - return canWork; + throw new ByActionStatusComponentException(actionStatus); } // verify resource is not deleted if (Boolean.TRUE.equals(component.getIsDeleted())) { log.debug("Component {} is marked as deleted", component.getUniqueId()); - return canWork; + throw new ByActionStatusComponentException(actionStatus); } - return Either.left(true); } + ComponentTypeEnum getComponentTypeByParentComponentType(ComponentTypeEnum parentComponentType) { switch (parentComponentType) { case SERVICE: @@ -410,19 +426,20 @@ public abstract class BaseBusinessLogic { } - protected Either<Map<String, DataTypeDefinition>, ResponseFormat> getAllDataTypes(ApplicationDataTypeCache applicationDataTypeCache) { + + protected Map<String, DataTypeDefinition> getAllDataTypes(ApplicationDataTypeCache applicationDataTypeCache) { Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); if (allDataTypes.isRight()) { JanusGraphOperationStatus operationStatus = allDataTypes.right().value(); if (operationStatus == JanusGraphOperationStatus.NOT_FOUND) { BeEcompErrorManager.getInstance().logInternalDataError("FetchDataTypes", "Data types are not loaded", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY)); + throw new ByActionStatusComponentException(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY); } else { BeEcompErrorManager.getInstance().logInternalFlowError("FetchDataTypes", "Failed to fetch data types", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } } - return Either.left(allDataTypes.left().value()); + return allDataTypes.left().value(); } Either<Boolean, ResponseFormat> validatePropertyDefaultValue(IComplexDefaultValue property, Map<String, DataTypeDefinition> dataTypes) { @@ -448,10 +465,10 @@ public abstract class BaseBusinessLogic { ResponseFormat responseFormat; if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, - property.getDefaultValue()); + property.getDefaultValue()); } else { responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, - property.getDefaultValue()); + property.getDefaultValue()); } return Either.right(responseFormat); @@ -525,7 +542,7 @@ public abstract class BaseBusinessLogic { NodeTypeEnum nodeType = componentType.getNodeType(); StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponentByName(name, nodeType); - if (lockResourceStatus.equals(StorageOperationStatus.OK)) { + if (lockResourceStatus == StorageOperationStatus.OK) { return Either.left(true); } else { BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), name); @@ -536,18 +553,17 @@ public abstract class BaseBusinessLogic { } } - protected Either<Component, ResponseFormat> validateComponentExistsByFilter(String componentId, ComponentTypeEnum componentType, ComponentParametersView componentParametersView) { + protected Component validateComponentExistsByFilter(String componentId, ComponentTypeEnum componentType, ComponentParametersView componentParametersView) { return toscaOperationFacade.getToscaElement(componentId, componentParametersView) - .right() - .map(err -> handleGetComponentError(componentId, componentType, err)); + .left() + .on(err -> handleGetComponentError(componentId, componentType, err)); } - private ResponseFormat handleGetComponentError(String componentId, ComponentTypeEnum componentType, StorageOperationStatus getComponentError) { + private Component handleGetComponentError(String componentId, ComponentTypeEnum componentType, StorageOperationStatus getComponentError) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentError, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, componentId); log.debug("error fetching component with id {}. error status: {}", componentId, getComponentError); - return responseFormat; + throw new ByActionStatusComponentException(actionStatus, componentId); } @SafeVarargs @@ -566,7 +582,7 @@ public abstract class BaseBusinessLogic { Boolean res = isValid.right().value(); if (Boolean.FALSE.equals(res)) { throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus( - JanusGraphOperationStatus.ILLEGAL_ARGUMENT)); + JanusGraphOperationStatus.ILLEGAL_ARGUMENT)); } } else { Object object = isValid.left().value(); @@ -579,7 +595,7 @@ public abstract class BaseBusinessLogic { if (Boolean.FALSE.equals(pair.getRight())) { BeEcompErrorManager.getInstance().logBeInvalidValueError(ADD_PROPERTY_VALUE, pair.getLeft(), property.getName(), propertyType); throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus( - JanusGraphOperationStatus.ILLEGAL_ARGUMENT)); + JanusGraphOperationStatus.ILLEGAL_ARGUMENT)); } return newValue; } @@ -697,7 +713,7 @@ public abstract class BaseBusinessLogic { } public <T extends ToscaDataDefinition> Either<List<T>, ResponseFormat> declareProperties(String userId, String componentId, - ComponentTypeEnum componentTypeEnum, ComponentInstInputsMap componentInstInputsMap) { + ComponentTypeEnum componentTypeEnum, ComponentInstInputsMap componentInstInputsMap) { return Either.left(new ArrayList<>()); } @@ -705,7 +721,7 @@ public abstract class BaseBusinessLogic { public <T extends PropertyDataDefinition> List<PropertyConstraint> setInputConstraint(T inputDefinition) { if (StringUtils.isNotBlank(inputDefinition.getParentPropertyType()) && StringUtils.isNotBlank(inputDefinition.getSubPropertyInputPath())) { - return setConstraint(inputDefinition); + return setConstraint(inputDefinition); } return Collections.emptyList(); @@ -756,4 +772,53 @@ public abstract class BaseBusinessLogic { return type; } + + + protected void rollbackWithException(StorageException e) { + janusGraphDao.rollback(); + throw e; + } + + protected void rollbackWithException(ComponentException e) { + janusGraphDao.rollback(); + throw e; + } + + protected void unlockRollbackWithException(Component component, RuntimeException e) { + janusGraphDao.rollback(); + graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType()); + throw e; + } + + protected void unlockWithCommit(Component component){ + ComponentTypeEnum componentType = component.getComponentType(); + NodeTypeEnum nodeType = componentType.getNodeType(); + janusGraphDao.commit(); + graphLockOperation.unlockComponent(component.getUniqueId(), nodeType); + } + + protected ComponentInstance componentInstanceException(StorageOperationStatus storageOperationStatus) { + throw new StorageException(storageOperationStatus); + } + + protected Component componentException(StorageOperationStatus storageOperationStatus) { + throw new StorageException(storageOperationStatus); + } + + protected PolicyDefinition storageExceptionPolicyDefinition(StorageOperationStatus storageOperationStatus) { + throw new StorageException(storageOperationStatus); + } + + protected PolicyDefinition componentExceptionPolicyDefinition(ResponseFormat responseFormat) { + throw new ByResponseFormatComponentException(responseFormat); + } + + protected Component componentException(ResponseFormat responseFormat) { + throw new ByResponseFormatComponentException(responseFormat); + } + + protected List<ComponentInstanceProperty> componentInstancePropertyListException(StorageOperationStatus storageOperationStatus) { + throw new StorageException(storageOperationStatus); + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CADIHealthCheck.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CADIHealthCheck.java new file mode 100644 index 0000000000..f94528c64a --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CADIHealthCheck.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl; + +import org.openecomp.sdc.common.api.HealthCheckInfo; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.stereotype.Component; + +import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_CADI; +import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOWN; + +@Component +public class CADIHealthCheck { + + private static CADIHealthCheck cadiHealthCheckInstance = new CADIHealthCheck();; + + private static HealthCheckInfo.HealthCheckStatus isCADIUpOrDown = DOWN; + + private static final Logger log = Logger.getLogger(CADIHealthCheck.class.getName()); + + public static CADIHealthCheck getCADIHealthCheckInstance() { + return cadiHealthCheckInstance; + } + + public void setIsCADIUp(HealthCheckInfo.HealthCheckStatus cadiStatus) { + log.debug("Setting cadiHealthCheckInstance status to: {}", cadiStatus.toString()); + isCADIUpOrDown = cadiStatus; + } + + public static HealthCheckInfo getCADIStatus() { + log.debug("getCADIStatus: Checking whether CADI was up or down while its init."); + String description = "OK"; + if (isCADIUpOrDown == DOWN){ + description = "CADI filter failed initialization"; + } + return new HealthCheckInfo(HC_COMPONENT_CADI, isCADIUpOrDown, null, + description); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilitiesBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilitiesBusinessLogic.java index 63aa08063a..4bfc6509c6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilitiesBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilitiesBusinessLogic.java @@ -20,6 +20,7 @@ import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; +import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; import org.openecomp.sdc.be.components.validation.CapabilitiesValidation; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -131,7 +132,7 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { private Either<Component, ResponseFormat> validateUserAndCapabilities(User user, String componentId, String errorContext, List<CapabilityDefinition> capabilityDefinitions ) { - validateUserExists(user.getUserId(), errorContext, true); + validateUserExists(user.getUserId()); Either<Component, ResponseFormat> componentEither = getComponentDetails(componentId); if (componentEither.isRight()) { return Either.right(componentEither.right().value()); @@ -194,7 +195,7 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { public Either<List<CapabilityDefinition>, ResponseFormat> updateCapabilities(String componentId, List<CapabilityDefinition> capabilityDefinitions, User user, String errorContext, boolean lock) { - validateUserExists(user.getUserId(), errorContext, true); + validateUserExists(user.getUserId()); Either<Component, ResponseFormat> componentEither = getComponentDetails(componentId); if (componentEither.isRight()) { return Either.right(componentEither.right().value()); @@ -371,7 +372,7 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { public Either<CapabilityDefinition, ResponseFormat> getCapability(String componentId, String capabilityToGet, User user, boolean lock) { - validateUserExists(user.getUserId(), GET_CAPABILITIES, true); + validateUserExists(user.getUserId()); Either<Component, ResponseFormat> componentEither = getComponentDetails(componentId); if (componentEither.isRight()) { return Either.right(componentEither.right().value()); @@ -423,7 +424,7 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { public Either<CapabilityDefinition, ResponseFormat> deleteCapability(String componentId, String capabilityIdToDelete, User user, boolean lock) { - validateUserExists(user.getUserId(), DELETE_CAPABILITIES, true); + validateUserExists(user.getUserId()); Either<Component, ResponseFormat> componentEither = getComponentDetails(componentId); if (componentEither.isRight()) { return Either.right(componentEither.right().value()); @@ -546,12 +547,12 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { private Either<Boolean, ResponseFormat> lockComponentResult(boolean lock, Component component, String action) { if (lock) { - Either<Boolean, ResponseFormat> lockResult = lockComponent(component.getUniqueId(), component, action); - if (lockResult.isRight()) { - LOGGER.debug(FAILED_TO_LOCK_COMPONENT_RESPONSE_IS, component.getName(), - lockResult.right().value().getFormattedMessage()); + try { + lockComponent(component.getUniqueId(), component, action); + } catch (ComponentException e){ + LOGGER.debug(FAILED_TO_LOCK_COMPONENT_RESPONSE_IS, component.getName(), e.getMessage()); janusGraphDao.rollback(); - return Either.right(lockResult.right().value()); + throw e; } } return Either.left(true); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java index 56cad89569..d5fe938bca 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java @@ -33,10 +33,16 @@ import org.openecomp.sdc.common.util.GeneralUtility; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; - +import javax.annotation.PreDestroy; import java.io.FileInputStream; import java.io.InputStream; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; @Component("cassandra-health-check") public class CassandraHealthCheck { @@ -50,6 +56,7 @@ public class CassandraHealthCheck { private int HC_FormulaNumber; private SdcSchemaUtils sdcSchemaUtils; + @PostConstruct private void init() { @@ -92,13 +99,8 @@ public class CassandraHealthCheck { log.info("creating cluster for Cassandra Health Check."); //Create cluster from nodes in cassandra configuration - cluster = sdcSchemaUtils.createCluster(); - if (cluster == null) { - log.error("Failure create cassandra cluster."); - return; - } - - Metadata metadata = cluster.getMetadata(); + + Metadata metadata = sdcSchemaUtils.getMetadata(); if (metadata == null) { log.error("Failure get cassandra metadata."); @@ -153,7 +155,8 @@ public class CassandraHealthCheck { } } - + + public boolean getCassandraStatus() { if (GeneralUtility.isEmptyString(localDataCenterName)) { @@ -161,17 +164,19 @@ public class CassandraHealthCheck { return false; } - Cluster cluster = null; + Session session = null; try { - log.info("creating cluster for Cassandra for monitoring."); - cluster = sdcSchemaUtils.createCluster(); - if (cluster == null) { - log.error("Failure create cassandra cluster."); + log.info("creating cluster for Cassandra for monitoring."); + + session = sdcSchemaUtils.connect(); + log.info("The cassandra session is {}", session); + if(session == null){ + log.error("Failed to connect to cassandra "); return false; } - session = cluster.connect(); - Metadata metadata = cluster.getMetadata(); + + Metadata metadata = sdcSchemaUtils.getMetadata(); if (metadata == null) { log.error("Failure get cassandra metadata."); @@ -192,11 +197,18 @@ public class CassandraHealthCheck { return false; } finally { if (session != null) { + log.info("close session for Cassandra for monitoring."); session.close(); } - if (cluster != null) { - cluster.close(); - } + + } + } + + @PreDestroy + public void closeClient() { + if (sdcSchemaUtils!= null) { + sdcSchemaUtils.closeCluster(); } + log.info("** sdcSchemaUtils cluster closed"); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java index 0df7c7066d..0eeb1a7086 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java @@ -38,7 +38,11 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Component; import org.yaml.snakeyaml.Yaml; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; @Component("categoriesImportManager") @@ -80,25 +84,9 @@ public class CategoriesImportManager { List<SubCategoryDefinition> newsubcategories = new ArrayList<>(); List<SubCategoryDefinition> subcategories = category.getSubcategories(); if (subcategories != null) { - for (SubCategoryDefinition subcategory : subcategories) { - Either<SubCategoryDefinition, ResponseFormat> createdSubCategory = createSubCategorieDeo(entry, newcategory, subcategory, nodeTypeSubCategory); - if (createdSubCategory.isRight()) { - return Either.right(createdCategoryRes.right().value()); - } - SubCategoryDefinition newsubcategory = createdSubCategory.left().value(); - List<GroupingDefinition> groupings = subcategory.getGroupings(); - if (groupings != null) { - List<GroupingDefinition> newgroupings = new ArrayList<>(); - for (GroupingDefinition grouping : groupings) { - Either<GroupingDefinition, ResponseFormat> createdGrouping = createGroupingDeo(entry, grouping, subcategory, category, nodeTypeGroup); - if (createdGrouping.isRight()) { - return Either.right(createdCategoryRes.right().value()); - } - newgroupings.add(createdGrouping.left().value()); - } - newsubcategory.setGroupings(newgroupings); - } - newsubcategories.add(newsubcategory); + boolean createdNewSubCategory = isCreatedNewSubCategory(entry, nodeTypeSubCategory, nodeTypeGroup, category, newcategory, newsubcategories, subcategories); + if (!createdNewSubCategory) { + return Either.right(createdCategoryRes.right().value()); } newcategory.setSubcategories(newsubcategories); } @@ -109,12 +97,36 @@ public class CategoriesImportManager { return Either.left(result); } + private boolean isCreatedNewSubCategory(Entry<String, List<CategoryDefinition>> entry, NodeTypeEnum nodeTypeSubCategory, NodeTypeEnum nodeTypeGroup, CategoryDefinition category, CategoryDefinition newcategory, List<SubCategoryDefinition> newsubcategories, List<SubCategoryDefinition> subcategories) { + for (SubCategoryDefinition subcategory : subcategories) { + Either<SubCategoryDefinition, ResponseFormat> createdSubCategory = createSubCategorieDeo(entry, newcategory, subcategory, nodeTypeSubCategory); + if (createdSubCategory.isRight()) { + return false; + } + SubCategoryDefinition newsubcategory = createdSubCategory.left().value(); + List<GroupingDefinition> groupings = subcategory.getGroupings(); + if (groupings != null) { + List<GroupingDefinition> newgroupings = new ArrayList<>(); + for (GroupingDefinition grouping : groupings) { + Either<GroupingDefinition, ResponseFormat> createdGrouping = createGroupingDeo(entry, grouping, subcategory, category, nodeTypeGroup); + if (createdGrouping.isRight()) { + return false; + } + newgroupings.add(createdGrouping.left().value()); + } + newsubcategory.setGroupings(newgroupings); + } + newsubcategories.add(newsubcategory); + } + return true; + } + private Either<GroupingDefinition, ResponseFormat> createGroupingDeo(Map.Entry<String, List<CategoryDefinition>> entry, GroupingDefinition grouping, SubCategoryDefinition subcategory, CategoryDefinition category, NodeTypeEnum nodeTypeGroup) { log.debug("createGroupingDeo: creating grouping {}", grouping); Either<GroupingDefinition, ActionStatus> createdGrouping = elementOperation.createGrouping(subcategory.getUniqueId(), grouping, nodeTypeGroup); if (createdGrouping.isRight()) { - if (ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY.equals(createdGrouping.right().value())) { + if (ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY == createdGrouping.right().value()) { log.debug(" create grouping for {} group {} already exists ", entry.getKey(), grouping.getName()); String groupingId = UniqueIdBuilder.buildGroupingUid(grouping.getUniqueId(), grouping.getNormalizedName()); createdGrouping = elementOperation.getGroupingUniqueForType(nodeTypeGroup, groupingId); @@ -139,7 +151,7 @@ public class CategoriesImportManager { log.debug("createSubCategorieDeo: creating subcategory {}", subcategory); Either<SubCategoryDefinition, ActionStatus> createdSubCategory = elementOperation.createSubCategory(newcategory.getUniqueId(), subcategory, nodeTypeSubCategory); if (createdSubCategory.isRight()) { - if (ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY.equals(createdSubCategory.right().value())) { + if (ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY == createdSubCategory.right().value()) { log.debug(" create subcategory for {} category {} subcategory {} already exists retrieving", entry.getKey(), newcategory.getName(), subcategory.getName()); String subCategoryId = UniqueIdBuilder.buildSubCategoryUid(newcategory.getUniqueId(), subcategory.getNormalizedName()); createdSubCategory = elementOperation.getSubCategory(nodeTypeSubCategory, subCategoryId); @@ -162,7 +174,7 @@ public class CategoriesImportManager { Either<CategoryDefinition, ActionStatus> createdCategory = elementOperation.createCategory(category, nodeTypeCategory); if (createdCategory.isRight()) { log.debug("Failed to create category for {} {} error {}", entry.getKey(), category.getName(), createdCategory.right().value()); - if (!ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS.equals(createdCategory.right().value())) { + if (ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS != createdCategory.right().value()) { return Either.right(componentsUtils.getResponseFormat(createdCategory.right().value())); } else { log.debug("createCategorieDeo: category exists {} retriving.", category); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java index 4dd012fcf7..c3ecda3e03 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java @@ -32,7 +32,11 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.elements.ToscaTypeDataDefinition; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.model.CapabilityTypeDefinition; +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.GroupTypeDefinition; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.normatives.ToscaTypeMetadata; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.api.TypeOperations; @@ -43,7 +47,11 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.yaml.snakeyaml.Yaml; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; import java.util.function.BiFunction; import java.util.function.Consumer; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java index 785b545d7e..83e4cf4c65 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java @@ -22,20 +22,22 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.stream.Collectors; - import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum; 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.generic.GenericTypeBusinessLogic; +import org.openecomp.sdc.be.components.validation.component.ComponentContactIdValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentDescriptionValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentIconValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentNameValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentProjectCodeValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentTagsValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentValidator; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -48,8 +50,8 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.facade.operations.CatalogOperation; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.CapReqDef; import org.openecomp.sdc.be.model.Component; @@ -89,13 +91,31 @@ import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.stream.Collectors; + public abstract class ComponentBusinessLogic extends BaseBusinessLogic { - protected final ArtifactsBusinessLogic artifactsBusinessLogic; + protected ArtifactsBusinessLogic artifactsBusinessLogic; protected final GroupBusinessLogic groupBusinessLogic; - private GenericTypeBusinessLogic genericTypeBusinessLogic; + protected GenericTypeBusinessLogic genericTypeBusinessLogic; + + protected ComponentDescriptionValidator componentDescriptionValidator; + protected ComponentProjectCodeValidator componentProjectCodeValidator; + + protected CatalogOperation catalogOperations; + protected ComponentIconValidator componentIconValidator; + + protected ComponentValidator componentValidator; + protected ComponentTagsValidator componentTagsValidator; + protected ComponentNameValidator componentNameValidator; + protected ComponentContactIdValidator componentContactIdValidator; public ComponentBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, @@ -105,13 +125,53 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsBusinessLogic artifactsBusinessLogic, - ArtifactsOperations artifactToscaOperation) { + ArtifactsOperations artifactToscaOperation, + ComponentContactIdValidator componentContactIdValidator, + ComponentNameValidator componentNameValidator, + ComponentTagsValidator componentTagsValidator, + ComponentValidator componentValidator, + ComponentIconValidator componentIconValidator, + ComponentProjectCodeValidator componentProjectCodeValidator, + ComponentDescriptionValidator componentDescriptionValidator){ + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); this.artifactsBusinessLogic = artifactsBusinessLogic; this.groupBusinessLogic = groupBusinessLogic; + this.componentContactIdValidator = componentContactIdValidator; + this.componentNameValidator = componentNameValidator; + this.componentTagsValidator = componentTagsValidator; + this.componentValidator = componentValidator; + this.componentIconValidator = componentIconValidator; + this.componentProjectCodeValidator = componentProjectCodeValidator; + this.componentDescriptionValidator = componentDescriptionValidator; + } + + public void setComponentDescriptionValidator(ComponentDescriptionValidator componentDescriptionValidator) { + this.componentDescriptionValidator = componentDescriptionValidator; + } + + public void setComponentProjectCodeValidator(ComponentProjectCodeValidator componentProjectCodeValidator) { + this.componentProjectCodeValidator = componentProjectCodeValidator; + } + + public void setComponentIconValidator(ComponentIconValidator componentIconValidator) { + this.componentIconValidator = componentIconValidator; } + public void setComponentContactIdValidator(ComponentContactIdValidator componentContactIdValidator) { + this.componentContactIdValidator = componentContactIdValidator; + } + + public void setComponentTagsValidator(ComponentTagsValidator componentTagsValidator) { + this.componentTagsValidator = componentTagsValidator; + } + + public void setComponentNameValidator(ComponentNameValidator componentNameValidator) { + this.componentNameValidator = componentNameValidator; + } + + @Autowired public void setGenericTypeBusinessLogic(GenericTypeBusinessLogic genericTypeBusinessLogic) { this.genericTypeBusinessLogic = genericTypeBusinessLogic; @@ -135,12 +195,12 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { */ public abstract Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId, List<String> dataParamsToReturn); - protected User validateUser(User user, String ecompErrorContext, Component component, AuditingActionEnum auditAction, boolean inTransaction) { + User validateUser(User user, String ecompErrorContext, Component component, AuditingActionEnum auditAction, boolean inTransaction) { User validatedUser; ResponseFormat responseFormat; try { validateUserNotEmpty(user, ecompErrorContext); - validatedUser = validateUserExists(user, ecompErrorContext, inTransaction); + validatedUser = validateUserExists(user); } catch(ByActionStatusComponentException e){ if(e.getActionStatus() == ActionStatus.MISSING_INFORMATION){ user.setUserId("UNKNOWN"); @@ -179,7 +239,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { String commentStr = null; String distrStatus = null; ComponentTypeEnum componentType = component.getComponentType(); - if (componentType.equals(ComponentTypeEnum.SERVICE)) { + if (componentType == ComponentTypeEnum.SERVICE) { distrStatus = ((ServiceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getDistributionStatus(); commentStr = comment; } @@ -189,119 +249,6 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { commentStr, null, null); } - protected void validateComponentName(User user, Component component, AuditingActionEnum actionEnum) { - ComponentTypeEnum type = component.getComponentType(); - String componentName = component.getName(); - if (!ValidationUtils.validateStringNotEmpty(componentName)) { - log.debug("component name is empty"); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, type.getValue()); - componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); - throw new ByActionStatusComponentException(ActionStatus.MISSING_COMPONENT_NAME, type.getValue()); - } - - if (!ValidationUtils.validateComponentNameLength(componentName)) { - log.debug("Component name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); - componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT,type.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); - } - - if (!validateTagPattern(componentName)) { - log.debug("Component name {} has invalid format", componentName); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPONENT_NAME, type.getValue()); - componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); - throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, type.getValue()); - } - component.setNormalizedName(ValidationUtils.normaliseComponentName(componentName)); - component.setSystemName(ValidationUtils.convertToSystemName(componentName)); - } - - protected void validateDescriptionAndCleanup(User user, Component component, AuditingActionEnum actionEnum) { - ComponentTypeEnum type = component.getComponentType(); - String description = component.getDescription(); - if (!ValidationUtils.validateStringNotEmpty(description)) { - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_DESCRIPTION, type.getValue()); - componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_DESCRIPTION, type.getValue()); - } - - description = cleanUpText(description); - try { - validateComponentDescription(description, type); - } catch(ByActionStatusComponentException e){ - ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); - componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, type); - throw e; - } catch(ByResponseFormatComponentException e){ - ResponseFormat responseFormat = e.getResponseFormat(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, type); - throw e; - } - component.setDescription(description); - } - - private void validateComponentDescription(String description, ComponentTypeEnum type) { - if (description != null) { - if (!ValidationUtils.validateDescriptionLength(description)) { - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); - } - - if (!ValidationUtils.validateIsEnglish(description)) { - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_DESCRIPTION, type.getValue()); - } - } - } - - protected Either<Boolean, ResponseFormat> validateComponentNameUnique(User user, Component component, AuditingActionEnum actionEnum) { - log.debug("validate component name uniqueness for: {}", component.getName()); - ComponentTypeEnum type = component.getComponentType(); - ResourceTypeEnum resourceType = null; - if(component instanceof Resource){ - resourceType = ((Resource)component).getResourceType(); - } - Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameExists(component.getName(), resourceType, type); - - if (dataModelResponse.isLeft()) { - if ( !dataModelResponse.left().value()) { - return Either.left(true); - } else { - log.info("Component with name {} already exists", component.getName()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, type.getValue(), component.getName()); - componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); - return Either.right(errorResponse); - } - } - BeEcompErrorManager.getInstance().logBeSystemError("validateComponentNameUnique"); - log.debug("Error while validateComponentNameUnique for component: {}", component.getName()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); - return Either.right(errorResponse); - } - - protected void validateContactId(User user, Component component, AuditingActionEnum actionEnum) { - log.debug("validate component contactId"); - ComponentTypeEnum type = component.getComponentType(); - String contactId = component.getContactId(); - - if (!ValidationUtils.validateStringNotEmpty(contactId)) { - log.info("contact is missing."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT, type.getValue()); - componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CONTACT, type.getValue()); - } - validateContactId(contactId, user, component, actionEnum, type); - } - - private void validateContactId(String contactId, User user, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum type) { - if (contactId != null && !ValidationUtils.validateContactId(contactId)) { - log.info("contact is invalid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, type.getValue()); - componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_CONTACT, type.getValue()); - } - } - - public Either<Boolean, ResponseFormat> validateConformanceLevel(String componentUuid, ComponentTypeEnum componentTypeEnum, String userId) { log.trace("validate conformance level"); @@ -311,7 +258,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { return Either.right(errorResponse); } - validateUserExists(userId, "validateConformanceLevel", false); + validateUserExists(userId); Either<ComponentMetadataData, StorageOperationStatus> eitherComponent = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, null); if (eitherComponent.isRight()) { @@ -342,149 +289,6 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { return Either.left(result); } - protected void validateIcon(User user, Component component, AuditingActionEnum actionEnum) { - log.debug("validate Icon"); - ComponentTypeEnum type = component.getComponentType(); - String icon = component.getIcon(); - if (!ValidationUtils.validateStringNotEmpty(icon)) { - log.info("icon is missing."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_ICON, type.getValue()); - componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_ICON, type.getValue()); - } - try { - validateIcon(icon, type); - } catch(ByActionStatusComponentException e){ - ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); - componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, type); - throw e; - } catch(ByResponseFormatComponentException e){ - ResponseFormat responseFormat = e.getResponseFormat(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, type); - throw e; - } - } - - private void validateIcon(String icon, ComponentTypeEnum type) { - if (icon != null) { - if (!ValidationUtils.validateIconLength(icon)) { - log.debug("icon exceeds max length"); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH); - } - - if (!ValidationUtils.validateIcon(icon)) { - log.info("icon is invalid."); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_ICON, type.getValue()); - } - } - } - - protected void validateTagsListAndRemoveDuplicates(User user, Component component, AuditingActionEnum actionEnum) { - List<String> tagsList = component.getTags(); - try { - validateComponentTags(tagsList, component.getName(), component.getComponentType(), user, component, actionEnum); - } catch(ByActionStatusComponentException e){ - ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); - componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, component.getComponentType()); - throw e; - } catch(ByResponseFormatComponentException e){ - ResponseFormat responseFormat = e.getResponseFormat(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, component.getComponentType()); - throw e; - } - ValidationUtils.removeDuplicateFromList(tagsList); - } - - protected void validateComponentTags(List<String> tags, String name, ComponentTypeEnum componentType, User user, Component component, AuditingActionEnum action) { - log.debug("validate component tags"); - boolean includesComponentName = false; - int tagListSize = 0; - ResponseFormat responseFormat; - if (tags != null && !tags.isEmpty()) { - for (String tag : tags) { - if (!ValidationUtils.validateTagLength(tag)) { - log.debug("tag length exceeds limit {}", ValidationUtils.TAG_MAX_LENGTH); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH); - componentsUtils.auditComponentAdmin(responseFormat, user, component, action, componentType); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH); - } - if (validateTagPattern(tag)) { - if (!includesComponentName) { - includesComponentName = name.equals(tag); - } - } else { - log.debug("invalid tag {}", tag); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_FIELD_FORMAT, componentType.getValue(), TAG_FIELD_LABEL); - componentsUtils.auditComponentAdmin(responseFormat, user, component, action, componentType); - throw new ByActionStatusComponentException(ActionStatus.INVALID_FIELD_FORMAT, componentType.getValue(), TAG_FIELD_LABEL); - } - tagListSize += tag.length() + 1; - } - if (tagListSize > 0) { - tagListSize--; - } - - if (!includesComponentName) { - log.debug("tags must include component name"); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME); - componentsUtils.auditComponentAdmin(responseFormat, user, component, action, componentType); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME); - } - if (!ValidationUtils.validateTagListLength(tagListSize)) { - log.debug("overall tags length exceeds limit {}", ValidationUtils.TAG_LIST_MAX_LENGTH); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); - componentsUtils.auditComponentAdmin(responseFormat, user, component, action, componentType); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); - } - } else { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_TAGS); - componentsUtils.auditComponentAdmin(responseFormat, user, component, action, componentType); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_TAGS); - } - } - - protected boolean validateTagPattern(String tag) { - return ValidationUtils.validateComponentNamePattern(tag); - } - - protected Either<Boolean, ResponseFormat> validateProjectCode(User user, Component component, AuditingActionEnum actionEnum) { - if (ComponentTypeEnum.RESOURCE.equals(component.getComponentType())) { - return Either.left(true); - } - log.debug("validate ProjectCode name "); - String projectCode = component.getProjectCode(); - - if (!ValidationUtils.validateStringNotEmpty(projectCode)) { - log.info("projectCode is missing."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_PROJECT_CODE); - componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, component.getComponentType(), - ResourceVersionInfo.newBuilder() - .build()); - return Either.right(errorResponse); - } - - Either<Boolean, ResponseFormat> validateProjectCodeResponse = validateProjectCode(projectCode); - if (validateProjectCodeResponse.isRight()) { - ResponseFormat responseFormat = validateProjectCodeResponse.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, component.getComponentType(), - ResourceVersionInfo.newBuilder() - .build()); - } - return validateProjectCodeResponse; - - } - - private Either<Boolean, ResponseFormat> validateProjectCode(String projectCode) { - if (projectCode != null) { - if (!ValidationUtils.validateProjectCode(projectCode)) { - log.info("projectCode is not valid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROJECT_CODE); - return Either.right(errorResponse); - } - return Either.left(true); - } - return Either.left(false); - } protected void checkComponentFieldsForOverrideAttempt(Component component) { if (component.getLifecycleState() != null) { @@ -520,46 +324,28 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { } } - protected void validateComponentFieldsBeforeCreate(User user, Component component, AuditingActionEnum actionEnum) { - // validate component name uniqueness - log.debug("validate component name "); - validateComponentName(user, component, actionEnum); - // validate description - log.debug("validate description"); - validateDescriptionAndCleanup(user, component, actionEnum); - // validate tags - log.debug("validate tags"); - validateTagsListAndRemoveDuplicates(user, component, actionEnum); - // validate contact info - log.debug("validate contact info"); - validateContactId(user, component, actionEnum); - // validate icon - log.debug("validate icon"); - validateIcon(user, component, actionEnum); - } - - public Either<CapReqDef, ResponseFormat> getRequirementsAndCapabilities(String componentId, ComponentTypeEnum componentTypeEnum, String userId) { + public CapReqDef getRequirementsAndCapabilities(String componentId, ComponentTypeEnum componentTypeEnum, String userId) { - validateUserExists(userId, "create Component Instance", false); - Either<CapReqDef, ResponseFormat> eitherRet = null; + validateUserExists(userId); ComponentParametersView filter = new ComponentParametersView(true); filter.setIgnoreCapabilities(false); filter.setIgnoreRequirements(false); filter.setIgnoreComponentInstances(false); - Either<Component, ResponseFormat> eitherComponent = validateComponentExists(componentId, componentTypeEnum, filter); - if (eitherComponent.isLeft()) { - eitherRet = Either.left(new CapReqDef(eitherComponent.left().value().getRequirements(), eitherComponent.left().value().getCapabilities())); - } else { + + try { + Component component = validateComponentExists(componentId, componentTypeEnum, filter); + return new CapReqDef(component.getRequirements(), component.getCapabilities()); + }catch (ComponentException e){ BeEcompErrorManager.getInstance().logBeComponentMissingError("getRequirementsAndCapabilities", componentTypeEnum.getValue(), componentId); - eitherRet = Either.right(eitherComponent.right().value()); + throwComponentException(e.getResponseFormat()); } - return eitherRet; + return null; } public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponents(boolean isAbstractAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids, String userId) { try{ - validateUserExists(userId, "get Latest Version Not Abstract Components", false); + validateUserExists(userId); List<Component> result = new ArrayList<>(); List<String> componentsUidToFetch = new ArrayList<>(); componentsUidToFetch.addAll(componentUids); @@ -602,12 +388,12 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { ResponseFormat responseFormat = null; try{ - validateUserExists(userId, "get Latest Version Not Abstract Components", false); + validateUserExists(userId); Boolean isHighest = isHighest(highestFilter); Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractMetadataOnly(isAbstractAbstract, componentTypeEnum, internalComponentType); if (nonCheckoutCompResponse.isLeft()) { - log.debug("Retrived Resource successfully."); + log.debug("Retrieved Resource successfully."); return Either.left(nonCheckoutCompResponse.left().value()); } responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())); @@ -643,27 +429,30 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { component.setToscaArtifacts(artifactMap); } - public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock) { - return populateToscaArtifacts(component, user, isInCertificationRequest, inTransaction, shouldLock, true); + public Either<ArtifactDefinition, Operation> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock) { + return populateToscaArtifacts(component, user, isInCertificationRequest, inTransaction, shouldLock, true, true); + } + + public Either<ArtifactDefinition, Operation> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock, boolean retrieveResource) { + return populateToscaArtifacts(component, user, isInCertificationRequest, inTransaction, shouldLock, true, retrieveResource); } - public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock, boolean fetchTemplatesFromDB) { - Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaFullElement(component.getUniqueId()); - if ( toscaElement.isRight() ){ - ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(toscaElement.right().value(), component.getComponentType())); - return Either.right(response); + private Either<ArtifactDefinition, Operation> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock, boolean fetchTemplatesFromDB, boolean retrieveResource) { + if (retrieveResource) { + Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaFullElement(component.getUniqueId()); + if ( toscaElement.isRight() ){ + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(toscaElement.right().value(), component.getComponentType())); + } + component = toscaElement.left().value(); } - component = toscaElement.left().value(); - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaRes = null; + + Either<ArtifactDefinition, Operation> generateToscaRes = null; if (component.getToscaArtifacts() != null && !component.getToscaArtifacts().isEmpty()) { ArtifactDefinition toscaArtifact = component.getToscaArtifacts().values().stream() .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())) .findAny().get(); generateToscaRes = saveToscaArtifactPayload(toscaArtifact, component, user, isInCertificationRequest, shouldLock, inTransaction, fetchTemplatesFromDB); - if (generateToscaRes.isRight()) { - return generateToscaRes; - } - toscaArtifact = generateToscaRes.left().value().left().value(); + toscaArtifact = generateToscaRes.left().value(); component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact); if(!isAbstractResource(component)){ toscaArtifact = component.getToscaArtifacts().values().stream() @@ -673,7 +462,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { if (generateToscaRes.isRight()) { return generateToscaRes; } - toscaArtifact = generateToscaRes.left().value().left().value(); + toscaArtifact = generateToscaRes.left().value(); component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact); } } @@ -684,18 +473,17 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource)component).isAbstract(); } - public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> saveToscaArtifactPayload(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest, boolean shouldLock, - boolean inTransaction, boolean fetchTemplatesFromDB) { + private Either<ArtifactDefinition, Operation> saveToscaArtifactPayload(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest, boolean shouldLock, + boolean inTransaction, boolean fetchTemplatesFromDB) { return artifactsBusinessLogic.generateAndSaveToscaArtifact(artifactDefinition, component, user, isInCertificationRequest, shouldLock, inTransaction, fetchTemplatesFromDB); } - public Either<ImmutablePair<String, byte[]>, ResponseFormat> getToscaModelByComponentUuid(ComponentTypeEnum componentType, String uuid, ResourceCommonInfo resourceCommonInfo) { + public ImmutablePair<String, byte[]> getToscaModelByComponentUuid(ComponentTypeEnum componentType, String uuid, ResourceCommonInfo resourceCommonInfo) { Either<List<Component>, StorageOperationStatus> latestVersionEither = toscaOperationFacade.getComponentListByUuid(uuid, null); if (latestVersionEither.isRight()) { - ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentType)); - return Either.right(response); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentType)); } List<Component> components = latestVersionEither.left().value(); @@ -706,14 +494,13 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { } if(component == null){ - ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType)); - return Either.right(response); + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType))); } resourceCommonInfo.setResourceName(component.getName()); // TODO remove after migration - handle artifact not found(no // placeholder) if (null == component.getToscaArtifacts() || component.getToscaArtifacts().isEmpty()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ArtifactTypeEnum.TOSCA_CSAR.name())); + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ArtifactTypeEnum.TOSCA_CSAR.name())); } ArtifactDefinition csarArtifact = component.getToscaArtifacts().values().stream() .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) @@ -736,6 +523,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { return markResourceToDelete; } else { log.debug("Component {} of type {} was marked as deleted", uniqueId, componentType); + updateCatalog(component, ChangeTypeEnum.DELETE); return StorageOperationStatus.OK; } } @@ -744,7 +532,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { String descriptionUpdated = updatedComponent.getDescription(); String descriptionCurrent = currentComponent.getDescription(); if (descriptionUpdated != null && !descriptionCurrent.equals(descriptionUpdated)) { - validateDescriptionAndCleanup(user, updatedComponent, auditingAction); + componentDescriptionValidator.validateAndCorrectField(user, updatedComponent, auditingAction); currentComponent.setDescription(updatedComponent.getDescription()); } return Either.left(true); @@ -754,9 +542,10 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { String projectCodeUpdated = updatedComponent.getProjectCode(); String projectCodeCurrent = currentComponent.getProjectCode(); if (projectCodeUpdated != null && !projectCodeCurrent.equals(projectCodeUpdated)) { - Either<Boolean, ResponseFormat> validatProjectCodeResponse = validateProjectCode(user, updatedComponent, null); - if (validatProjectCodeResponse.isRight()) { - ResponseFormat errorRespons = validatProjectCodeResponse.right().value(); + try { + componentProjectCodeValidator.validateAndCorrectField(user, updatedComponent, null); + } catch (ComponentException exp) { + ResponseFormat errorRespons = exp.getResponseFormat(); return Either.right(errorRespons); } currentComponent.setProjectCode(updatedComponent.getProjectCode()); @@ -769,7 +558,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { String iconCurrent = currentComponent.getIcon(); if (iconUpdated != null && !iconCurrent.equals(iconUpdated)) { if (!hasBeenCertified) { - validateIcon(user, updatedComponent, null); + componentIconValidator.validateAndCorrectField(user, updatedComponent, null); currentComponent.setIcon(updatedComponent.getIcon()); } else { log.info("icon {} cannot be updated once the component has been certified once.", iconUpdated); @@ -800,7 +589,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { List<ArtifactDefinition> artifacts = new ArrayList<>(); Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse = artifactToscaOperation.getArtifacts(parentId); if (artifactsResponse.isRight()) { - if (!artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + if (artifactsResponse.right().value() != StorageOperationStatus.NOT_FOUND) { log.debug("failed to retrieve artifacts for {} {}", parentType, parentId); return Either.right(artifactsResponse.right().value()); } @@ -821,7 +610,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { public Either<UiComponentDataTransfer, ResponseFormat> getComponentDataFilteredByParams(String componentId, User user, List<String> dataParamsToReturn) { if (user != null) { - validateUserExists(user, "Get Component by filtered by ui params", false); + validateUserExists(user); } UiComponentDataTransfer result = new UiComponentDataTransfer(); @@ -885,7 +674,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { response = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); } if (userId != null && response == null) { - validateUserExists(userId, "Get filtered component instance properties", false); + validateUserExists(userId); } if(response == null){ getResourceRes = toscaOperationFacade.getToscaElement(componentId); @@ -920,18 +709,12 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { for(ComponentInstance instance : filteredInstances){ if(component.getComponentInstancesProperties()!=null &&component.getComponentInstancesProperties().containsKey(instance.getUniqueId())){ List<IComponentInstanceConnectedElement> currProperties = getFilteredComponentInstanceProperties(component.getComponentInstancesProperties().get(instance.getUniqueId()), propertyNameFragment, searchByFragment); - if(CollectionUtils.isNotEmpty(currProperties)){ - filteredProperties.put(instance.getUniqueId(), currProperties); - } + setFilteredProperties(filteredProperties, instance, currProperties); } if(component.getComponentInstancesInputs()!=null && component.getComponentInstancesInputs().containsKey(instance.getUniqueId())){ List<IComponentInstanceConnectedElement> currInputs = getFilteredComponentInstanceInputs(component.getComponentInstancesInputs().get(instance.getUniqueId()), propertyNameFragment, searchByFragment); if(CollectionUtils.isNotEmpty(currInputs)){ - if(filteredProperties.get(instance.getUniqueId())!=null){ - filteredProperties.get(instance.getUniqueId()).addAll(currInputs); - } else { - filteredProperties.put(instance.getUniqueId(), currInputs); - } + checkFilteredProperties(filteredProperties, instance, currInputs); } } } @@ -939,6 +722,20 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { return result; } + private void setFilteredProperties(Map<String, List<IComponentInstanceConnectedElement>> filteredProperties, ComponentInstance instance, List<IComponentInstanceConnectedElement> currProperties) { + if(CollectionUtils.isNotEmpty(currProperties)){ + filteredProperties.put(instance.getUniqueId(), currProperties); + } + } + + private void checkFilteredProperties(Map<String, List<IComponentInstanceConnectedElement>> filteredProperties, ComponentInstance instance, List<IComponentInstanceConnectedElement> currInputs) { + if(filteredProperties.get(instance.getUniqueId())!=null){ + filteredProperties.get(instance.getUniqueId()).addAll(currInputs); + } else { + filteredProperties.put(instance.getUniqueId(), currInputs); + } + } + private List<IComponentInstanceConnectedElement> getFilteredComponentInstanceInputs(List<ComponentInstanceInput> inputs, String propertyNameFragment, boolean searchByFragment) { return inputs.stream().filter(i -> isMatchingInput(i, propertyNameFragment, searchByFragment)).collect(Collectors.toList()); } @@ -996,18 +793,23 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { dataTypeProperties = currentProperty.getProperties(); if(CollectionUtils.isNotEmpty(dataTypeProperties)){ - for(PropertyDefinition prop : dataTypeProperties){ - if(isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)){ - return true; - } + if (isMatchingComplexProperty(propertyNameFragment, searchByFragment, dataTypeProperties)){ + return true; } } dataTypeProperties = currentProperty.getDerivedFrom().getProperties(); if(CollectionUtils.isNotEmpty(dataTypeProperties)){ - for(PropertyDefinition prop : dataTypeProperties){ - if(isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)){ - return true; - } + if (isMatchingComplexProperty(propertyNameFragment, searchByFragment, dataTypeProperties)){ + return true; + } + } + return false; + } + + private boolean isMatchingComplexProperty(String propertyNameFragment, boolean searchByFragment, List<PropertyDefinition> dataTypeProperties) { + for(PropertyDefinition prop : dataTypeProperties){ + if(isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)){ + return true; } } return false; @@ -1120,22 +922,34 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { return isMatchingType; } - String cleanUpText(String text){ - text = ValidationUtils.removeNoneUtf8Chars(text); - text = ValidationUtils.normaliseWhitespace(text); - text = ValidationUtils.stripOctets(text); - text = ValidationUtils.removeHtmlTagsOnly(text); - return text; - } - public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) { //general implementation. Must be error for service, VF . In ResourceBuisnessLogic exist override return Either.right(ActionStatus.GENERAL_ERROR); } + protected Either<Component, ResponseFormat> updateCatalog(Component component, ChangeTypeEnum changeStatus){ + log.debug("update Catalog start with Component Type {} And Componet Name {} with change status {}", component.getComponentType().name(), component.getName(), changeStatus.name()); + ActionStatus status = catalogOperations.updateCatalog(changeStatus,component); + if(status != ActionStatus.OK){ + return Either.right( componentsUtils.getResponseFormat(status)); + } + + return Either.left(component); + } + + public CatalogOperation getCatalogOperations() { + return catalogOperations; + } + + @Autowired + public void setCatalogOperations(CatalogOperation catalogOperations) { + this.catalogOperations = catalogOperations; + } + public List<GroupDefinition> throwComponentException(ResponseFormat responseFormat) { throw new ByResponseFormatComponentException(responseFormat); } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogicProvider.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogicProvider.java index 2c516cce57..5f1e6a100f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogicProvider.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogicProvider.java @@ -27,8 +27,6 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.springframework.stereotype.Component; -import javax.inject.Inject; - @Component public class ComponentBusinessLogicProvider { @@ -36,7 +34,6 @@ public class ComponentBusinessLogicProvider { private final ServiceBusinessLogic serviceBusinessLogic; private final ProductBusinessLogic productBusinessLogic; - @Inject public ComponentBusinessLogicProvider(ResourceBusinessLogic resourceBusinessLogic, ServiceBusinessLogic serviceBusinessLogic, ProductBusinessLogic productBusinessLogic) { this.resourceBusinessLogic = resourceBusinessLogic; this.serviceBusinessLogic = serviceBusinessLogic; @@ -54,7 +51,7 @@ public class ComponentBusinessLogicProvider { return resourceBusinessLogic; default: BeEcompErrorManager.getInstance().logBeSystemError("getComponentBL"); - throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT_PARAM, componentTypeEnum.getValue()); + throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT, componentTypeEnum.getValue()); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java index 040c460ffc..51eb22d527 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java @@ -26,6 +26,9 @@ import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; +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.instance.ComponentInstanceChangeOperationOrchestrator; import org.openecomp.sdc.be.components.impl.utils.DirectivesUtils; import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceMergeDataBusinessLogic; @@ -34,23 +37,24 @@ import org.openecomp.sdc.be.components.utils.PropertiesUtils; import org.openecomp.sdc.be.components.validation.ComponentValidations; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; +import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; -import org.openecomp.sdc.be.datamodel.utils.PropertyValueConstraintValidationUtil; +import org.openecomp.sdc.be.datamodel.utils.ContainerInstanceTypesData; import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition; import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GetPolicyValueDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ForwardingPathUtils; import org.openecomp.sdc.be.impl.ServiceFilterUtils; import org.openecomp.sdc.be.info.CreateAndAssotiateInfo; @@ -69,7 +73,6 @@ import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.PolicyDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames; import org.openecomp.sdc.be.model.RelationshipInfo; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.RequirementDefinition; @@ -82,12 +85,13 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeFilterOperation; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; -import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation; +import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation; import org.openecomp.sdc.be.model.operations.api.IGroupOperation; import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; @@ -142,12 +146,12 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { private static final String FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS = "Failed to copy the component instance to the canvas"; private static final String COPY_COMPONENT_INSTANCE_OK = "Copy component instance OK"; - private final IComponentInstanceOperation componentInstanceOperation; - private final ArtifactsBusinessLogic artifactBusinessLogic; - private final ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL; - private final ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator; - private final ForwardingPathOperation forwardingPathOperation; - private final NodeFilterOperation serviceFilterOperation; + private ComponentInstanceOperation componentInstanceOperation; + private ArtifactsBusinessLogic artifactBusinessLogic; + private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL; + private ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator; + private ForwardingPathOperation forwardingPathOperation; + private NodeFilterOperation serviceFilterOperation; @Autowired public ComponentInstanceBusinessLogic(IElementOperation elementDao, @@ -156,7 +160,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - IComponentInstanceOperation componentInstanceOperation, ArtifactsBusinessLogic artifactBusinessLogic, + ComponentInstanceOperation componentInstanceOperation, ArtifactsBusinessLogic artifactBusinessLogic, ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL, ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator, ForwardingPathOperation forwardingPathOperation, NodeFilterOperation serviceFilterOperation, @@ -171,10 +175,14 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { this.serviceFilterOperation = serviceFilterOperation; } - public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, - String containerComponentId, String userId, ComponentInstance resourceInstance) { - return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, - true); + @Autowired + private CompositionBusinessLogic compositionBusinessLogic; + + @Autowired + private ContainerInstanceTypesData containerInstanceTypesData; + + public ComponentInstance createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) { + return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true); } public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){ @@ -191,23 +199,27 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { if (ciPropList != null && !ciPropList.isEmpty()) { for(ComponentInstanceProperty prop: ciPropList){ List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues(); - if(inputsValues != null && !inputsValues.isEmpty()){ - for(GetInputValueDataDefinition inputData: inputsValues){ - if(isGetInputValueForInput(inputData, inputId)){ - prop.setComponentInstanceId(s); - prop.setComponentInstanceName(ciName); - resList.add(prop); - break; - } - } - } - + addCompInstanceProperty(s, ciName, prop, inputsValues, inputId, resList); } } } }); } return resList; + + } + + private void addCompInstanceProperty(String s, String ciName, ComponentInstanceProperty prop, List<GetInputValueDataDefinition> inputsValues, String inputId, List<ComponentInstanceProperty> resList) { + if(inputsValues != null && !inputsValues.isEmpty()){ + for(GetInputValueDataDefinition inputData: inputsValues){ + if(isGetInputValueForInput(inputData, inputId)){ + prop.setComponentInstanceId(s); + prop.setComponentInstanceName(ciName); + resList.add(prop); + break; + } + } + } } public Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicyId(Component component, @@ -286,16 +298,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { if (ciPropList != null && !ciPropList.isEmpty()) { for(ComponentInstanceInput prop: ciPropList){ List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues(); - if(inputsValues != null && !inputsValues.isEmpty()){ - for(GetInputValueDataDefinition inputData: inputsValues){ - if(isGetInputValueForInput(inputData, inputId)){ - prop.setComponentInstanceId(s); - prop.setComponentInstanceName(ciName); - resList.add(prop); - break; - } - } - } + addCompInstanceInput(s, ciName, prop, inputsValues, inputId, resList); } } @@ -303,90 +306,190 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { }); } return resList; + } - public Either<ComponentInstance, ResponseFormat> createComponentInstance( - String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) { + private void addCompInstanceInput(String s, String ciName, ComponentInstanceInput prop, List<GetInputValueDataDefinition> inputsValues, String inputId, List<ComponentInstanceInput> resList) { + if(inputsValues != null && !inputsValues.isEmpty()){ + for(GetInputValueDataDefinition inputData: inputsValues){ + if(isGetInputValueForInput(inputData, inputId)){ + prop.setComponentInstanceId(s); + prop.setComponentInstanceName(ciName); + resList.add(prop); + break; + } + } + } + } + + public ComponentInstance createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) { Component origComponent = null; - Either<ComponentInstance, ResponseFormat> resultOp = null; - User user = null; + User user; org.openecomp.sdc.be.model.Component containerComponent = null; ComponentTypeEnum containerComponentType; - try { - user = validateUserExists(userId, "create Component Instance", inTransaction); - - Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class); - if (validateValidJson.isRight()) { - return Either.right(validateValidJson.right().value()); - } - - Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - return Either.right(validateComponentType.right().value()); - } else { - containerComponentType = validateComponentType.left().value(); - } - - Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } else { - containerComponent = validateComponentExists.left().value(); - } + user = validateUserExists(userId); + validateUserNotEmpty(user, "Create component instance"); + validateJsonBody(resourceInstance, ComponentInstance.class); + containerComponentType = validateComponentType(containerComponentParam); + containerComponent = validateComponentExists(containerComponentId, containerComponentType, null); if (ModelConverter.isAtomicComponent(containerComponent)) { log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType())); + throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()); } - Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } + validateCanWorkOnComponent(containerComponent, userId); if (resourceInstance != null && containerComponentType != null) { OriginTypeEnum originType = resourceInstance.getOriginType(); + validateInstanceName(resourceInstance); if (originType == OriginTypeEnum.ServiceProxy) { + Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy"); - if (serviceProxyOrigin.isRight()) { - log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()))); + if (isServiceProxyOrigin(serviceProxyOrigin)) { + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())); } origComponent = serviceProxyOrigin.left().value(); StorageOperationStatus fillProxyRes = fillProxyInstanceData(resourceInstance, origComponent); - if (fillProxyRes != StorageOperationStatus.OK) { - log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes))); - - } - - } else { - Either<Component, ResponseFormat> getOriginComponentRes = getAndValidateOriginComponentOfComponentInstance(containerComponentType, resourceInstance); - - if (getOriginComponentRes.isRight()) { - return Either.right(getOriginComponentRes.right().value()); - } else { - origComponent = getOriginComponentRes.left().value(); + if (isFillProxyRes(fillProxyRes)) { + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes)); } } - } - if (needLock) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); + else { + origComponent = getAndValidateOriginComponentOfComponentInstance(containerComponent, resourceInstance); } + validateOriginAndResourceInstanceTypes(containerComponent, origComponent, originType); + validateResourceInstanceState(containerComponent, origComponent); + overrideFields(origComponent, resourceInstance); + compositionBusinessLogic.validateAndSetDefaultCoordinates(resourceInstance); } - log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH); - resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user); - return resultOp; + return createComponent(needLock, containerComponent,origComponent, resourceInstance, user); - } finally { + }catch (ComponentException e){ + throw e; + } + } + + private ComponentInstance createComponent(boolean needLock, Component containerComponent, Component origComponent, ComponentInstance resourceInstance, User user) { + + boolean failed = false; + try { + + ComponentInstance lockComponent = isNeedLock(needLock, containerComponent); + if (lockComponent != null) { + return lockComponent; + } + log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH); + return createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user); + }catch (ComponentException e){ + failed = true; + throw e; + }finally { if (needLock) - unlockComponent(resultOp, containerComponent); + unlockComponent(failed, containerComponent); + } + } + + private void overrideFields(Component origComponent, ComponentInstance resourceInstance) { + resourceInstance.setComponentVersion(origComponent.getVersion()); + resourceInstance.setIcon(origComponent.getIcon()); + } + + private void validateInstanceName(ComponentInstance resourceInstance) { + + String resourceInstanceName = resourceInstance.getName(); + if (StringUtils.isEmpty(resourceInstanceName)) { + log.debug("ComponentInstance name is empty"); + throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName()); + } + + if (!ValidationUtils.validateComponentNameLength(resourceInstanceName)) { + log.debug("ComponentInstance name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH); + throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName()); + } + + if (!ValidationUtils.validateComponentNamePattern(resourceInstanceName)) { + log.debug("ComponentInstance name {} has invalid format", resourceInstanceName); + throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName()); + } + } + + private void validateResourceInstanceState(Component containerComponent, Component origComponent) { + if (origComponent.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT){ + throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE, + containerComponent.getComponentType().getValue(), origComponent.getLifecycleState().toString()); + } + } + + private void validateOriginAndResourceInstanceTypes(Component containerComponent, Component origComponent, OriginTypeEnum originType) { + ResourceTypeEnum resourceType = null; + ResourceTypeEnum convertedOriginType; + resourceType = getResourceTypeEnumFromOriginComponent(origComponent, resourceType); + validateOriginType(originType, resourceType); + validateOriginComponentIsValidForContainer(containerComponent, resourceType); + } + + private void validateOriginComponentIsValidForContainer(Component containerComponent, ResourceTypeEnum resourceType) { + switch (containerComponent.getComponentType()) { + case SERVICE: + if (!containerInstanceTypesData.getServiceContainerList().contains((resourceType))) { + throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE, + containerComponent.getComponentType().toString(), resourceType.name()); + } + break; + case RESOURCE: + if (!containerInstanceTypesData.getValidInstanceTypesInResourceContainer().get(((Resource) containerComponent).getResourceType()).contains(resourceType)) { + throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE, + containerComponent.getComponentType().toString(), resourceType.name()); + } + break; + default: + throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); + } + } + + private void validateOriginType(OriginTypeEnum originType, ResourceTypeEnum resourceType) { + ResourceTypeEnum convertedOriginType; + try { + convertedOriginType = ResourceTypeEnum.getTypeIgnoreCase(originType.name()); + } + catch (Exception e){ + throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); + } + + if (resourceType != convertedOriginType) throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); + } + + private ResourceTypeEnum getResourceTypeEnumFromOriginComponent(Component origComponent, ResourceTypeEnum resourceType) { + switch (origComponent.getComponentType()) { + case SERVICE: + resourceType = ResourceTypeEnum.ServiceProxy; + break; + case RESOURCE: + resourceType = ((Resource) origComponent).getResourceType(); + break; + default: + throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); } + return resourceType; + } + + private ComponentInstance isNeedLock(boolean needLock, Component containerComponent) { + if (needLock) { + lockComponent(containerComponent, "createComponentInstance"); + } + return null; + } + + private boolean isServiceProxyOrigin(Either<Component, StorageOperationStatus> serviceProxyOrigin) { + if (serviceProxyOrigin.isRight()) { + log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value()); + return true; + } + return false; } private StorageOperationStatus fillProxyInstanceData(ComponentInstance resourceInstance, Component proxyTemplate) { @@ -409,7 +512,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { resourceInstance.setCapabilities(capabilities); Map<String, List<RequirementDefinition>> req = service.getRequirements(); resourceInstance.setRequirements(req); - Map<String, InterfaceDefinition> serviceInterfaces = service.getInterfaces(); if(MapUtils.isNotEmpty(serviceInterfaces)) { serviceInterfaces.forEach(resourceInstance::addInterface); @@ -421,7 +523,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { List<InputDefinition> serviceInputs = service.getInputs(); resourceInstance.setInputs(serviceInputs); - String name = service.getNormalizedName() + ToscaOperationFacade.PROXY_SUFFIX; + String name = ValidationUtils.normalizeComponentInstanceName(service.getName()) + ToscaOperationFacade.PROXY_SUFFIX; String toscaResourceName = ((Resource) proxyTemplate).getToscaResourceName(); int lastIndexOf = toscaResourceName.lastIndexOf('.'); if (lastIndexOf != -1) { @@ -447,64 +549,34 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { ComponentInstance resourceInstance = createAndAssotiateInfo.getNode(); RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate(); - User user = validateUserExists(userId, "create And Associate RI To RI", false); + User user = validateUserExists(userId); - Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - return Either.right(validateComponentType.right().value()); - } - - final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); + final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam); - Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); + org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null); if (ModelConverter.isAtomicComponent(containerComponent)) { log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType())); } - Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } - - Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createAndAssociateRIToRI"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } + validateCanWorkOnComponent(containerComponent, userId); + boolean failed = false; try { + lockComponent(containerComponent, "createAndAssociateRIToRI"); log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH); - Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(resourceInstance); - - if (eitherResourceName.isRight()) { - resultOp = Either.right(eitherResourceName.right().value()); - return resultOp; - } - Component origComponent = eitherResourceName.left().value(); - - Either<ComponentInstance, ResponseFormat> result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user); - if (result.isRight()) { - log.debug("Failed to create resource instance {}", containerComponentId); - resultOp = Either.right(result.right().value()); - return resultOp; - - } + Component origComponent = getOriginComponentFromComponentInstance(resourceInstance); log.debug(ENTITY_ON_GRAPH_IS_CREATED); - ComponentInstance resResourceInfo = result.left().value(); + ComponentInstance resResourceInfo = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user); if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) { associationInfo.setFromNode(resResourceInfo.getUniqueId()); } else { associationInfo.setToNode(resResourceInfo.getUniqueId()); } - RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo; - Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponentId, requirementCapabilityRelDef); + Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponent, containerComponentId, associationInfo); if (resultReqCapDef.isLeft()) { log.debug(ENTITY_ON_GRAPH_IS_CREATED); RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value(); @@ -518,61 +590,53 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return resultOp; } - } finally { - unlockComponent(resultOp, containerComponent); + }catch (ComponentException e){ + failed = true; + throw e; + }finally { + unlockComponent(failed, containerComponent); } } - private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(ComponentInstance componentInstance) { + private Component getOriginComponentFromComponentInstance(ComponentInstance componentInstance) { return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getComponentUid()); } - private Either<Component, ResponseFormat> getInstanceOriginNode(ComponentInstance componentInstance) { + private Component getInstanceOriginNode(ComponentInstance componentInstance) { return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getActualComponentUid()); } - private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(String componentInstanceName, String origComponetId) { - Either<Component, ResponseFormat> eitherResponse; + private Component getOriginComponentFromComponentInstance(String componentInstanceName, String origComponetId) { Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId); if (eitherComponent.isRight()) { log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName); - eitherResponse = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null)); - } else { - eitherResponse = Either.left(eitherComponent.left().value()); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null); } - return eitherResponse; + return eitherComponent.left().value(); } - private Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) { + private ComponentInstance createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) { Either<ComponentInstance, ResponseFormat> resultOp; Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user); if (result.isRight()) { log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName()); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null)); - return resultOp; + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null)); } log.debug(ENTITY_ON_GRAPH_IS_CREATED); Component updatedComponent = result.left().value().getLeft(); Map<String, String> existingEnvVersions = new HashMap<>(); // TODO existingEnvVersions ?? - Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts = addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions); - if (addComponentInstanceArtifacts.isRight()) { - log.debug("Failed to create component instance {}", componentInstance.getName()); - resultOp = Either.right(addComponentInstanceArtifacts.right().value()); - return resultOp; - } + addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions); Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst(); if (!updatedInstanceOptional.isPresent()) { log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName()); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName())); - return resultOp; + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()); } - resultOp = Either.left(updatedInstanceOptional.get()); - return resultOp; + return updatedInstanceOptional.get(); } public boolean isCloudSpecificArtifact(String artifact) { @@ -598,14 +662,13 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { * @param existingEnvVersions * @return */ - protected Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user, Map<String, String> existingEnvVersions) { + protected ActionStatus addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user, Map<String, String> existingEnvVersions) { log.debug("add artifacts to resource instance"); List<GroupDefinition> filteredGroups = null; ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance); - if (!ActionStatus.OK.equals(status)) { - ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null); - return Either.right(resultOp); + if (ActionStatus.OK != status) { + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(status, "", null)); } StorageOperationStatus artStatus; // generate heat_env if necessary @@ -614,22 +677,23 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<>(); Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>(); - + Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration() + .getHeatArtifactDeploymentTimeout().getDefaultMinutes(); for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) { String type = artifact.getArtifactType(); if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) { finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact); } - if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT.getType()))) { + if (type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT.getType())) { + artifact.setTimeout(defaultHeatTimeout); + } else { continue; } if (artifact.checkEsIdExist()) { - Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactBusinessLogic.createHeatEnvPlaceHolder(artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, - componentInstance.getName(), user, containerComponent, existingEnvVersions); - if (createHeatEnvPlaceHolder.isRight()) { - return Either.right(createHeatEnvPlaceHolder.right().value()); - } - ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value(); + ArtifactDefinition artifactDefinition = artifactBusinessLogic.createHeatEnvPlaceHolder(new ArrayList<>(), + artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), + NodeTypeEnum.ResourceInstance, componentInstance.getName(), user, containerComponent, + existingEnvVersions); // put env finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition); @@ -637,37 +701,25 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList()); } if (CollectionUtils.isNotEmpty(filteredGroups)) { - for (GroupDefinition groupInstance : filteredGroups) { - Optional<String> op = groupInstance.getArtifacts().stream().filter(p -> p.equals(artifactDefinition.getGeneratedFromId())).findAny(); - if (op.isPresent()) { - List<ArtifactDefinition> artifactsUid; - if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) { - artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId()); - } else { - artifactsUid = new ArrayList<>(); - } - artifactsUid.add(artifactDefinition); - groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid); - break; - } - - if (isCloudSpecificArtifact(artifactDefinition.getArtifactName())) { - groupInstance.getArtifacts().add(artifactDefinition.getGeneratedFromId()); - } - } + filteredGroups.stream().filter(g -> + g.getArtifacts() + .stream() + .anyMatch(p -> p.equals(artifactDefinition.getGeneratedFromId()))) + .findFirst() + .ifPresent(g -> fillInstanceArtifactMap(groupInstancesArtifacts, artifactDefinition, g)); } } } artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts); if (artStatus != StorageOperationStatus.OK) { log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false))); + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false))); } StorageOperationStatus result = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts); if (result != StorageOperationStatus.OK) { log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result))); + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result))); } componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts); } @@ -675,20 +727,35 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts()); if (artStatus != StorageOperationStatus.OK) { log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false))); + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false))); } componentInstance.setArtifacts(originComponent.getArtifacts()); - return Either.left(ActionStatus.OK); + return ActionStatus.OK; + } + + private void fillInstanceArtifactMap(Map<String, List<ArtifactDefinition>> groupInstancesArtifacts, ArtifactDefinition artifactDefinition, GroupDefinition groupInstance) { + List<ArtifactDefinition> artifactsUid; + if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) { + artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId()); + } else { + artifactsUid = new ArrayList<>(); + } + artifactsUid.add(artifactDefinition); + groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid); + if (isCloudSpecificArtifact(artifactDefinition.getArtifactName())) { + groupInstance.getArtifacts().add(artifactDefinition.getGeneratedFromId()); + } } private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) { - Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null); + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = + artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null); Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>(); if (getResourceDeploymentArtifacts.isRight()) { StorageOperationStatus status = getResourceDeploymentArtifacts.right().value(); - if (!status.equals(StorageOperationStatus.NOT_FOUND)) { + if (status != StorageOperationStatus.NOT_FOUND) { log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status); return componentsUtils.convertFromStorageResponseForResourceInstance(status, true); } @@ -711,119 +778,78 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) { - return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true); + return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true); } public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction, - boolean needLock, boolean createNewTransaction) { + boolean needLock) { - validateUserExists(userId, "update Component Instance", inTransaction); + validateUserExists(userId); - Either<ComponentInstance, ResponseFormat> resultOp = null; + final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam); - Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - return Either.right(validateComponentType.right().value()); - } - - final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); - - Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); + org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null); - Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } + validateCanWorkOnComponent(containerComponent, userId); ComponentTypeEnum instanceType = getComponentType(containerComponentType); Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid()); if (validateParentStatus.isRight()) { log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase())); - return resultOp; + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase()); } if (!validateParentStatus.left().value()) { - resultOp = Either.right( - componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId)); - return resultOp; + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId); } if (needLock) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } + lockComponent(containerComponent, "updateComponentInstance"); } + Component origComponent; + boolean failed = false; try { - - Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(componentInstance); - - if (eitherResourceName.isRight()) { - resultOp = Either.right(eitherResourceName.right().value()); - return resultOp; + origComponent = getOriginComponentFromComponentInstance(componentInstance); + componentInstance = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance); + }catch (ComponentException e) { + failed = true; + throw e; + }finally { + if (needLock) { + unlockComponent(failed, containerComponent); } - Component origComponent = eitherResourceName.left().value(); - - resultOp = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance); - return resultOp; - - } finally { - if (needLock) - unlockComponent(resultOp, containerComponent); } + return Either.left(componentInstance); } // New Multiple Instance Update API - public Either<List<ComponentInstance>, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock) { + public List<ComponentInstance> updateComponentInstance(String containerComponentParam, Component containerComponent, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock) { - Either<List<ComponentInstance>, ResponseFormat> resultOp = null; - org.openecomp.sdc.be.model.Component containerComponent = null; + boolean failed = false; try { - validateUserExists(userId, "update Component Instance", true); - - Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - return Either.right(validateComponentType.right().value()); - } - - final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); + validateUserExists(userId); + final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam); ComponentParametersView componentFilter = new ComponentParametersView(); componentFilter.disableAll(); componentFilter.setIgnoreUsers(false); componentFilter.setIgnoreComponentInstances(false); - Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - - containerComponent = validateComponentExists.left().value(); - - Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); + if (containerComponent == null) { + containerComponent = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter); } + validateCanWorkOnComponent(containerComponent, userId); ComponentTypeEnum instanceType = getComponentType(containerComponentType); for (ComponentInstance componentInstance : componentInstanceList) { boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId()); if (!validateParent) { - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), - containerComponentId)); - return resultOp; + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), + instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), + containerComponentId); } } if (needLock) { - - Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } + lockComponent(containerComponent, "updateComponentInstance"); } List<ComponentInstance> updatedList = new ArrayList<>(); @@ -843,8 +869,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName()); if (!isUniqueName) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", origInst.getName(), updatedCi.getName()); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName())); - return resultOp; + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName())); } listForUpdate.add(updatedCi); } else @@ -852,28 +877,26 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } containerComponent.setComponentInstances(listForUpdate); - if (resultOp == null) { - Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter); - if (updateStatus.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value()); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null)); - return resultOp; - } - for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) { - Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny(); - if (op.isPresent()) { - updatedList.add(updatedInstance); - } + Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter); + if (updateStatus.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value()); + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null)); + } + + for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) { + Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny(); + if (op.isPresent()) { + updatedList.add(updatedInstance); } } } - - resultOp = Either.left(updatedList); - return resultOp; - - } finally { + return updatedList; + }catch (ComponentException e){ + failed = true; + throw e; + }finally { if (needLock) { - unlockComponent(resultOp, containerComponent); + unlockComponent(failed, containerComponent); } } } @@ -883,94 +906,94 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) { - if (ComponentTypeEnum.PRODUCT.equals(containerComponentType)) { + if (ComponentTypeEnum.PRODUCT == containerComponentType) { return ComponentTypeEnum.SERVICE_INSTANCE; } else { return ComponentTypeEnum.RESOURCE_INSTANCE; } } - private Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId, - ComponentInstance componentInstance) { + private ComponentInstance updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId, + ComponentInstance componentInstance) { - Either<ComponentInstance, ResponseFormat> resultOp = null; - Optional<ComponentInstance> componentInstanceOptional = null; + Optional<ComponentInstance> componentInstanceOptional; Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null; ComponentInstance oldComponentInstance = null; boolean isNameChanged = false; - if (resultOp == null) { - componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst(); - if (!componentInstanceOptional.isPresent()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName()); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName())); - } - } - if (resultOp == null) { - oldComponentInstance = componentInstanceOptional.get(); - String newInstanceName = componentInstance.getName(); - if (oldComponentInstance != null && oldComponentInstance.getName() != null && !oldComponentInstance.getName().equals(newInstanceName)) - isNameChanged = true; - Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName); - if (!isUniqueName) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", oldComponentInstance.getName(), newInstanceName); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName())); - } - if(!DirectivesUtils.isValid(componentInstance.getDirectives())) { - final String directivesStr = - componentInstance.getDirectives().stream().collect(Collectors.joining(" , ", " [ ", " ] ")); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, - "Failed to update the directives of the component instance {} to {}. Directives data {} is invalid. ", - oldComponentInstance.getName(), newInstanceName , - directivesStr); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.DIRECTIVES_INVALID_VALUE, - directivesStr)); - } + componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst(); + if (!componentInstanceOptional.isPresent()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName()); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()); } + String oldComponentName; + oldComponentInstance = componentInstanceOptional.get(); + oldComponentName = oldComponentInstance.getName(); String newInstanceName = componentInstance.getName(); - String oldInstanceName = null; - if (resultOp == null) { - oldComponentInstance = componentInstanceOptional.get(); - newInstanceName = componentInstance.getName(); - updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance)); - if (updateRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(), - updateRes.right().value()); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null)); - } else { - // region - Update instance Groups - if (isNameChanged) { - Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId); - if (result.isRight()) - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value()); - if (containerComponent instanceof Service) { - Either<ComponentInstance, ResponseFormat> renameEither = - renameServiceFilter((Service) containerComponent, newInstanceName, - oldInstanceName); - if (renameEither.isRight()) { - return renameEither; - } + if (oldComponentName != null && !oldComponentInstance.getName().equals(newInstanceName)) + isNameChanged = true; + Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName); + if (!isUniqueName) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", oldComponentInstance.getName(), newInstanceName); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName()); + } + if(!DirectivesUtils.isValid(componentInstance.getDirectives())) { + final String directivesStr = + componentInstance.getDirectives().stream().collect(Collectors.joining(" , ", " [ ", " ] ")); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, + "Failed to update the directives of the component instance {} to {}. Directives data {} is invalid. ", + oldComponentInstance.getName(), newInstanceName , + directivesStr); + throw new ByActionStatusComponentException(ActionStatus.DIRECTIVES_INVALID_VALUE, containerComponentType.getValue(), componentInstance.getName()); } + updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance)); + if (updateRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(), + updateRes.right().value()); + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null)); + } else { + // region - Update instance Groups + if (isNameChanged) { + Either<StorageOperationStatus, StorageOperationStatus> result = + toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId); + if (result.isRight()) + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value()); + + if (containerComponent instanceof Service){ + Either<ComponentInstance, ResponseFormat> renameEither = + renameServiceFilter((Service) containerComponent, newInstanceName, + oldComponentInstance.getName()); + if (renameEither.isRight()) { + throw new ByResponseFormatComponentException(renameEither.right().value()); } + + updateForwardingPathDefinition(containerComponent, componentInstance, oldComponentName); } - // endregion } + // endregion } - if (resultOp == null) { - String newInstanceId = updateRes.left().value().getRight(); - Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst(); + String newInstanceId = updateRes.left().value().getRight(); + Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst(); - if (!updatedInstanceOptional.isPresent()) { - log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName()); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName())); - } else { - resultOp = Either.left(updatedInstanceOptional.get()); - } - - } - if (resultOp == null) { - resultOp = Either.left(componentInstanceOptional.get()); + if (!updatedInstanceOptional.isPresent()) { + log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName()); + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName())); } - return resultOp; + + return componentInstanceOptional.get(); + } + + private void updateForwardingPathDefinition(Component containerComponent, ComponentInstance componentInstance, String oldComponentName) { + Collection<ForwardingPathDataDefinition> forwardingPathDataDefinitions = getForwardingPathDataDefinitions(containerComponent.getUniqueId()); + Set<ForwardingPathDataDefinition> updated = new ForwardingPathUtils() + .updateComponentInstanceName(forwardingPathDataDefinitions, oldComponentName, + componentInstance.getName()); + updated.forEach(fp -> { + Either<ForwardingPathDataDefinition, StorageOperationStatus> resultEither = forwardingPathOperation + .updateForwardingPath(containerComponent.getUniqueId(), fp); + if (resultEither.isRight()){ + CommonUtility.addRecordToLog(log, LogLevelEnum.ERROR, "Failed to rename forwarding path for container {}. error {} ",containerComponent.getName(), resultEither.right().value()); + } + }); } @@ -1023,32 +1046,17 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return oldComponentInstance; } - public Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) { + public ComponentInstance deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) { - validateUserExists(userId, "delete Component Instance", false); + validateUserExists(userId); - Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - return Either.right(validateComponentType.right().value()); - } + final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam); - final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); - Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); - Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } + org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null); + validateCanWorkOnComponent(containerComponent, userId); - Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "deleteComponentInstance"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - - Either<ComponentInstance, ResponseFormat> resultOp = null; + boolean failed = false; + ComponentInstance deletedRelatedInst; try { if (containerComponent instanceof Service) { ComponentInstance componentInstance = containerComponent.getComponentInstanceById(componentInstanceId).get(); @@ -1058,29 +1066,32 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { ActionStatus status = componentsUtils.convertFromStorageResponse(deleteServiceFilterEither.right().value(), containerComponentType); janusGraphDao.rollback(); - return Either.right(componentsUtils.getResponseFormat(status, componentInstanceId)); + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(status, componentInstanceId)); } - resultOp = deleteServiceFiltersRelatedTobeDeletedComponentInstance((Service) containerComponent, + Either<ComponentInstance, ResponseFormat> resultOp = deleteServiceFiltersRelatedTobeDeletedComponentInstance((Service) containerComponent, componentInstance, ComponentTypeEnum.SERVICE, userId); if (resultOp.isRight()) { janusGraphDao.rollback(); - return resultOp; + throw new ByResponseFormatComponentException(resultOp.right().value()); } } - resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType); - if (resultOp.isRight()){ - return resultOp; - } - Either<ComponentInstance, ResponseFormat> deleteEither = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, - containerComponentType, resultOp); - if (deleteEither.isRight()){ - return deleteEither; - } - return deleteEither; + lockComponent(containerComponent, "deleteComponentInstance"); + ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType); - } finally { - unlockComponent(resultOp, containerComponent); + deletedRelatedInst = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, + containerComponentType, deletedCompInstance); + ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator.doOnDeleteInstanceOperations(containerComponent, componentInstanceId); + if (ActionStatus.OK != onDeleteOperationsStatus) { + throw new ByActionStatusComponentException(onDeleteOperationsStatus); + } + } catch (ComponentException e) { + failed = true; + throw e; } + finally { + unlockComponent(failed, containerComponent); + } + return deletedRelatedInst; } public Either<ComponentInstance, ResponseFormat> deleteServiceFiltersRelatedTobeDeletedComponentInstance( @@ -1112,7 +1123,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { ci.setDirectives(directives); final Either<ComponentInstance, ResponseFormat> componentInstanceResponseFormatEither = updateComponentInstanceMetadata(ComponentTypeEnum.SERVICE_PARAM_NAME, service.getUniqueId(), - ci.getUniqueId(), userId, ci, true, false, false); + ci.getUniqueId(), userId, ci, true, false); if (componentInstanceResponseFormatEither.isRight()) { return componentInstanceResponseFormatEither; } @@ -1137,45 +1148,37 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } - public Either<ComponentInstance, ResponseFormat> deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId, ComponentTypeEnum containerComponentType, - Either<ComponentInstance, ResponseFormat> resultOp) { - if(containerComponentType.equals(ComponentTypeEnum.SERVICE) && resultOp.isLeft() ){ - final ComponentInstance componentInstance = resultOp.left().value(); + ComponentInstance deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId, + ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) { + if(containerComponentType == ComponentTypeEnum.SERVICE){ List<String> pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstance.getName()); if (!pathIDsToBeDeleted.isEmpty()) { - Either<Set<String>, ResponseFormat> deleteForwardingPathsEither = deleteForwardingPaths(containerComponentId, - pathIDsToBeDeleted); - if(deleteForwardingPathsEither.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - + deleteForwardingPaths(containerComponentId, pathIDsToBeDeleted); } } - return resultOp; + return componentInstance; } - private Either<Set<String>, ResponseFormat> deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete){ + + + + private void deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete){ Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId); if(storageStatus.isRight()) { - return Either.right(componentsUtils.getResponseFormat(storageStatus.right().value())); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus.right().value())); } Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation.deleteForwardingPath(storageStatus.left().value(), Sets.newHashSet(pathIdsToDelete)); if(result.isRight()) { - return Either.right(componentsUtils.getResponseFormat(result.right().value())); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(result.right().value())); } - return Either.left(result.left().value()); } private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId){ - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreForwardingPath(false); - Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade - .getToscaElement(containerComponentId, filter); - Collection<ForwardingPathDataDefinition> allPaths = forwardingPathOrigin.left().value().getForwardingPaths().values(); + Collection<ForwardingPathDataDefinition> allPaths = getForwardingPathDataDefinitions(containerComponentId); List<String> pathIDsToBeDeleted = new ArrayList<>(); allPaths.stream().filter(path -> isPathRelatedToComponent(path,componentInstanceId )) @@ -1184,6 +1187,14 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return pathIDsToBeDeleted; } + private Collection<ForwardingPathDataDefinition> getForwardingPathDataDefinitions(String containerComponentId) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreForwardingPath(false); + Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade + .getToscaElement(containerComponentId, filter); + return forwardingPathOrigin.left().value().getForwardingPaths().values(); + } + private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition, String componentInstanceId){ return pathDataDefinition.getPathElements().getListToscaDataDefinition() @@ -1193,49 +1204,28 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } - private Either<ComponentInstance, ResponseFormat> deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) { - - Either<ComponentInstance, ResponseFormat> resultOp = null; - ComponentInstance deletedInstance = null; + private ComponentInstance deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) { Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId); - if (deleteRes.isRight()) { log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId); ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType); - resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId)); - } - if (resultOp == null) { - log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent); - deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent); - resultOp = Either.left(deletedInstance); - } - if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getGroups())) { - List<GroupDataDefinition> groupsToUpdate = new ArrayList<>(); - for (GroupDataDefinition currGroup : containerComponent.getGroups()) { - Map<String, String> members = currGroup.getMembers(); - if (members != null && members.containsKey(deletedInstance.getName())) { - members.remove(deletedInstance.getName()); - groupsToUpdate.add(currGroup); - } - } - Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsRes = toscaOperationFacade.updateGroupsOnComponent(containerComponent, groupsToUpdate); - if (updateGroupsRes.isRight()) { - log.debug("Failed to delete component instance {} from group members. ", componentInstanceId); - ActionStatus status = componentsUtils.convertFromStorageResponse(updateGroupsRes.right().value(), containerComponentType); - resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId)); - } + throw new ByActionStatusComponentException(status, componentInstanceId); } - if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())) { + log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent); + ComponentInstance deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent); + + if (CollectionUtils.isNotEmpty(containerComponent.getInputs())) { List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList()); if (CollectionUtils.isNotEmpty(inputsToDelete)) { StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, inputsToDelete); if (deleteInputsRes != StorageOperationStatus.OK) { log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId); - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId)); + throw new ByActionStatusComponentException( + componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId); } } } - return resultOp; + return deletedInstance; } private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) { @@ -1261,59 +1251,45 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId); } - public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) { - return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true, true); + public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) { + return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true); } - public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock, - boolean createNewTransaction) { - - validateUserExists(userId, "associate Ri To RI", inTransaction); + public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock) { - Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null; + validateUserExists(userId); - Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); + RequirementCapabilityRelDef requirementCapabilityRelDef = null; - Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } - if (needLock) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI"); - - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - } + org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null); + validateCanWorkOnComponent(containerComponent, userId); + boolean failed = false; try { - - resultOp = associateRIToRIOnGraph(validateComponentExists.left().value(), requirementDef, componentTypeEnum, inTransaction); - - return resultOp; - - } finally { + if (needLock) { + lockComponent(containerComponent, "associateRIToRI"); + } + requirementCapabilityRelDef = associateRIToRIOnGraph(containerComponent, requirementDef); + }catch (ComponentException e){ + failed = true; + throw e; + }finally { if (needLock) - unlockComponent(resultOp, containerComponent); + unlockComponent(failed, containerComponent); } + return requirementCapabilityRelDef; } - public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) { + public RequirementCapabilityRelDef associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef) { log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH); - Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null; - Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef); + Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(null, containerComponent.getUniqueId(), requirementDef); if (result.isLeft()) { - log.debug("Enty on graph is created."); + log.debug(ENTITY_ON_GRAPH_IS_CREATED); RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value(); - resultOp = Either.left(requirementCapabilityRelDef); - return resultOp; + return requirementCapabilityRelDef; } else { log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode()); @@ -1331,9 +1307,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { toNameOrId = toResult.left().value().getName(); } - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement())); - - return resultOp; + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponseForResourceInstance + (result.right().value(), true), fromNameOrId, toNameOrId, + requirementDef.getRelationships().get(0).getRelation().getRequirement()); } } @@ -1351,112 +1327,71 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { List<RequirementCapabilityRelDef> requirementDefList, ComponentTypeEnum componentTypeEnum) { + validateUserExists(userId); + org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null); + validateCanWorkOnComponent(containerComponent, userId); + boolean failed = false; List<RequirementCapabilityRelDef> delOkResult = new ArrayList<>(); - Either<Component, ResponseFormat> validateResponse = validateDissociateRI(componentId, userId, componentTypeEnum); - if (validateResponse.isRight()) { - - return delOkResult; - } - Component containerComponent = validateResponse.left().value(); - Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI"); - if (lockComponent.isRight()) { - return delOkResult; - } try { + lockComponent(containerComponent, "associateRIToRI"); for (RequirementCapabilityRelDef requirementDef : requirementDefList) { - Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = dissociateRIFromRI( - componentId, requirementDef, containerComponent); - - if (actionResponse.isLeft()) { - delOkResult.add(actionResponse.left().value()); - } + RequirementCapabilityRelDef requirementCapabilityRelDef = dissociateRIFromRI( + componentId, userId, requirementDef, containerComponent.getComponentType()); + delOkResult.add(requirementCapabilityRelDef); } - } finally { - unlockComponent(validateResponse, containerComponent); + }catch (ComponentException e){ + failed = true; + throw e; + }finally { + unlockComponent(failed, containerComponent); } return delOkResult; } - public Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI( - String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) { - Either<Component, ResponseFormat> validateResponse = validateDissociateRI(componentId, userId, componentTypeEnum); - if(validateResponse.isRight()) - { - return Either.right(validateResponse.right().value()); - } - Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = null; - Component containerComponent = validateResponse.left().value(); - Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - try { - actionResponse = dissociateRIFromRI( - componentId, requirementDef,containerComponent); - } finally { - unlockComponent(validateResponse, containerComponent); - } - return actionResponse; - } - - private Either<Component, ResponseFormat> validateDissociateRI( - String componentId, String userId, ComponentTypeEnum componentTypeEnum) { - validateUserExists(userId, "dissociate RI From RI", false); - - - Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); - - Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } - return Either.left(containerComponent); - } - private Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI( - String componentId, RequirementCapabilityRelDef requirementDef, Component containerComponent) { + public RequirementCapabilityRelDef dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) { + validateUserExists(userId); Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null; - log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH); - Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances( - componentId, requirementDef); - if (result.isLeft()) { - log.debug("Enty on graph is created."); - RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value(); - resultOp = Either.left(requirementCapabilityRelDef); - return resultOp; + org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null); - } else { + validateCanWorkOnComponent(containerComponent, userId); + boolean failed = false; + try { + lockComponent(containerComponent, "associateRIToRI"); + log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH); + Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef); + if (result.isLeft()) { + log.debug(ENTITY_ON_GRAPH_IS_CREATED); + return result.left().value(); + } else { - log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode()); - String fromNameOrId = ""; - String toNameOrId = ""; - Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById( - containerComponent, requirementDef.getFromNode()); - Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById( - containerComponent, requirementDef.getToNode()); + log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode()); + String fromNameOrId = ""; + String toNameOrId = ""; + Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode()); + Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode()); - toNameOrId = requirementDef.getFromNode(); - fromNameOrId = requirementDef.getFromNode(); - if (fromResult.isLeft()) { - fromNameOrId = fromResult.left().value().getName(); - } - if (toResult.isLeft()) { - toNameOrId = toResult.left().value().getName(); - } + toNameOrId = requirementDef.getFromNode(); + fromNameOrId = requirementDef.getFromNode(); + if (fromResult.isLeft()) { + fromNameOrId = fromResult.left().value().getName(); + } + if (toResult.isLeft()) { + toNameOrId = toResult.left().value().getName(); + } - resultOp = Either - .right(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponseForResourceInstance( - result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement())); - return resultOp; + throw new ByActionStatusComponentException( + componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), + fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()); + } + }catch (ComponentException e){ + failed = true; + throw e; + }finally { + unlockComponent(failed, containerComponent); } } - /** * Allows to get relation contained in specified component according to received Id * @param componentId @@ -1473,23 +1408,14 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = null; RequirementCapabilityRelDef foundRelation = null; - validateUserExists(userId, "get relation by Id", false); - - if(resultOp == null){ - validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null); - if (validateComponentExists.isRight()) { - resultOp = Either.right(validateComponentExists.right().value()); - } - } - if(resultOp == null){ - containerComponent = validateComponentExists.left().value(); - List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations(); - foundRelation = findRelation(relationId, requirementCapabilityRelations); - if(foundRelation == null){ - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId); - log.debug("Relation with id {} was not found on the component", relationId, componentId); - resultOp = Either.right(responseFormat); - } + validateUserExists(userId); + containerComponent = validateComponentExists(componentId, componentTypeEnum, null); + List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations(); + foundRelation = findRelation(relationId, requirementCapabilityRelations); + if(foundRelation == null){ + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId); + log.debug("Relation with id {} was not found on the component", relationId, componentId); + resultOp = Either.right(responseFormat); } if(resultOp == null){ resultOp = setRelatedCapability(foundRelation, containerComponent); @@ -1526,7 +1452,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } if(result == null){ for(List<RequirementDefinition> requirements : instance.get().getRequirements().values()){ - foundRequirement = requirements.stream().filter(r -> isBelongingRequirement(relationshipInfo, r)).findFirst(); + foundRequirement = requirements.stream().filter(r -> isBelongingCalcRequirement(relationshipInfo, r, containerComponent.getLifecycleState())).findFirst(); if(foundRequirement.isPresent()){ foundRelation.resolveSingleRelationship().setRequirement(foundRequirement.get()); result = Either.left(foundRelation); @@ -1534,7 +1460,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } if(result == null){ - Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade.getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, req)->isBelongingRequirement(rel, req)); + Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade.getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullRequirement); if(getfulfilledRequirementRes.isRight()){ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId, containerComponent.getUniqueId()); log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId()); @@ -1549,12 +1475,18 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return result; } - private boolean isBelongingRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) { + private boolean isBelongingFullRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) { return req.getName().equals(relationshipInfo.getRequirement()) && req.getUniqueId().equals(relationshipInfo.getRequirementUid()) && req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId()); } + private boolean isBelongingCalcRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req, LifecycleStateEnum state) { + return nameMatches(relationshipInfo.getRequirement(), req.getName(), req.getPreviousName(), state) && + req.getUniqueId().equals(relationshipInfo.getRequirementUid()) && + req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId()); + } + private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) { Either<RequirementCapabilityRelDef, ResponseFormat> result = null; RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation(); @@ -1568,7 +1500,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } if(result == null){ for(List<CapabilityDefinition> capabilities : instance.get().getCapabilities().values()){ - foundCapability = capabilities.stream().filter(c -> isBelongingCapability(relationshipInfo, c)).findFirst(); + foundCapability = capabilities.stream().filter(c -> isBelongingCalcCapability(relationshipInfo, c, containerComponent.getLifecycleState())).findFirst(); if(foundCapability.isPresent()){ foundRelation.resolveSingleRelationship().setCapability(foundCapability.get()); result = Either.left(foundRelation); @@ -1577,7 +1509,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } if(result == null){ Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = - toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, cap)->isBelongingCapability(rel, cap)); + toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullCapability); if(getfulfilledRequirementRes.isRight()){ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId()); log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId()); @@ -1592,12 +1524,24 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return result; } - private boolean isBelongingCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) { + private boolean isBelongingFullCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) { return cap.getName().equals(relationshipInfo.getCapability()) && cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) && cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId()); } + private boolean isBelongingCalcCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap, LifecycleStateEnum state) { + return nameMatches(relationshipInfo.getCapability(), cap.getName(), cap.getPreviousName(), state) && + cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) && + cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId()); + } + + private boolean nameMatches(String nameFromRelationship, String currName, String previousName, LifecycleStateEnum state) { + return state == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT ? + currName.equals(nameFromRelationship): + previousName!= null && previousName.equals(nameFromRelationship); + } + private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) { Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true); Either<ComponentInstanceProperty, ResponseFormat> result; @@ -1660,7 +1604,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { Either<ComponentInstanceProperty, ResponseFormat> result = null; Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - validateUserExist(userId, "create Or Update Attribute Value"); + validateUserExists(userId); if (errorWrapper.isEmpty()) { validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper); } @@ -1696,45 +1640,12 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } - private boolean isNetworkRoleServiceProperty(ComponentInstanceProperty property, ComponentTypeEnum componentTypeEnum) { - return StringUtils.isNotEmpty(property.getValue()) - && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName()) - && ComponentTypeEnum.SERVICE == componentTypeEnum; - } - - // US833308 VLI in service - specific network_role property value logic - private StorageOperationStatus concatServiceNameToVLINetworkRolePropertiesValues(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties) { - for (ComponentInstanceProperty property: properties) { - if (isNetworkRoleServiceProperty(property, componentTypeEnum)) { - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreComponentInstances(false); - Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade.getToscaElement(componentId, componentParametersView); - if (getServiceResult.isRight()) { - return getServiceResult.right().value(); - } - Component service = getServiceResult.left().value(); - Optional<ComponentInstance> getInstance = service.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(resourceInstanceId)).findAny(); - if (!getInstance.isPresent()) { - return StorageOperationStatus.NOT_FOUND; - } - String prefix = service.getSystemName() + "."; - String value = property.getValue(); - if (OriginTypeEnum.VL == getInstance.get().getOriginType() && (!value.startsWith(prefix) || value.equalsIgnoreCase(prefix))) { - property.setValue(prefix + value); - } - } - } - return StorageOperationStatus.OK; - } - public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties, String userId) { Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null; /*-------------------------------Validations---------------------------------*/ - - validateUserExists(userId, "create Or Update Properties Values", false); + validateUserExists(userId); if (componentTypeEnum == null) { BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO); @@ -1745,51 +1656,45 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { if (getResourceResult.isRight()) { log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - return resultOp; + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum); + return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId)); } Component containerComponent = getResourceResult.left().value(); if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) { + if (containerComponent.isArchived()) { + log.info("Component is archived. Component id: {}", componentId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName())); + } log.info("Restricted operation for user: {} on service {}", userId, componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - return resultOp; + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } - //Validate value and Constraint of property - Either<Boolean, ResponseFormat> constraintValidatorResponse = - PropertyValueConstraintValidationUtil.getInstance(). - validatePropertyConstraints(properties, applicationDataTypeCache); - if (constraintValidatorResponse.isRight()) { - log.error("Failed validation value and constraint of property: {}", - constraintValidatorResponse.right().value()); - return Either.right(constraintValidatorResponse.right().value()); - } - Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId); if (resourceInstanceStatus.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId)); - return resultOp; + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, + resourceInstanceId, "resource instance", "service", componentId)); } ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); - // specific property value logic US833308 - StorageOperationStatus fetchByIdsStatus = concatServiceNameToVLINetworkRolePropertiesValues(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, properties); - if (StorageOperationStatus.OK != fetchByIdsStatus) { - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fetchByIdsStatus))); - return resultOp; - } + // lock resource StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); if (lockStatus != StorageOperationStatus.OK) { log.debug(FAILED_TO_LOCK_SERVICE, componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); - return resultOp; + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); } - + List <ComponentInstanceProperty> updatedProperties = new ArrayList<>(); try { for (ComponentInstanceProperty property: properties) { + validateMandatoryFields(property); + ComponentInstanceProperty componentInstanceProperty = validatePropertyExistsOnComponent(property, containerComponent, foundResourceInstance); String propertyParentUniqueId = property.getParentUniqueId(); Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, false); + if (updatedPropertyValue.isRight()) { + log.error("Failed to update property object value of property: {}", + property); + throw new ByResponseFormatComponentException(updatedPropertyValue.right().value()); + } Optional<CapabilityDefinition> capPropDefinition = getPropertyCapabilityOfChildInstance(propertyParentUniqueId, foundResourceInstance.getCapabilities()); if(capPropDefinition.isPresent()) { @@ -1801,6 +1706,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { else { updatedPropertyValue.bimap(updatedValue -> updatePropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance), Either::right); + updatedProperties.add(componentInstanceProperty); } } @@ -1810,7 +1716,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); return resultOp; } - resultOp = Either.left(properties); + resultOp = Either.left(updatedProperties); return resultOp; } finally { @@ -1824,17 +1730,29 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } + private void validateMandatoryFields(PropertyDataDefinition property) { + if (StringUtils.isEmpty(property.getName())) { + throw new ByActionStatusComponentException (ActionStatus.MISSING_PROPERTY_NAME); + } + } + + private ComponentInstanceProperty validatePropertyExistsOnComponent(ComponentInstanceProperty property, Component containerComponent, ComponentInstance foundResourceInstance) { + List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(foundResourceInstance.getUniqueId()); + Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getName().equals(property.getName())).findAny(); + if (!instanceProperty.isPresent()) { + throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, property.getName()); + } + return instanceProperty.get(); + } + + + private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance, String capabilityType, String capabilityName) { String componentInstanceUniqueId = foundResourceInstance.getUniqueId(); - StringBuilder sb = new StringBuilder(componentInstanceUniqueId); - sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM) - .append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName); - String capKey = sb.toString(); - ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent, - foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId, capKey); + foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId); if (actionStatus != null) { return actionStatus; } @@ -1858,14 +1776,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } else { propOwner = foundResourceInstance.getSourceModelUid(); } - StringBuilder sb = new StringBuilder(componentInstanceUniqueId); - - sb.append(ModelConverter.CAP_PROP_DELIM).append(propOwner).append(ModelConverter.CAP_PROP_DELIM) - .append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName); - String capKey = sb.toString(); ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent, - foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId, capKey); + foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId); if (actionStatus != null) { return actionStatus; } @@ -1877,7 +1790,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { Component containerComponent, ComponentInstance foundResourceInstance, String capabilityType, String capabilityName, - String componentInstanceUniqueId, String capKey) { + String componentInstanceUniqueId) { Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities()).orElse(Collections.emptyMap()); List<CapabilityDefinition> capPerType = @@ -1891,6 +1804,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); StorageOperationStatus status; if (instanceProperty.isPresent()) { + String capKey = ModelConverter.buildCapabilityPropertyKey(foundResourceInstance.getOriginType().isAtomicType(), capabilityType, capabilityName, componentInstanceUniqueId, cap.get()); instanceProperty.get().setValue(newValue); List<String> path = new ArrayList<>(); path.add(componentInstanceUniqueId); @@ -1911,35 +1825,59 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return null; } - private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, - Component containerComponent, ComponentInstance foundResourceInstance) { - List<ComponentInstanceProperty> instanceProperties = - containerComponent.getComponentInstancesProperties().get(foundResourceInstance.getUniqueId()); - Optional<ComponentInstanceProperty> instanceProperty = - instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); + private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty instanceProperty, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) { StorageOperationStatus status; - instanceProperty.get().setValue(newValue); - if (instanceProperty.isPresent()) { - status = toscaOperationFacade - .updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), - property); - } else { - status = toscaOperationFacade - .addComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), - property); - } + instanceProperty.setValue(newValue); + status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), instanceProperty); if (status != StorageOperationStatus.OK) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""); } - List<String> path = new ArrayList<>(); - path.add(foundResourceInstance.getUniqueId()); - property.setPath(path); - foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString()); return componentsUtils.getResponseFormat(ActionStatus.OK); } + private <T extends PropertyDefinition> Either<String,ResponseFormat> validatePropertyObjectValue(T property, String newValue, boolean isInput) { + Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll(); + if (allDataTypesEither.isRight()) { + JanusGraphOperationStatus status = allDataTypesEither.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)))); + } + Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value(); + String propertyType = property.getType(); + String innerType = getInnerType(property); + + // Specific Update Logic + Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(property.getType(), newValue, true, innerType, allDataTypes); + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (!res) { + log.error("Invalid value {} of property {} ", newValue, property.getName()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + if (validateAndUpdateRules(property, isInput, allDataTypes, innerType, propertyType)) + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)))); + return Either.left(newValue); + } + + private <T extends PropertyDefinition> boolean validateAndUpdateRules(T property, boolean isInput, Map<String, DataTypeDefinition> allDataTypes, String innerType, String propertyType) { + if (!isInput) { + ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true); + if (pair.getRight() != null && !pair.getRight()) { + BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); + return true; + } + } + return false; + } + private <T extends PropertyDefinition> Either<String,ResponseFormat> updatePropertyObjectValue(T property, boolean isInput) { Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll(); if (allDataTypesEither.isRight()) { @@ -1972,7 +1910,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { if (isValid.isRight()) { Boolean res = isValid.right().value(); if (!res) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)))); + log.debug("validate and update property value has failed with value: {}", property.getValue()); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))); } } else { Object object = isValid.left().value(); @@ -1991,15 +1930,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) { - List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId()); - Optional<ComponentInstanceInput> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(input.getUniqueId())).findAny(); StorageOperationStatus status; - if (instanceProperty.isPresent()) { - instanceProperty.get().setValue(input.getValue()); - status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input); - } else { - status = toscaOperationFacade.addComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input); - } + input.setValue(newValue); + status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input); if (status != StorageOperationStatus.OK) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""); @@ -2012,7 +1945,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null; - validateUserExists(userId, "create Or Update Property Value", false); + validateUserExists(userId); if (componentTypeEnum == null) { BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO); @@ -2023,20 +1956,24 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { if (getResourceResult.isRight()) { log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - return resultOp; + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum); + return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId)); } Component containerComponent = getResourceResult.left().value(); if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) { + if (containerComponent.isArchived()) { + log.info("Component is archived. Component id: {}", componentId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName())); + } log.info("Restricted operation for user: {} on service {}", userId, componentId); resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); return resultOp; } Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId); if (resourceInstanceStatus.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId)); - return resultOp; + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, + resourceInstanceId, "resource instance", "service", componentId)); } ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); @@ -2045,24 +1982,27 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); if (lockStatus != StorageOperationStatus.OK) { log.debug(FAILED_TO_LOCK_SERVICE, componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); - return resultOp; + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); } + List <ComponentInstanceInput> updatedInputs = new ArrayList<>(); try { for (ComponentInstanceInput input: inputs) { - Either<String, ResponseFormat> updatedInputValue = updatePropertyObjectValue(input, true); - updatedInputValue.bimap(updatedValue -> updateInputOnContainerComponent(input,updatedValue, containerComponent, foundResourceInstance), - Either::right); - + validateMandatoryFields(input); + ComponentInstanceInput componentInstanceInput = validateInputExistsOnComponent(input, containerComponent, foundResourceInstance); + Either<String, ResponseFormat> validatedInputValue = validatePropertyObjectValue(componentInstanceInput, input.getValue(), true); + if (validatedInputValue.isRight()){ + throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT, input.getName()); + } + updateInputOnContainerComponent(componentInstanceInput, validatedInputValue.left().value(), containerComponent, foundResourceInstance); + updatedInputs.add(componentInstanceInput); } Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); - if (updateContainerRes.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); return resultOp; } - resultOp = Either.left(inputs); + resultOp = Either.left(updatedInputs); return resultOp; } finally { @@ -2077,12 +2017,20 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } - public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property, - String userId) { + private ComponentInstanceInput validateInputExistsOnComponent(ComponentInstanceInput input, Component containerComponent, ComponentInstance foundResourceInstance) { + List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId()); + Optional<ComponentInstanceInput> instanceInput = instanceProperties.stream().filter(p -> p.getName().equals(input.getName())).findAny(); + if (!instanceInput.isPresent()) { + throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, input.getName()); + } + return instanceInput.get(); + } + + public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property, String userId) { Either<ComponentInstanceProperty, ResponseFormat> resultOp = null; - validateUserExists(userId, "create Or Update Property Value", false); + validateUserExists(userId); if (componentTypeEnum == null) { BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO); @@ -2172,98 +2120,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } - public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput inputProperty, String userId) { - - Either<ComponentInstanceInput, ResponseFormat> resultOp = null; - - validateUserExists(userId, "create Or Update Input Value", false); - - if (componentTypeEnum == null) { - BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateInputValue", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); - return resultOp; - } - - if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) { - log.info("Restricted operation for user: {} on service: {}", userId, componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - return resultOp; - } - // lock resource - StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); - if (lockStatus != StorageOperationStatus.OK) { - log.debug(FAILED_TO_LOCK_SERVICE, componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); - return resultOp; - } - try { - String propertyValueUid = inputProperty.getValueUniqueUid(); - if (propertyValueUid == null) { - - Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true); - - if (counterRes.isRight()) { - log.debug("increaseAndGetResourceInputCounter failed resource instance {} inputProperty {}", resourceInstanceId, inputProperty); - StorageOperationStatus status = counterRes.right().value(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); - resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus)); - } - Integer index = counterRes.left().value(); - Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.addInputValueToResourceInstance(inputProperty, resourceInstanceId, index, true); - - if (result.isLeft()) { - log.debug("Property value was added to resource instance {}", resourceInstanceId); - ComponentInstanceInput instanceProperty = result.left().value(); - - resultOp = Either.left(instanceProperty); - return resultOp; - - } else { - log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId); - - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); - - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - - return resultOp; - } - - } else { - Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.updateInputValueInResourceInstance(inputProperty, resourceInstanceId, true); - - if (result.isLeft()) { - log.debug("Input value {} was updated on graph.", inputProperty.getValueUniqueUid()); - ComponentInstanceInput instanceProperty = result.left().value(); - - resultOp = Either.left(instanceProperty); - return resultOp; - - } else { - log.debug("Failed to update property value {} in resource instance {}", inputProperty, resourceInstanceId); - - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); - - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - - return resultOp; - } - } - - } finally { - if (resultOp == null || resultOp.isRight()) { - janusGraphDao.rollback(); - } else { - janusGraphDao.commit(); - } - // unlock resource - graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); - } - - } - public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) { - validateUserExists(userId, "delete Property Value", false); + validateUserExists(userId); Either<ComponentInstanceProperty, ResponseFormat> resultOp = null; @@ -2317,32 +2176,27 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } - private Either<Component, ResponseFormat> getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) { + private Component getAndValidateOriginComponentOfComponentInstance(Component containerComponent, ComponentInstance componentInstance) { - Either<Component, ResponseFormat> eitherResponse = null; - ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType); + ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponent.getComponentType()); Component component; - ResponseFormat errorResponse; Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid()); if (getComponentRes.isRight()) { log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName()); ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType); - errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); - eitherResponse = Either.right(errorResponse); + throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING); } - if (eitherResponse == null) { - component = getComponentRes.left().value(); - LifecycleStateEnum resourceCurrState = component.getLifecycleState(); - if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) { - ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE; - errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString()); - eitherResponse = Either.right(errorResponse); - } + component = getComponentRes.left().value(); + LifecycleStateEnum resourceCurrState = component.getLifecycleState(); + if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) { + ActionStatus actionStatus = ActionStatus.CONTAINER_CANNOT_CONTAIN_COMPONENT_IN_STATE; + throw new ByActionStatusComponentException(actionStatus, containerComponent.getComponentType().toString(), resourceCurrState.toString()); } - if (eitherResponse == null) { - eitherResponse = Either.left(getComponentRes.left().value()); + if (component.isArchived() == true){ + ActionStatus actionStatus = ActionStatus.COMPONENT_IS_ARCHIVED; + throw new ByActionStatusComponentException(actionStatus, component.getName()); } - return eitherResponse; + return component; } public Either<Set<String>, ResponseFormat> forwardingPathOnVersionChange(String containerComponentParam, @@ -2350,20 +2204,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { String componentInstanceId, ComponentInstance newComponentInstance) { Either<Set<String>, ResponseFormat> resultOp; - Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - return Either.right(validateComponentType.right().value()); - } - final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); + final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam); ComponentParametersView componentParametersView = getComponentParametersViewForForwardingPath(); //Fetch Component - Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = - validateComponentExists(containerComponentId, containerComponentType, componentParametersView); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - Component containerComponent = validateComponentExists.left().value(); + Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, componentParametersView); //Fetch current component instance Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance = @@ -2379,7 +2224,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { String resourceId = newComponentInstance.getComponentUid(); Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId); if (componentExistsRes.isRight()) { - log.debug("Failed to find resource {} ", resourceId); + log.debug("Failed to find resource {}", resourceId); resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse (componentExistsRes.right().value()), resourceId)); return resultOp; @@ -2390,12 +2235,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } //Fetch component using new component instance uid - Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance); - if (eitherResourceName.isRight()) { - resultOp = Either.right(eitherResourceName.right().value()); - return resultOp; - } - Component updatedContainerComponent=eitherResourceName.left().value(); + Component updatedContainerComponent=getOriginComponentFromComponentInstance(newComponentInstance); Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent, currentResourceInstance, updatedContainerComponent); resultOp=Either.left(toDeleteForwardingPaths); @@ -2406,7 +2246,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance, Component updatedContainerComponent) { DataForMergeHolder dataForMergeHolder=new DataForMergeHolder(); - dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getUniqueId()); + dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getName()); Service service = (Service) containerComponent; ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils(); @@ -2422,35 +2262,20 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return componentParametersView; } - public Either<ComponentInstance, ResponseFormat> changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) { + public ComponentInstance changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) { - User user = validateUserExists(userId, "change Component Instance Version", false); - - Either<ComponentInstance, ResponseFormat> resultOp = null; - - Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - return Either.right(validateComponentType.right().value()); - } - - final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); + User user = validateUserExists(userId); + final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam); ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.setIgnoreCapabiltyProperties(false); - Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, componentParametersView); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); - Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } + org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, componentParametersView); + + validateCanWorkOnComponent(containerComponent, userId); Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId); if (resourceInstanceStatus.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId)); - return resultOp; + throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId); } ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value(); @@ -2458,84 +2283,48 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType ); } - public Either<ComponentInstance, ResponseFormat> changeInstanceVersion(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance currentResourceInstance, - ComponentInstance newComponentInstance, User user, final ComponentTypeEnum containerComponentType ) { - Either<ComponentInstance, ResponseFormat> resultOp = null; + public ComponentInstance changeInstanceVersion(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance currentResourceInstance, + ComponentInstance newComponentInstance, User user, final ComponentTypeEnum containerComponentType ) { + boolean failed = false; Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus; - Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion"); - String containerComponentId = containerComponent.getUniqueId(); - String componentInstanceId = currentResourceInstance.getUniqueId(); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - try { - - + lockComponent(containerComponent, "changeComponentInstanceVersion"); + String containerComponentId = containerComponent.getUniqueId(); + String componentInstanceId = currentResourceInstance.getUniqueId(); if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) { - resultOp = Either.left(currentResourceInstance); - return resultOp; - + return currentResourceInstance; } String resourceId = newComponentInstance.getComponentUid(); - - Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId); if (componentExistsRes.isRight()) { - log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId); - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId)); - return resultOp; + log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId, componentExistsRes.right().value()); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId); } else if (!componentExistsRes.left().value()) { log.debug("The resource {} not found ", resourceId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); - return resultOp; + throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, resourceId); } - Either<Component, ResponseFormat> eitherOriginComponent = getInstanceOriginNode(currentResourceInstance); + Component eitherOriginComponent = getInstanceOriginNode(currentResourceInstance); - if (eitherOriginComponent.isRight()) { - resultOp = Either.right(eitherOriginComponent.right().value()); - return resultOp; - } - DataForMergeHolder dataHolder = compInstMergeDataBL.saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent.left().value()); - resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType); - if (resultOp.isRight()) { - log.debug("failed to delete resource instance {}", resourceId); - return resultOp; - } - ComponentInstance resResourceInfo = resultOp.left().value(); + DataForMergeHolder dataHolder = compInstMergeDataBL.saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent); + ComponentInstance resResourceInfo = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType); Component origComponent = null; OriginTypeEnum originType = currentResourceInstance.getOriginType(); if (originType == OriginTypeEnum.ServiceProxy) { Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy"); - if (serviceProxyOrigin.isRight()) { - log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()))); - } + if (isServiceProxyOrigin(serviceProxyOrigin)) + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())); origComponent = serviceProxyOrigin.left().value(); StorageOperationStatus fillProxyRes = fillProxyInstanceData(newComponentInstance, origComponent); - if (fillProxyRes != StorageOperationStatus.OK) { - log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes))); - - } + if (isFillProxyRes(fillProxyRes)) + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes)); newComponentInstance.setOriginType(originType); }else{ - - - Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance); - - if (eitherResourceName.isRight()) { - resultOp = Either.right(eitherResourceName.right().value()); - return resultOp; - } - - origComponent = eitherResourceName.left().value(); - + origComponent = getOriginComponentFromComponentInstance(newComponentInstance); newComponentInstance.setName(resResourceInfo.getName()); } @@ -2544,28 +2333,13 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { newComponentInstance.setPosY(resResourceInfo.getPosY()); newComponentInstance.setDescription(resResourceInfo.getDescription()); - resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user); - - if (resultOp.isRight()) { - log.debug("failed to create resource instance {}", resourceId); - return resultOp; - } - - ComponentInstance updatedComponentInstance = resultOp.left().value(); - if (resultOp.isRight()) { - log.debug("failed to create resource instance {}", resourceId); - return resultOp; - } - + ComponentInstance updatedComponentInstance = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user); dataHolder.setCurrInstanceNode(origComponent); - Either<Component, ResponseFormat> mergeStatusEither = compInstMergeDataBL.mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId()); - if (mergeStatusEither.isRight()) { - return Either.right(mergeStatusEither.right().value()); - } + Component mergeStatusEither = compInstMergeDataBL.mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId()); ActionStatus postChangeVersionResult = onChangeInstanceOperationOrchestrator.doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance); if (postChangeVersionResult != ActionStatus.OK) { - return Either.right(componentsUtils.getResponseFormat(postChangeVersionResult)); + throw new ByActionStatusComponentException(postChangeVersionResult); } ComponentParametersView filter = new ComponentParametersView(true); @@ -2574,59 +2348,62 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { if (updatedComponentRes.isRight()) { StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value(); ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); log.debug("Component with id {} was not found", containerComponentId); - return Either.right(responseFormat); + throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING); } resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(), updatedComponentInstance.getUniqueId()); if (resourceInstanceStatus.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId())); - return resultOp; + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse + (resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId()); } - resultOp = Either.left(resourceInstanceStatus.left().value()); - return resultOp; + return resourceInstanceStatus.left().value(); - } finally { - unlockComponent(resultOp, containerComponent); + }catch (ComponentException e){ + failed = true; + throw e; + }finally { + unlockComponent(failed, containerComponent); } } + private boolean isFillProxyRes(StorageOperationStatus fillProxyRes) { + if (fillProxyRes != StorageOperationStatus.OK) { + log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes); + return true; + } + return false; + } + // US831698 - public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) { - final String ECOMP_ERROR_CONTEXT = "Get Component Instance Properties By Id"; + public List<ComponentInstanceProperty> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) { Component containerComponent = null; - Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null; + boolean failed = false; try { - validateUserExists(userId, ECOMP_ERROR_CONTEXT, false); - - Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentTypeParam); - if (validateComponentType.isRight()) { - resultOp = Either.right(validateComponentType.right().value()); - return resultOp; - } + validateUserExists(userId); + validateComponentType(containerComponentTypeParam); Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId); if (validateContainerComponentExists.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()))); - return resultOp; + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())); } containerComponent = validateContainerComponentExists.left().value(); Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId); if (resourceInstanceStatus.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); - return resultOp; + throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId); } List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId); if (CollectionUtils.isEmpty(instanceProperties)) { instanceProperties = new ArrayList<>(); } - resultOp = Either.left(instanceProperties); - return resultOp; - } finally { - unlockComponent(resultOp, containerComponent); + return instanceProperties; + }catch (ComponentException e){ + failed = true; + throw e; + }finally { + unlockComponent(failed, containerComponent); } } @@ -2668,20 +2445,17 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { public Either<ComponentInstance, ResponseFormat> deleteServiceProxy() { // TODO Add implementation - Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance()); - return result; + return Either.left(new ComponentInstance()); } public Either<ComponentInstance, ResponseFormat> createServiceProxy() { // TODO Add implementation - Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance()); - return result; + return Either.left(new ComponentInstance()); } public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion() { // TODO Add implementation - Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance()); - return result; + return Either.left(new ComponentInstance()); } private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) { @@ -2753,6 +2527,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { if (resourceInstanceForUpdate.getSourceModelUid() == null) { resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid()); } + if (resourceInstanceForUpdate.getCreatedFrom() == null) { + resourceInstanceForUpdate.setCreatedFrom(origInstanceForUpdate.getCreatedFrom()); + } return resourceInstanceForUpdate; } /** @@ -2766,43 +2543,29 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { * @param ownerId * @return */ - public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, String userId) { + public List<ComponentInstanceProperty> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, String userId) { Component containerComponent = null; - Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null; + List<ComponentInstanceProperty> resultOp = null; try { - validateUserExists(userId, "Get Component Instance Properties By Id", false); - if(resultOp == null){ - Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentType); - if (validateComponentType.isRight()) { - resultOp = Either.right(validateComponentType.right().value()); - } - } - if(resultOp == null){ - Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaFullElement(containerComponentId); - if (validateContainerComponentExists.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()))); - } else { - containerComponent = validateContainerComponentExists.left().value(); - } - } - if(resultOp == null){ - Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId); - if (resourceInstanceStatus.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); - } else { - resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId, resourceInstanceStatus.left().value().getCapabilities()); - } - } - return resultOp; - } finally { - unlockComponent(resultOp, containerComponent); - } + validateUserExists(userId); + validateComponentType(containerComponentType); + containerComponent = toscaOperationFacade.getToscaFullElement(containerComponentId).left().on(this::componentException); + ComponentInstance resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId).left().on(this::componentInstanceException); + resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId, resourceInstanceStatus.getCapabilities()); + } catch(StorageException e){ + unlockRollbackWithException(containerComponent, e); + } catch (ComponentException e) { + unlockRollbackWithException(containerComponent, e); + } catch (Exception e){ + unlockRollbackWithException(containerComponent, new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR)); + } + unlockWithCommit(containerComponent); + return resultOp; } - private Either<List<ComponentInstanceProperty>, ResponseFormat> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId, Map<String, List<CapabilityDefinition>> instanceCapabilities) { - Either<List<ComponentInstanceProperty>, ResponseFormat> result = null; + private List<ComponentInstanceProperty> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId, Map<String, List<CapabilityDefinition>> instanceCapabilities) { CapabilityDefinition foundCapability; if (MapUtils.isNotEmpty(instanceCapabilities)) { List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType); @@ -2810,43 +2573,27 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst(); if (capabilityOpt.isPresent()) { foundCapability = capabilityOpt.get(); - result = Either.left(foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties()); + return foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties(); } } } - if (result == null) { - result = fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId); - } - return result; + return fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId); } - private Either<List<ComponentInstanceProperty>, ResponseFormat> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId) { - Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null; + private List<ComponentInstanceProperty> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId) { try { - Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties = toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId); - if(getComponentInstanceCapabilityProperties != null) { - if (getComponentInstanceCapabilityProperties.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentInstanceCapabilityProperties.right().value()), capabilityType, instanceId, componentId)); - } else { - resultOp = Either.left(getComponentInstanceCapabilityProperties.left().value()); - } - } else { - resultOp = Either.left(new ArrayList<>()); - } + return toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId) + .left() + .on(this::componentInstancePropertyListException); } catch(Exception e){ - log.error("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + log.debug("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e); + throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } - return resultOp; } - private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance, + /*private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance, String capabilityType, String capabilityName, String ownerId) { String componentInstanceUniqueId = foundResourceInstance.getUniqueId(); - StringBuilder sb = new StringBuilder(componentInstanceUniqueId); - sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName); - String capKey = sb.toString(); - Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities()) .orElse(Collections.emptyMap()); List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList()); @@ -2857,6 +2604,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); StorageOperationStatus status; if (instanceProperty.isPresent()) { + String capKey = ModelConverter.buildCapabilityPropertyKey(foundResourceInstance.getOriginType().isAtomicType(), capabilityType, capabilityName, componentInstanceUniqueId, cap.get()); instanceProperty.get().setValue(newValue); List<String> path = new ArrayList<>(); path.add(componentInstanceUniqueId); @@ -2873,13 +2621,13 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } return componentsUtils.getResponseFormat(ActionStatus.OK); - } + }*/ - public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, + /*public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, List<ComponentInstanceProperty> properties, String userId) { Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null; - validateUserExists(userId, "update instance capability property", false); + validateUserExists(userId); if (componentTypeEnum == null) { BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO); @@ -2894,7 +2642,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { Component containerComponent = getResourceResult.left().value(); if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) { - log.info("Restricted operation for user: {sourcePropList} on component {}", userId, containerComponentId); + log.info("Restricted operation for user: {} on component {}", userId, containerComponentId); return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId); @@ -2918,9 +2666,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { try { for (ComponentInstanceProperty property : properties) { - Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false); + Either<String, ResponseFormat> newPropertyValueEither = validatePropertyObjectValue(property, false); newPropertyValueEither.bimap(updatedValue -> - updateCapabilityPropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName, ownerId), + updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName, ownerId), Either::right); } Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); @@ -2942,14 +2690,13 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { // unlock resource graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType()); } - } + }*/ public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, List<ComponentInstanceProperty> properties, String userId) { Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null; - validateUserExists(userId, "update instance capability property", false); - + validateUserExists(userId); if (componentTypeEnum == null) { BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO); return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); @@ -2980,9 +2727,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { try { for (ComponentInstanceProperty property : properties) { - Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false); + Either<String, ResponseFormat> newPropertyValueEither = validatePropertyObjectValue(property, property.getValue(), false); newPropertyValueEither.bimap(updatedValue -> - updateCapabilityPropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName), + updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName), Either::right); } Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); @@ -3021,62 +2768,67 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { Component origComponent = getOrigComponent.left().value(); - Either<Boolean, ResponseFormat> lockComponent = lockComponent(origComponent, "copyComponentInstance"); - if (lockComponent.isRight()) { + try { + lockComponent(origComponent, "copyComponentInstance"); + + } catch (ComponentException e) { log.error("destComponentInstance's data is {}", origComponent.toString()); - return Either.right(lockComponent.right().value()); + return Either.right(componentsUtils.getResponseFormat( + ActionStatus.USER_DEFINED, "Failed to lock component destComponentInstance's data is {}", origComponent.toString())); } - - Either<ComponentInstance, ResponseFormat> actionResponse = null; + boolean failed = false; + ComponentInstance actionResponse = null; try { + actionResponse = createComponentInstance( "services", containerComponentId, userId, inputComponentInstance, true, false); - if (actionResponse.isRight()) { - log.error(FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS); - return Either.right(componentsUtils.getResponseFormat( - ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS)); - } - + } catch (ComponentException e) { + failed = true; + throw e; } finally { // on failure of the create instance unlock the resource and rollback the transaction. - if (null == actionResponse || actionResponse.isRight()) { + if (null == actionResponse || failed) { janusGraphDao.rollback(); + log.error("Failed to copy the component instance to the canvas"); + + unlockComponent(failed, origComponent); + + return Either.right(componentsUtils.getResponseFormat( + ActionStatus.USER_DEFINED, "Failed to copy the component instance to the canvas")); } - unlockComponent(actionResponse, origComponent); } Either<String, ResponseFormat> resultOp = null; try { - ComponentInstance destComponentInstance = actionResponse.left().value(); + ComponentInstance destComponentInstance = actionResponse; log.debug("destComponentInstance's data is {}", destComponentInstance.toString()); resultOp = deepCopyComponentInstance( origComponent, containerComponentId, componentInstanceId, destComponentInstance, userId); - if (resultOp.isRight()) { - log.error("Failed to deep copy component instance"); - return Either.right(componentsUtils.getResponseFormat( - ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas")); - } resultMap.put("componentInstance", destComponentInstance); - return Either.left(resultMap); } finally { + // unlock resource if (resultOp == null || resultOp.isRight()) { + unlockComponent(true, origComponent); janusGraphDao.rollback(); - + log.error("Failed to deep copy component instance"); + return Either.right(componentsUtils.getResponseFormat( + ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas")); } else { + unlockComponent(false, origComponent); janusGraphDao.commit(); log.debug("Success trasaction commit"); } - // unlock resource - unlockComponent(resultOp, origComponent); } + + return Either.left(resultMap); } private Either<String, ResponseFormat> deepCopyComponentInstance( @@ -3160,8 +2912,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { log.debug("Now start to update inputs"); if (sourceProp.getGetInputValues() != null) { - if (sourceProp.getGetInputValues().isEmpty()) { - log.debug("source property input values empty"); + if (sourceProp.getGetInputValues().size() < 1) { + log.debug("property is return from input, set by man"); break; } log.debug("Now starting to copy the {} property", destPropertyName); @@ -3243,7 +2995,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { Either<ComponentInstanceProperty, ResponseFormat> resultOp = null; - validateUserExists(userId, "Create or Update attribute value", false); + validateUserExists(userId); if (componentTypeEnum == null) { BeEcompErrorManager.getInstance().logInvalidInputError( @@ -3398,22 +3150,12 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { List<String> deleteErrorIds = new ArrayList<>(); Map<String, List<String>> deleteErrorMap = new HashMap<>(); - Either<Component, ResponseFormat> validateResponse = validateUser(containerComponentType, componentId, userId); - if (validateResponse.isRight()) { - deleteErrorMap.put("deleteFailedIds", componentInstanceIdList); - return deleteErrorMap; - } - Component containerComponent = validateResponse.left().value(); - - Either<Boolean, ResponseFormat> lockComponent = lockComponent( - containerComponent, "batchDeleteComponentInstance"); - if (lockComponent.isRight()) { - log.error("Failed to lockComponent containerComponent"); - deleteErrorMap.put("deleteFailedIds", componentInstanceIdList); - return deleteErrorMap; - } + validateUserExists(userId); + org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, ComponentTypeEnum.findByParamName(containerComponentType), null); + boolean failed = false; try { + lockComponent(containerComponent, "batchDeleteComponentInstance"); for (String eachInstanceId : componentInstanceIdList) { Either<ComponentInstance, ResponseFormat> actionResponse = batchDeleteComponentInstance( containerComponent, containerComponentType, componentId, eachInstanceId); @@ -3426,35 +3168,12 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { //sending the ids of the error nodes that were not deleted to UI deleteErrorMap.put("deleteFailedIds", deleteErrorIds); return deleteErrorMap; - } finally { - unlockComponent(validateResponse, containerComponent); - } - } - - private Either<Component, ResponseFormat> validateUser(String containerComponentParam, - String containerComponentId, - String userId) { - validateUserExists(userId, "delete Component Instance", false); - Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - log.error("ComponentType[{}] doesn't support", containerComponentParam); - return Either.right(validateComponentType.right().value()); - } - - final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); - Either<Component, ResponseFormat> validateComponentExists = validateComponentExists( - containerComponentId, containerComponentType, null); - if (validateComponentExists.isRight()) { - log.error("Component Id[{}] doesn't exist", containerComponentId); - return Either.right(validateComponentExists.right().value()); - } - - Component containerComponent = validateComponentExists.left().value(); - Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); + }catch (ComponentException e){ + failed = true; + throw e; + }finally { + unlockComponent(failed, containerComponent); } - return Either.left(containerComponent); } private Either<ComponentInstance, ResponseFormat> batchDeleteComponentInstance(Component containerComponent, @@ -3462,17 +3181,21 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { String containerComponentId, String componentInstanceId) { - Either<ComponentInstance, ResponseFormat> resultOp; + ComponentInstance resultOp; final ComponentTypeEnum containerComponentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentTypeEnum); - - if (resultOp.isRight()) { + boolean failed = false; + try { + resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentTypeEnum); + log.info("Successfully deleted instance with id {}", componentInstanceId); + return Either.left(resultOp); + } + catch (ComponentException e){ log.error("Failed to deleteComponentInstance with instanceId[{}]", componentInstanceId); - return Either.right(resultOp.right().value()); + return Either.right(new ResponseFormat()); } - log.info("Successfully deleted instance with id {}", componentInstanceId); - return Either.left(resultOp.left().value()); + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java index ba256d4c84..14a193fde4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java @@ -22,20 +22,26 @@ package org.openecomp.sdc.be.components.impl; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; -import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.exception.ResponseFormat; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.*; +import java.security.SecureRandom; +import java.util.ArrayList; import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; import java.util.stream.Collectors; /** @@ -47,7 +53,7 @@ import java.util.stream.Collectors; @Component("compositionBusinessLogic") public class CompositionBusinessLogic { private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic; - + private static final Logger log = Logger.getLogger(CompositionBusinessLogic.class.getName()); private static final int VFC_CANVAS_ELEMENT_SIZE = 50; private static final int CP_CANVAS_ELEMENT_SIZE = 21; private static final int CANVAS_WIDTH = 1000; @@ -73,17 +79,11 @@ public class CompositionBusinessLogic { // Set Relative Locations According to Canvas Size componentInstanceLocations.entrySet().forEach(this::setRelativePosition); // Update in DB - componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME,resource.getUniqueId(), - userId, resource.getComponentInstances(), false) - .left() - .on(this::throwComponentException); + componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME,resource, resource.getUniqueId(), + userId, resource.getComponentInstances(), false); } } - private List<ComponentInstance> throwComponentException(ResponseFormat responseFormat) { - throw new ByResponseFormatComponentException(responseFormat); - } - private void setRelativePosition(Entry<ImmutablePair<Double, Double>, ComponentInstance> entry) { int xCenter = CANVAS_WIDTH / 2; int yCenter = CANVAS_HEIGHT / 2; @@ -284,5 +284,19 @@ public class CompositionBusinessLogic { } return relativeElementPosition; } + protected void validateAndSetDefaultCoordinates(ComponentInstance resourceInstance) { + int xCenter = CANVAS_WIDTH / 2; + int yCenter = CANVAS_HEIGHT / 2; + double leftLimit = -10D; + double rightLimit = -1D; + double generatedDouble = leftLimit + new SecureRandom().nextDouble() * (rightLimit - leftLimit); + + if (StringUtils.isEmpty(resourceInstance.getPosX())|| StringUtils.isEmpty(resourceInstance.getPosY())){ + resourceInstance.setPosX(calculateCompositionPosition(xCenter, generatedDouble, resourceInstance)); + resourceInstance.setPosY(calculateCompositionPosition(yCenter, generatedDouble, resourceInstance)); + log.debug("Missing Failed PosX/PosY values. new values generated automatically. PosX = {} and PosY = {}", resourceInstance.getPosX(), resourceInstance.getPosY()); + } + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java index 5c7c35a6b5..8b4c1c3e8b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,6 +21,7 @@ package org.openecomp.sdc.be.components.impl; import fj.data.Either; +import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -61,12 +62,12 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic { @Autowired public ConsumerBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - ArtifactsOperations artifactToscaOperation) { + IGroupOperation groupOperation, + IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, + InterfaceOperation interfaceOperation, + InterfaceLifecycleOperation interfaceLifecycleTypeOperation, + ArtifactsOperations artifactToscaOperation) { super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); } @@ -135,8 +136,10 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic { return Either.right(responseFormat); } log.debug("get user from DB"); - Either<User, ActionStatus> eitherCreator = userAdmin.getUser(user.getUserId(), false); - if (eitherCreator.isRight() || eitherCreator.left().value() == null) { + User userFromDB; + try { + userFromDB = userAdmin.getUser(user.getUserId(), false); + }catch (ByActionStatusComponentException e){ log.debug("createEcompUser method - user is not listed. userId= {}", user.getUserId()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS); log.debug(AUDIT_BEFORE_SENDING_RESPONSE); @@ -144,7 +147,7 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic { return Either.right(responseFormat); } - user = eitherCreator.left().value(); + user = userFromDB; // validate user role log.debug("validate user role"); if (!user.getRole().equals(Role.ADMIN.name())) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java index d29a2c4458..1757fcdf01 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java @@ -34,7 +34,12 @@ import org.openecomp.sdc.exception.ResponseFormat; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringReader; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -200,7 +205,7 @@ public class CsarValidationUtils { return Either.left(new ImmutablePair<>(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE, artifactsFileContents)); } - public static Either<ImmutablePair<String, byte[]>, ResponseFormat> getArtifactsContent(String csarUUID, Map<String, byte[]> csar, String artifactPath, String artifactName, ComponentsUtils componentsUtils) { + public static Either<ImmutablePair<String, byte[]>, ResponseFormat> getArtifactContent(String csarUUID, Map<String, byte[]> csar, String artifactPath, String artifactName, ComponentsUtils componentsUtils) { if (!csar.containsKey(artifactPath)) { log.debug("Entry-Definitions entry not found in Artifacts/HEAT.meta file, csar ID {}", csarUUID); BeEcompErrorManager.getInstance().logInternalDataError(ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java index a9502b14f4..5ba9cfbe87 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java @@ -37,7 +37,11 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Component; import javax.annotation.Resource; -import java.util.*; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.stream.Collectors; @Component("dataTypeImportManager") diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java index 5d9a06cc4c..087685292b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java @@ -39,13 +39,16 @@ import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; import org.openecomp.sdc.be.resources.data.auditing.DistributionStatusEvent; import org.openecomp.sdc.common.datastructure.AuditingFieldsKey; -import org.openecomp.sdc.common.datastructure.ESTimeBasedEvent; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; @Component("distributionMonitoringBusinessLogic") public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic { @@ -77,7 +80,7 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic { public Either<DistributionStatusListResponse, ResponseFormat> getListOfDistributionStatus(String did, String userId) { - validateUserExists(userId, "get List Of Distribution Status", false); + validateUserExists(userId); log.trace("getListOfDistributionStatus for did {}", did); Either<List<DistributionStatusEvent>, ActionStatus> distributionStatus = cassandraDao.getListOfDistributionStatuses(did); @@ -88,7 +91,7 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic { List<DistributionStatusInfo> distribStatusInfoList = new ArrayList<>(); List<DistributionStatusEvent> distributionStatusEventList = distributionStatus.left().value(); if (distributionStatusEventList != null) { - for (ESTimeBasedEvent distributionStatusEvent : distributionStatusEventList) { + for (AuditingGenericEvent distributionStatusEvent : distributionStatusEventList) { distribStatusInfoList.add(new DistributionStatusInfo(distributionStatusEvent)); } } @@ -100,7 +103,7 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic { } public Either<DistributionStatusOfServiceListResponce, ResponseFormat> getListOfDistributionServiceStatus(String serviceUuid, String userId) { - validateUserExists(userId, "get List Of Distribution Service Status", false); + validateUserExists(userId); log.trace("getListOfDistributionServiceStatus for serviceUUID {}", serviceUuid); Either<List<? extends AuditingGenericEvent>, ActionStatus> status = cassandraDao.getServiceDistributionStatusesList(serviceUuid); @@ -127,7 +130,7 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic { String dNotifyStatus = ""; boolean isResult = false; List<? extends AuditingGenericEvent> auditingGenericEventList = serviceDidMap.get(did); - ESTimeBasedEvent resAuditingGenericEvent = null; + AuditingGenericEvent resAuditingGenericEvent = null; for (AuditingGenericEvent auditingGenericEvent : auditingGenericEventList) { auditingGenericEvent.fillFields(); @@ -174,7 +177,7 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic { return reslist; } - private String getStatusFromAuditEvent(ESTimeBasedEvent auditingGenericEvent) { + private String getStatusFromAuditEvent(AuditingGenericEvent auditingGenericEvent) { String status = ""; Object requestStatus = auditingGenericEvent.getFields().get(AuditingFieldsKey.AUDIT_STATUS.getDisplayName()); if (requestStatus instanceof String) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java index ca2e4a8078..711e6648ed 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java @@ -28,11 +28,13 @@ import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; 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.config.Configuration; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; @@ -40,14 +42,33 @@ import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum; import org.openecomp.sdc.be.datamodel.utils.NodeTypeConvertUtils; import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.*; -import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactType; +import org.openecomp.sdc.be.model.CatalogUpdateTimestamp; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Product; +import org.openecomp.sdc.be.model.PropertyScope; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.Tag; +import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.catalog.CatalogComponent; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.GroupingDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation; import org.openecomp.sdc.be.model.operations.api.IGroupOperation; @@ -56,9 +77,6 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.be.resources.data.ComponentMetadataData; -import org.openecomp.sdc.be.resources.data.ResourceMetadataData; -import org.openecomp.sdc.be.resources.data.ServiceMetadataData; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.resources.data.category.CategoryData; import org.openecomp.sdc.be.resources.data.category.SubCategoryData; @@ -69,14 +87,25 @@ import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.beans.factory.annotation.Autowired; import java.nio.charset.StandardCharsets; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; -import org.springframework.beans.factory.annotation.Autowired; import static org.apache.commons.lang.BooleanUtils.isTrue; +import static org.openecomp.sdc.be.components.impl.ImportUtils.Constants.DEFAULT_ICON; @org.springframework.stereotype.Component("elementsBusinessLogic") public class ElementBusinessLogic extends BaseBusinessLogic { @@ -106,7 +135,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic { this.elementOperation = elementOperation; this.userAdminManager = userAdminManager; } - /** * * @param user @@ -121,37 +149,25 @@ public class ElementBusinessLogic extends BaseBusinessLogic { Role currentRole = Role.valueOf(role); switch (currentRole) { - case DESIGNER: - response = handleDesigner(userId); - break; - - case TESTER: - response = handleTester(); - break; + case DESIGNER: + response = handleDesigner(userId); + break; - case GOVERNOR: - response = handleGovernor(); - break; + case PRODUCT_STRATEGIST: + response = handleProductStrategist(); + break; - case OPS: - response = handleOps(); - break; + case PRODUCT_MANAGER: + response = handleProductManager(userId); + break; - case PRODUCT_STRATEGIST: - response = handleProductStrategist(); - break; + case ADMIN: + response = handleAdmin(); + break; - case PRODUCT_MANAGER: - response = handleProductManager(userId); - break; - - case ADMIN: - response = handleAdmin(); - break; - - default: - response = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - break; + default: + response = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + break; } // converting the Set to List so the rest of the code will handle it normally (Was changed because the same element with the same uuid was returned twice) return convertedToListResponse(response); @@ -174,9 +190,8 @@ public class ElementBusinessLogic extends BaseBusinessLogic { Either<Map<String, Set<? extends Component>>, ResponseFormat> response; // userId should stay null Set<LifecycleStateEnum> lifecycleStates = new HashSet<>(); - Set<LifecycleStateEnum> lastStateStates = new HashSet<>(); lifecycleStates.add(LifecycleStateEnum.CERTIFIED); - response = getFollowedResourcesAndServices(null, lifecycleStates, lastStateStates); + response = getFollowedResourcesAndServices(null, lifecycleStates, new HashSet<>()); return response; } @@ -186,11 +201,9 @@ public class ElementBusinessLogic extends BaseBusinessLogic { Either<Map<String, Set<? extends Component>>, ResponseFormat> response; lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); - lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); lifecycleStates.add(LifecycleStateEnum.CERTIFIED); // more states - lastStateStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); + lastStateStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); response = getFollowedResourcesAndServices(userId, lifecycleStates, lastStateStates); return response; } @@ -212,23 +225,13 @@ public class ElementBusinessLogic extends BaseBusinessLogic { Either<Map<String, Set<? extends Component>>, ResponseFormat> response; lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); - lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); lifecycleStates.add(LifecycleStateEnum.CERTIFIED); // more states - lastStateStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); + lastStateStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); response = getFollowedProducts(userId, lifecycleStates, lastStateStates); return response; } - private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleOps() { - Set<DistributionStatusEnum> distStatus = new HashSet<>(); - distStatus.add(DistributionStatusEnum.DISTRIBUTION_APPROVED); - distStatus.add(DistributionStatusEnum.DISTRIBUTED); - - return handleFollowedCertifiedServices(distStatus); - } - private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleFollowedCertifiedServices(Set<DistributionStatusEnum> distStatus) { Either<List<Service>, StorageOperationStatus> services = toscaOperationFacade.getCertifiedServicesWithDistStatus(distStatus); @@ -243,14 +246,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } } - private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleTester() { - Set<LifecycleStateEnum> lifecycleStates = new HashSet<>(); - lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); - - return getFollowedResourcesAndServices(null, lifecycleStates, null); - } - private Either<Map<String, Set<? extends Component>>, ResponseFormat> getFollowedResourcesAndServices(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates) { try { @@ -303,20 +298,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic { String componentType = componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue(); CategoryTypeEnum categoryType = CategoryTypeEnum.CATEGORY; - User user; - Either<User, ResponseFormat> validateUser = validateUser(userId); - if (validateUser.isRight()) { - log.debug(VALIDATION_OF_USER_FAILED_USER_ID, userId); - ResponseFormat responseFormat = validateUser.right().value(); - user = new User(); - user.setUserId(userId); - String currCategoryName = (category == null ? null : category.getName()); - handleCategoryAuditing(responseFormat, user, currCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - user = validateUser.left().value(); - + User user = validateUserExists(userId); if (category == null) { log.debug("Category json is invalid"); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); @@ -363,6 +345,11 @@ public class ElementBusinessLogic extends BaseBusinessLogic { String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(categoryName); category.setNormalizedName(normalizedName); + if (ValidationUtils.validateCategoryIconNotEmpty(category.getIcons())){ + log.debug("createCategory: setting category icon to default icon since service category was created without an icon "); + category.setIcons(Arrays.asList(DEFAULT_ICON)); + } + NodeTypeEnum nodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, categoryType); Either<Boolean, ActionStatus> categoryUniqueEither = elementOperation.isCategoryUniqueForType(nodeType, normalizedName); @@ -416,7 +403,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic { String origSubCategoryName = subCategoryName; User user; try{ - user = validateUserExists(userId, "createSubCategory", false); + user = validateUserExists(userId); } catch(ByActionStatusComponentException e){ ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); handleComponentException(userId, auditingAction, componentType, parentCategoryName, origSubCategoryName, @@ -579,7 +566,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic { User user; try{ - user = validateUserExists(userId, "create Grouping", false); + user = validateUserExists(userId); } catch(ByResponseFormatComponentException e){ ResponseFormat responseFormat = e.getResponseFormat(); handleComponentException(grouping, userId, auditingAction, componentType, parentCategoryName, @@ -741,7 +728,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return Either.right(responseFormat); } try { - user = validateUserExists(userId, "get All Categories", false); + user = validateUserExists(userId); } catch (ByActionStatusComponentException e){ responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); handleComponentException(componentType, userId, responseFormat); @@ -778,7 +765,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic { ResponseFormat responseFormat; UiCategories categories = new UiCategories(); - User user = validateUserExists(userId, "get all categories", false); + User user = validateUserExists(userId); // GET resource categories Either<List<CategoryDefinition>, ActionStatus> getResourceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ResourceNewCategory, false); @@ -797,23 +784,13 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return Either.right(responseFormat); } categories.setServiceCategories(getServiceCategoriesByType.left().value()); - - // GET product categories - Either<List<CategoryDefinition>, ActionStatus> getProductCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ProductCategory, false); - if (getProductCategoriesByType.isRight()) { - responseFormat = componentsUtils.getResponseFormat(getProductCategoriesByType.right().value()); - componentsUtils.auditGetCategoryHierarchy(user, ComponentTypeEnum.PRODUCT.getValue(), responseFormat); - return Either.right(responseFormat); - } - - categories.setProductCategories(getProductCategoriesByType.left().value()); + categories.setProductCategories(new ArrayList<>()); return Either.left(categories); - } public Either<CategoryDefinition, ResponseFormat> deleteCategory(String categoryId, String componentTypeParamName, String userId) { - validateUserExists(userId, "delete Category", false); + validateUserExists(userId); ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); if (componentTypeEnum == null) { @@ -835,7 +812,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic { public Either<SubCategoryDefinition, ResponseFormat> deleteSubCategory(String parentSubCategoryId, String componentTypeParamName, String userId) { - validateUserExists(userId, "delete Sub Category", false); + validateUserExists(userId); ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); if (componentTypeEnum == null) { @@ -857,7 +834,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic { public Either<GroupingDefinition, ResponseFormat> deleteGrouping(String groupingId, String componentTypeParamName, String userId) { - validateUserExists(userId, "delete Grouping", false); + validateUserExists(userId); ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); if (componentTypeEnum == null) { @@ -877,31 +854,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return Either.left(deletedGrouping); } - private Either<User, ResponseFormat> validateUser(String userId) { - - // validate user exists - if (userId == null) { - log.debug("UserId is null"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION)); - } - - Either<User, ActionStatus> userResult = userAdminManager.getUser(userId, false); - if (userResult.isRight()) { - ResponseFormat responseFormat; - if (userResult.right().value().equals(ActionStatus.USER_NOT_FOUND)) { - log.debug("Not authorized user, userId = {}", userId); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - } else { - log.debug("Failed to authorize user, userId = {}", userId); - responseFormat = componentsUtils.getResponseFormat(userResult.right().value()); - } - - return Either.right(responseFormat); - } - return Either.left(userResult.left().value()); - // ========================================- - } - private Either<Boolean, ResponseFormat> validateUserRole(User user, ComponentTypeEnum componentTypeEnum) { String role = user.getRole(); boolean validAdminAction = role.equals(Role.ADMIN.name()) && (componentTypeEnum == ComponentTypeEnum.SERVICE || componentTypeEnum == ComponentTypeEnum.RESOURCE); @@ -919,10 +871,10 @@ public class ElementBusinessLogic extends BaseBusinessLogic { boolean validResourceAction = componentType == ComponentTypeEnum.RESOURCE && (categoryType == CategoryTypeEnum.CATEGORY || categoryType == CategoryTypeEnum.SUBCATEGORY); boolean validServiceAction = componentType == ComponentTypeEnum.SERVICE && categoryType == CategoryTypeEnum.CATEGORY; boolean validProductAction = componentType == ComponentTypeEnum.PRODUCT; // can - // be - // any - // category - // type + // be + // any + // category + // type if (!(validResourceAction || validServiceAction || validProductAction)) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); @@ -981,25 +933,25 @@ public class ElementBusinessLogic extends BaseBusinessLogic { */ public Either<List<Tag>, ActionStatus> getAllTags(String userId) { - Either<User, ActionStatus> resp = validateUserExistsActionStatus(userId, "get All Tags"); - if (resp.isRight()) { - return Either.right(resp.right().value()); + ActionStatus status = validateUserExistsActionStatus(userId); + if (ActionStatus.OK != status) { + return Either.right(status); } return elementOperation.getAllTags(); } public Either<List<PropertyScope>, ActionStatus> getAllPropertyScopes(String userId) { - Either<User, ActionStatus> resp = validateUserExistsActionStatus(userId, "get All Property Scopes"); - if (resp.isRight()) { - return Either.right(resp.right().value()); + ActionStatus status = validateUserExistsActionStatus(userId); + if (ActionStatus.OK != status) { + return Either.right(status); } return elementOperation.getAllPropertyScopes(); } public Either<List<ArtifactType>, ActionStatus> getAllArtifactTypes(String userId) { - Either<User, ActionStatus> resp = validateUserExistsActionStatus(userId, "get All Artifact Types"); - if (resp.isRight()) { - return Either.right(resp.right().value()); + ActionStatus status = validateUserExistsActionStatus(userId); + if (ActionStatus.OK != status) { + return Either.right(status); } return elementOperation.getAllArtifactTypes(); } @@ -1008,13 +960,12 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return elementOperation.getAllDeploymentArtifactTypes(); } - public Either<Integer, ActionStatus> getDefaultHeatTimeout() { + public Either<Configuration.HeatDeploymentArtifactTimeout, ActionStatus> getDefaultHeatTimeout() { return elementOperation.getDefaultHeatTimeout(); } - public Either<Map<String, List<CatalogComponent>>, ResponseFormat> getCatalogComponents(String userId, List<OriginTypeEnum> excludeTypes) { + public Either<Map<String, List<CatalogComponent>>, ResponseFormat> getCatalogComponents(String userId, List<OriginTypeEnum> excludeTypes) { try { - validateUserExists(userId, "get Catalog Components", true); return toscaOperationFacade.getCatalogOrArchiveComponents(true, excludeTypes) .bimap(this::groupByComponentType, err -> componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(err))); @@ -1030,23 +981,19 @@ public class ElementBusinessLogic extends BaseBusinessLogic { if (map == null) { map = new HashMap<>(); } - if (map.get(RESOURCES) == null) { - map.put(RESOURCES, new ArrayList()); - } - if (map.get(SERVICES) == null) { - map.put(SERVICES, new ArrayList()); - } + map.computeIfAbsent(RESOURCES, k -> new ArrayList()); + map.computeIfAbsent(SERVICES, k -> new ArrayList()); return map; } private String cmptTypeToString(ComponentTypeEnum componentTypeEnum) { switch (componentTypeEnum) { - case RESOURCE: - return RESOURCES; - case SERVICE: - return SERVICES; - default: - throw new IllegalStateException("resources or services only"); + case RESOURCE: + return RESOURCES; + case SERVICE: + return SERVICES; + default: + throw new IllegalStateException("resources or services only"); } } @@ -1077,7 +1024,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value()), params.get(0), params.get(1), params.get(2))); } if (result.left().value().isEmpty()) {// no assets found for requested - // criteria + // criteria return Either.right(componentsUtils.getResponseFormat(ActionStatus.NO_ASSETS_FOUND, assetType, query)); } return Either.left(result.left().value()); @@ -1087,7 +1034,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic { Either<List<Component>, StorageOperationStatus> assetResult = Either.left(new LinkedList<>()); if (assetType == ComponentTypeEnum.RESOURCE) { - assetResult = getFilteredResouces(filters, inTransaction); + assetResult = getFilteredResources(filters, inTransaction); } else if (assetType == ComponentTypeEnum.SERVICE) { @@ -1096,7 +1043,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return assetResult; } - private <T> Either<List<T>, StorageOperationStatus> getFilteredServices(Map<FilterKeyEnum, String> filters, boolean inTransaction) { + private <T extends Component> Either<List<T>, StorageOperationStatus> getFilteredServices(Map<FilterKeyEnum, String> filters, boolean inTransaction) { Either<List<T>, StorageOperationStatus> components = null; @@ -1109,9 +1056,9 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } if (categoryName != null) { // primary filter - components = fetchByCategoryOrSubCategoryName(categoryName, NodeTypeEnum.ServiceNewCategory, NodeTypeEnum.Service, inTransaction, ServiceMetadataData.class, null); + components = fetchByCategoryOrSubCategoryName(categoryName, NodeTypeEnum.ServiceNewCategory, NodeTypeEnum.Service, inTransaction, null); if (components.isLeft() && distEnum != null) {// secondary filter - Predicate<T> statusFilter = p -> ((Service) p).getDistributionStatus().equals(distEnum); + Predicate<T> statusFilter = p -> ((Service) p).getDistributionStatus() == distEnum; return Either.left(components.left().value().stream().filter(statusFilter).collect(Collectors.toList())); } filters.remove(FilterKeyEnum.DISTRIBUTION_STATUS); @@ -1145,15 +1092,15 @@ public class ElementBusinessLogic extends BaseBusinessLogic { Map<GraphPropertyEnum, Object> additionalPropertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); switch (assetTypeEnum) { - case RESOURCE: - additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); - break; - case SERVICE: - additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); - break; - default: - log.debug("getCatalogComponentsByUuidAndAssetType: Corresponding ComponentTypeEnum not allowed for this API"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + case RESOURCE: + additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + break; + case SERVICE: + additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + break; + default: + log.debug("getCatalogComponentsByUuidAndAssetType: Corresponding ComponentTypeEnum not allowed for this API"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); } Either<List<Component>, StorageOperationStatus> componentsListByUuid = toscaOperationFacade.getComponentListByUuid(uuid, additionalPropertiesToMatch); @@ -1209,7 +1156,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return params; } - public Either<List<Component>, StorageOperationStatus> getFilteredResouces(Map<FilterKeyEnum, String> filters, boolean inTransaction) { + public Either<List<Component>, StorageOperationStatus> getFilteredResources(Map<FilterKeyEnum, String> filters, boolean inTransaction) { String subCategoryName = filters.get(FilterKeyEnum.SUB_CATEGORY); String categoryName = filters.get(FilterKeyEnum.CATEGORY); @@ -1230,11 +1177,10 @@ public class ElementBusinessLogic extends BaseBusinessLogic { if (!subCategoryData.isPresent()) { return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); } - return fetchByCategoryOrSubCategoryUid((String) subCategoryData.get().getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, NodeTypeEnum.Resource, inTransaction, - ResourceMetadataData.class, resourceType); + return fetchByCategoryOrSubCategoryUid(subCategoryData.get().getLeft().getUniqueId(), NodeTypeEnum.Resource, inTransaction, resourceType); } - return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, NodeTypeEnum.Resource, inTransaction, ResourceMetadataData.class, resourceType); + return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, NodeTypeEnum.Resource, inTransaction, resourceType); } if (subcategories != null) { return fetchByMainCategory(subcategories.left().value(), inTransaction, resourceType); @@ -1263,10 +1209,9 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return childNodes.stream().filter(matchName).findAny(); } - protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryUid(String categoryUid, NodeTypeEnum categoryType, NodeTypeEnum neededType, boolean inTransaction, - Class<S> clazz, ResourceTypeEnum resourceType) { + protected <T extends Component> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryUid(String categoryUid, NodeTypeEnum categoryType, boolean inTransaction, ResourceTypeEnum resourceType) { try { - return collectComponents(neededType, categoryUid, categoryType, clazz, resourceType); + return collectComponents(categoryType, categoryUid, resourceType); } finally { if (!inTransaction) { janusGraphDao.commit(); @@ -1274,8 +1219,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } } - protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName, NodeTypeEnum categoryType, NodeTypeEnum neededType, boolean inTransaction, - Class<S> clazz, ResourceTypeEnum resourceType) { + protected <T extends Component> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName, NodeTypeEnum categoryType, NodeTypeEnum neededType, boolean inTransaction, ResourceTypeEnum resourceType) { List<T> components = new ArrayList<>(); try { Class categoryClazz = categoryType == NodeTypeEnum.ServiceNewCategory ? CategoryData.class : SubCategoryData.class; @@ -1286,13 +1230,16 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); } for (GraphNode category : getCategory.left().value()) { - Either<List<T>, StorageOperationStatus> result = collectComponents(neededType, (String) category.getUniqueId(), categoryType, clazz, resourceType); - if (result.isRight()) { + Either<List<T>, StorageOperationStatus> result = collectComponents(neededType, category.getUniqueId(), resourceType); + if (result.isRight() && result.right().value() != StorageOperationStatus.NOT_FOUND) { return result; + } else if (result.isLeft()){ + components.addAll(result.left().value()); } - components.addAll(result.left().value()); } - + if (components.isEmpty()){ + return Either.right(StorageOperationStatus.NOT_FOUND); + } return Either.left(components); } finally { if (!inTransaction) { @@ -1302,25 +1249,38 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } - private <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> collectComponents(NodeTypeEnum neededType, String categoryUid, NodeTypeEnum categoryType, Class<S> clazz, ResourceTypeEnum resourceType) { + private <T extends Component> Either<List<T>, StorageOperationStatus> collectComponents(NodeTypeEnum neededType, String categoryUid, ResourceTypeEnum resourceType) { List<T> components = new ArrayList<>(); - Either<List<ImmutablePair<S, GraphEdge>>, JanusGraphOperationStatus> parentNodes = janusGraphGenericDao - .getParentNodes(UniqueIdBuilder.getKeyByNodeType(categoryType), categoryUid, GraphEdgeLabels.CATEGORY, neededType, clazz); - if (parentNodes.isLeft()) { - for (ImmutablePair<S, GraphEdge> component : parentNodes.left().value()) { - ComponentMetadataDataDefinition componentData = component.getLeft().getMetadataDataDefinition(); - Boolean isHighest = componentData.isHighestVersion(); - boolean isMatchingResourceType = isMatchingByResourceType(neededType, resourceType, componentData); - boolean isDeleted = isTrue(componentData.isDeleted()); - boolean isArchived = isTrue(componentData.isArchived()); - - if (isHighest && isMatchingResourceType && !isDeleted && !isArchived) { - Either<T, StorageOperationStatus> result = (Either<T, StorageOperationStatus>) toscaOperationFacade.getToscaElement(componentData.getUniqueId(), JsonParseFlagEnum.ParseMetadata); - if (result.isRight()) { - return Either.right(result.right().value()); - } - components.add(result.left().value()); + Either<GraphVertex, JanusGraphOperationStatus> categoryVertexById = janusGraphDao.getVertexById(categoryUid, JsonParseFlagEnum.NoParse); + if (categoryVertexById.isRight()){ + JanusGraphOperationStatus status = categoryVertexById.right().value(); + log.debug("#collectComponents Failed to get category vertex with uid {}, status is {}.", categoryUid, status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + GraphVertex categoryVertex = categoryVertexById.left().value(); + Either<List<GraphVertex>, JanusGraphOperationStatus> componentsVertices = janusGraphDao.getParentVertices(categoryVertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.ParseMetadata); + if (componentsVertices.isRight()){ + JanusGraphOperationStatus status = componentsVertices.right().value(); + log.debug("#collectComponents Failed to get components vertices of category {}, status is {}.", categoryVertex, status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + List<ComponentMetadataDataDefinition> componentsMetadataDataDefinition = componentsVertices.left().value() + .stream() + .filter(Objects::nonNull) + .filter(componentsVertex -> Objects.nonNull(componentsVertex.getType())) + .map(ModelConverter::convertToComponentMetadataDataDefinition) + .collect(Collectors.toList()); + for (ComponentMetadataDataDefinition component : componentsMetadataDataDefinition) { + boolean isHighest = isTrue(component.isHighestVersion()); + boolean isMatchingResourceType = isMatchingByResourceType(neededType, resourceType, component); + boolean isDeleted = isTrue(component.isDeleted()); + boolean isArchived = isTrue(component.isArchived()); + if (isHighest && isMatchingResourceType && !isDeleted && !isArchived) { + Either<T, StorageOperationStatus> result = toscaOperationFacade.getToscaElement(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata); + if (result.isRight()) { + return Either.right(result.right().value()); } + components.add(result.left().value()); } } return Either.left(components); @@ -1341,12 +1301,12 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return isMatching; } - private <T> Either<List<T>, StorageOperationStatus> fetchByMainCategory(List<ImmutablePair<SubCategoryData, GraphEdge>> subcategories, boolean inTransaction, ResourceTypeEnum resourceType) { + private <T extends Component> Either<List<T>, StorageOperationStatus> fetchByMainCategory(List<ImmutablePair<SubCategoryData, GraphEdge>> subcategories, boolean inTransaction, ResourceTypeEnum resourceType) { List<T> components = new ArrayList<>(); for (ImmutablePair<SubCategoryData, GraphEdge> subCategory : subcategories) { - Either<List<T>, StorageOperationStatus> fetched = fetchByCategoryOrSubCategoryUid((String) subCategory.getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, NodeTypeEnum.Resource, - inTransaction, ResourceMetadataData.class, resourceType); + Either<List<T>, StorageOperationStatus> fetched = fetchByCategoryOrSubCategoryUid(subCategory.getLeft().getUniqueId(), NodeTypeEnum.Resource, + inTransaction, resourceType); if (fetched.isRight()) { continue; } @@ -1385,4 +1345,16 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } } } + + + public CatalogUpdateTimestamp getCatalogUpdateTime(String userId) { + + try{ + return toscaOperationFacade.getCatalogTimes(); + + } finally { + janusGraphDao.commit(); + } + + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java index 8340aa46ab..2c824c8e23 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java @@ -21,13 +21,14 @@ package org.openecomp.sdc.be.components.impl; import fj.data.Either; +import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; +import org.openecomp.sdc.be.components.impl.lock.LockingTransactional; import org.openecomp.sdc.be.components.validation.AccessValidations; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.dto.ExternalRefDTO; import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ExternalReferencesOperation; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -82,62 +83,53 @@ public class ExternalRefsBusinessLogic { } } - public Either<String, ActionStatus> addExternalReference(ComponentTypeEnum componentType, String userId, String uuid, String componentInstanceName, String objectType, ExternalRefDTO ref) { - return this.doAction(componentType, userId, "POST", uuid, componentInstanceName, objectType, ref.getReferenceUUID(), ""); + @LockingTransactional + public Either<String, ActionStatus> addExternalReference(String componentId, ComponentTypeEnum componentType, String userId, String componentInstanceName, String objectType, ExternalRefDTO ref) { + return this.doAction(componentId, componentType, userId, "POST", componentId, componentInstanceName, objectType, ref.getReferenceUUID(), ""); } - public Either<String, ActionStatus> deleteExternalReference(ComponentTypeEnum componentType, String userId, String uuid, String componentInstanceName, String objectType, String reference) { - return this.doAction(componentType, userId, "DELETE", uuid, componentInstanceName, objectType, reference, ""); + @LockingTransactional + public Either<String, ActionStatus> deleteExternalReference(String componentId, ComponentTypeEnum componentType, String userId, String componentInstanceName, String objectType, String reference) { + return this.doAction(componentId, componentType, userId, "DELETE", componentId, componentInstanceName, objectType, reference, ""); } - public Either<String, ActionStatus> updateExternalReference(ComponentTypeEnum componentType, String userId, String uuid, String componentInstanceName, String objectType, String oldRefValue, String newRefValue) { - return this.doAction(componentType, userId, "PUT", uuid, componentInstanceName, objectType, oldRefValue, newRefValue); + @LockingTransactional + public Either<String, ActionStatus> updateExternalReference(String componentId, ComponentTypeEnum componentType, String userId, String componentInstanceName, String objectType, String oldRefValue, String newRefValue) { + return this.doAction(componentId, componentType, userId, "PUT", componentId, componentInstanceName, objectType, oldRefValue, newRefValue); } - private Either<String, ActionStatus> doAction(ComponentTypeEnum componentType, String userId, String action, String uuid, String componentInstanceName, String objectType, String ref1, String ref2){ + public String fetchComponentUniqueIdByUuid(String uuid, ComponentTypeEnum componentType){ Either<Component, StorageOperationStatus> latestServiceByUuid = toscaOperationFacade.getLatestComponentByUuid(uuid, createPropsToMatch(componentType)); if (latestServiceByUuid == null || latestServiceByUuid.isRight()){ - return Either.right(ActionStatus.RESOURCE_NOT_FOUND); + throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, uuid); } //Get Component Unique ID Component component = latestServiceByUuid.left().value(); - String uniqueId = component.getUniqueId(); - - //Lock Asset - this.componentLocker.lock(component); - this.accessValidations.validateUserCanWorkOnComponent(component, userId, action + " EXTERNAL REF"); - - Either<String, ActionStatus> opResult = Either.right(ActionStatus.GENERAL_ERROR); - try { - switch (action) { - case "POST": - opResult = this.externalReferencesOperation.addExternalReferenceWithCommit(uniqueId, componentInstanceName, objectType, ref1); - break; - case "PUT": - opResult = this.externalReferencesOperation.updateExternalReferenceWithCommit(uniqueId, componentInstanceName, objectType, ref1, ref2); - break; - case "DELETE": - opResult = this.externalReferencesOperation.deleteExternalReferenceWithCommit(uniqueId, componentInstanceName, objectType, ref1); - break; - default: - break; - } - } catch (Exception e) { - opResult = Either.right(ActionStatus.GENERAL_ERROR); - log.error("Failed to execute external ref action:{} on asset:{} component:{} objectType:{}", action, uuid, componentInstanceName, objectType); - log.error("Cause is:" , e); - } finally { - //Unlock Asset - this.componentLocker.unlock(uniqueId, componentType); + return component.getUniqueId(); + } + + + public Either<String, ActionStatus> doAction(String componentId, ComponentTypeEnum componentType, String userId, String action, String uuid, String componentInstanceName, String objectType, String ref1, String ref2){ + + accessValidations.validateUserCanWorkOnComponent(componentId, componentType, userId, action + " EXTERNAL REF"); + + switch (action) { + case "POST": + return this.externalReferencesOperation.addExternalReferenceWithCommit(componentId, componentInstanceName, objectType, ref1); + case "PUT": + return this.externalReferencesOperation.updateExternalReferenceWithCommit(componentId, componentInstanceName, objectType, ref1, ref2); + case "DELETE": + return this.externalReferencesOperation.deleteExternalReferenceWithCommit(componentId, componentInstanceName, objectType, ref1); + default: + return Either.right(ActionStatus.GENERAL_ERROR); } - return opResult; + } private Map<GraphPropertyEnum, Object> createPropsToMatch(ComponentTypeEnum componentType) { Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<>(); propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); - propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); return propertiesToMatch; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GenericArtifactBrowserBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GenericArtifactBrowserBusinessLogic.java index d95045b87b..4f092c6bd9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GenericArtifactBrowserBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GenericArtifactBrowserBusinessLogic.java @@ -27,8 +27,6 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; -import java.io.IOException; -import java.lang.reflect.Type; import org.onap.sdc.gab.GABService; import org.onap.sdc.gab.GABServiceImpl; import org.onap.sdc.gab.model.GABQuery; @@ -43,6 +41,9 @@ import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation; import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; import org.springframework.beans.factory.annotation.Autowired; +import java.io.IOException; +import java.lang.reflect.Type; + @org.springframework.stereotype.Component public class GenericArtifactBrowserBusinessLogic extends BaseBusinessLogic { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java index 1f906aefac..417380b5d9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java @@ -31,6 +31,7 @@ import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.lang3.tuple.ImmutablePair; 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.lock.LockingTransactional; import org.openecomp.sdc.be.components.impl.policy.PolicyTargetsUpdateHandler; import org.openecomp.sdc.be.components.utils.Utils; @@ -47,12 +48,25 @@ import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.CreatedFrom; +import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum; import org.openecomp.sdc.be.info.ArtifactDefinitionInfo; import org.openecomp.sdc.be.info.ArtifactTemplateInfo; import org.openecomp.sdc.be.info.GroupDefinitionInfo; -import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.GroupInstance; +import org.openecomp.sdc.be.model.GroupInstanceProperty; +import org.openecomp.sdc.be.model.GroupProperty; +import org.openecomp.sdc.be.model.GroupTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.PropertyDefinition.GroupInstancePropertyValueUpdateBehavior; import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation; @@ -66,13 +80,26 @@ import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.log.elements.LoggerSupportability; +import org.openecomp.sdc.common.log.enums.LogLevel; +import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions; +import org.openecomp.sdc.common.log.enums.StatusCode; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -85,7 +112,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { public static final String GROUP_DELIMITER_REGEX = "\\.\\."; - public static final String INITIAL_VERSION = "1"; + public static final String INITIAL_VERSION = "0.0"; private static final String ADDING_GROUP = "AddingGroup"; @@ -99,6 +126,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic { private static final Logger log = Logger.getLogger(GroupBusinessLogic.class); + public LoggerSupportability loggerSupportability= LoggerSupportability.getLogger(GroupBusinessLogic.class.getName()); + private final AccessValidations accessValidations; private final PolicyTargetsUpdateHandler policyTargetsUpdateHandler; @@ -218,22 +247,14 @@ public class GroupBusinessLogic extends BaseBusinessLogic { public Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType, GroupDefinition updatedGroup, boolean inTransaction , boolean shouldLock) { Either<GroupDefinition, ResponseFormat> result = null; + boolean failed = false; try { // Validate user exist - validateUserExists(user.getUserId(), UPDATE_GROUP, inTransaction); + validateUserExists(user.getUserId()); // Validate component exist - Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, null); - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - org.openecomp.sdc.be.model.Component component = validateComponent.left().value(); + org.openecomp.sdc.be.model.Component component = validateComponentExists(componentId, componentType, null); // validate we can work on component - Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, user.getUserId()); - if (canWork.isRight()) { - result = Either.right(canWork.right().value()); - return result; - } + validateCanWorkOnComponent(component, user.getUserId()); List<GroupDefinition> currentGroups = component.getGroups(); if (CollectionUtils.isEmpty(currentGroups)) { log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING); @@ -249,11 +270,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } GroupDefinition currentGroup = currentGroupOpt.get(); if ( shouldLock ){ - Either<Boolean, ResponseFormat> lockResult = lockComponent(componentId, component, "Update GroupDefinition Metadata"); - if (lockResult.isRight()) { - result = Either.right(lockResult.right().value()); - return result; - } + lockComponent(componentId, component, "Update GroupDefinition Metadata"); } // Validate group type is vfModule if (currentGroup.getType().equals(Constants.GROUP_TOSCA_HEAT)) { @@ -265,8 +282,11 @@ public class GroupBusinessLogic extends BaseBusinessLogic { result = updateGroupMetadata(component, currentGroup, updatedGroup); return result; - } finally { - if (result != null && result.isLeft()) { + }catch (ComponentException e){ + failed = true; + throw e; + }finally { + if (!failed) { janusGraphDao.commit(); } else { janusGraphDao.rollback(); @@ -293,23 +313,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic { private Either<GroupDefinition, ResponseFormat> updateGroup(Component component, GroupDefinition updatedGroup, String currentGroupName) { Either<GroupDefinition, StorageOperationStatus> handleGroupRes; Either<GroupDefinition, ResponseFormat> result = null; - if (updatedGroup.getName().equals(currentGroupName)) { - handleGroupRes = groupsOperation.updateGroup(component, updatedGroup); - if (handleGroupRes.isRight()) { - log.debug("Failed to update a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value()))); - } - } else { - StorageOperationStatus deleteStatus = groupsOperation.deleteGroup(component, currentGroupName); - if (deleteStatus != StorageOperationStatus.OK) { - log.debug("Failed to delete the group {} from component {}. ", updatedGroup.getName(), component.getName()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteStatus))); - } - handleGroupRes = groupsOperation.addGroup(component, updatedGroup); - if (handleGroupRes.isRight()) { - log.debug("Failed to add the group {} to component {}. ", updatedGroup.getName(), component.getName()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value()))); - } + handleGroupRes = groupsOperation.updateGroup(component, updatedGroup); + if (handleGroupRes.isRight()) { + log.debug("Failed to update a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName()); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value()))); } if (result == null) { result = Either.left(updatedGroup); @@ -424,7 +431,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { Either<GroupDefinitionInfo, ResponseFormat> result = null; // Validate user exist - validateUserExists(userId, GET_GROUP, true); + validateUserExists(userId); // Validate component exist org.openecomp.sdc.be.model.Component component = null; @@ -435,17 +442,12 @@ public class GroupBusinessLogic extends BaseBusinessLogic { componentParametersView.setIgnoreArtifacts(false); componentParametersView.setIgnoreUsers(false); - Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView); - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - component = validateComponent.left().value(); + component = validateComponentExists(componentId, componentType, componentParametersView); Either<GroupDefinition, StorageOperationStatus> groupEither = findGroupOnComponent(component, groupId); if (groupEither.isRight()) { - log.debug("Faild to find group {} under component {}", groupId, component.getUniqueId()); + log.debug("Failed to find group {} under component {}", groupId, component.getUniqueId()); BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "group " + groupId + " not found under component " + component.getUniqueId(), ErrorSeverity.INFO); String componentTypeForResponse = getComponentTypeForResponse(component); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupId, component.getSystemName(), componentTypeForResponse)); @@ -453,18 +455,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } GroupDefinition group = groupEither.left().value(); - Boolean isBase = null; List<GroupProperty> props = group.convertToGroupProperties(); - if (props != null && !props.isEmpty()) { - Optional<GroupProperty> isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); - if (isBasePropOp.isPresent()) { - GroupProperty propIsBase = isBasePropOp.get(); - isBase = Boolean.parseBoolean(propIsBase.getValue()); - - } else { - BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO); - } - } + Boolean isBase = isBaseProp(component, props); List<ArtifactDefinitionInfo> artifacts = new ArrayList<>(); List<ArtifactDefinition> artifactsFromComponent = new ArrayList<>(); @@ -485,12 +477,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } artifactsFromComponent.add(deploymentArtifacts.get(id)); } - if (!artifactsFromComponent.isEmpty()) { - for (ArtifactDefinition artifactDefinition : artifactsFromComponent) { - ArtifactDefinitionInfo artifactDefinitionInfo = new ArtifactDefinitionInfo(artifactDefinition); - artifacts.add(artifactDefinitionInfo); - } - } + addArtifactsToList(artifacts, artifactsFromComponent); } GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group); @@ -503,21 +490,28 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return result; } finally { + closeTransaction(inTransaction, result); + } - if (!inTransaction) { + } - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - janusGraphDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - janusGraphDao.commit(); - } + private void addArtifactsToList(List<ArtifactDefinitionInfo> artifacts, List<ArtifactDefinition> artifactsFromComponent) { + artifactsFromComponent.forEach(a-> artifacts.add(new ArtifactDefinitionInfo(a))); + } - } + private Boolean isBaseProp(Component component, List<GroupProperty> props) { + Boolean isBase = null; + if (CollectionUtils.isNotEmpty(props)) { + Optional<GroupProperty> isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); + if (isBasePropOp.isPresent()) { + GroupProperty propIsBase = isBasePropOp.get(); + isBase = Boolean.parseBoolean(propIsBase.getValue()); + } else { + BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO); + } } - + return isBase; } private Either<GroupDefinition, StorageOperationStatus> findGroupOnComponent(Component component, String groupId) { @@ -591,6 +585,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { newGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, description, counter); if (newGroupNameRes.isRight()) { log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value()); + loggerSupportability.log(LogLevel.INFO,LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML.getName(),StatusCode.ERROR.name(),"Failed to generate new vf module group name. Status is: "+newGroupNameRes.right().value()); result = Either.right(newGroupNameRes.right().value()); break; } @@ -655,9 +650,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic { Either<GroupDefinitionInfo, ResponseFormat> result = null; // Validate user exist - validateUserExists(userId, UPDATE_GROUP, true); + validateUserExists(userId); // Validate component exist - org.openecomp.sdc.be.model.Component component = null; + org.openecomp.sdc.be.model.Component component; try { ComponentParametersView componentParametersView = new ComponentParametersView(); @@ -666,12 +661,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { componentParametersView.setIgnoreComponentInstances(false); componentParametersView.setIgnoreArtifacts(false); - Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView); - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - component = validateComponent.left().value(); + component = validateComponentExists(componentId, componentType, componentParametersView); Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceRes = findComponentInstanceAndGroupInstanceOnComponent(component, componentInstanceId, groupInstId); if (findComponentInstanceAndGroupInstanceRes.isRight()) { @@ -683,18 +673,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { GroupInstance group = findComponentInstanceAndGroupInstanceRes.left().value().getRight(); - Boolean isBase = null; - List<? extends GroupProperty> props = group.convertToGroupInstancesProperties(); - if (props != null && !props.isEmpty()) { - Optional<? extends GroupProperty> isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); - if (isBasePropOp.isPresent()) { - GroupProperty propIsBase = isBasePropOp.get(); - isBase = Boolean.parseBoolean(propIsBase.getValue()); - - } else { - BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO); - } - } + Boolean isBase = isBaseProperty(component, group); List<ArtifactDefinitionInfo> artifacts = new ArrayList<>(); List<String> artifactsIds = group.getArtifacts(); @@ -702,25 +681,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic { List<ComponentInstance> instances = component.getComponentInstances(); if (instances != null) { - Optional<ComponentInstance> findFirst = instances.stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst(); - if (findFirst.isPresent()) { - ComponentInstance ci = findFirst.get(); - Map<String, ArtifactDefinition> deploymentArtifacts = ci.getDeploymentArtifacts(); - for (String id : artifactsIds) { - Optional<ArtifactDefinition> artOp = deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst(); - if (artOp.isPresent()) { - artifacts.add(new ArtifactDefinitionInfo(artOp.get())); - } - } - List<String> instArtifactsIds = group.getGroupInstanceArtifacts(); - for (String id : instArtifactsIds) { - Optional<ArtifactDefinition> artOp = deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst(); - if (artOp.isPresent()) { - artifacts.add(new ArtifactDefinitionInfo(artOp.get())); - } - } - } - + instances.stream().filter(i -> i.getUniqueId().equals(componentInstanceId)) + .findFirst() + .ifPresent(f->getFirstComponentInstance(group, artifacts, artifactsIds, f)); } } GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group); @@ -733,19 +696,51 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return result; } finally { + closeTransaction(inTransaction, result); + } + } - if (!inTransaction) { + private void getFirstComponentInstance(GroupInstance group, List<ArtifactDefinitionInfo> artifacts, List<String> artifactsIds, ComponentInstance ci) { + Map<String, ArtifactDefinition> deploymentArtifacts = ci.getDeploymentArtifacts(); + artifactsIds.forEach(id -> deploymentArtifacts.values().stream() + .filter(a -> a.getUniqueId().equals(id)) + .findFirst() + .ifPresent(g -> artifacts.add(new ArtifactDefinitionInfo(g)))); - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - janusGraphDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - janusGraphDao.commit(); - } + List<String> instArtifactsIds = group.getGroupInstanceArtifacts(); + instArtifactsIds.forEach(id -> deploymentArtifacts.values() + .stream() + .filter(a -> a.getUniqueId().equals(id)) + .findFirst() + .ifPresent(g -> artifacts.add(new ArtifactDefinitionInfo(g)))); + } + + private Boolean isBaseProperty(Component component, GroupInstance group) { + + Boolean isBase = null; + List<? extends GroupProperty> props = group.convertToGroupInstancesProperties(); + if (props != null && !props.isEmpty()) { + Optional<? extends GroupProperty> isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); + if (isBasePropOp.isPresent()) { + GroupProperty propIsBase = isBasePropOp.get(); + isBase = Boolean.parseBoolean(propIsBase.getValue()); + } else { + BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO); } + } + return isBase; + } + private void closeTransaction(boolean inTransaction, Either<GroupDefinitionInfo, ResponseFormat> result) { + if (!inTransaction) { + if (result == null || result.isRight()) { + log.debug("Going to execute rollback on create group."); + janusGraphDao.rollback(); + } else { + log.debug("Going to execute commit on create group."); + janusGraphDao.commit(); + } } } @@ -768,56 +763,51 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return result; } - private Either<Boolean, ResponseFormat> validateMinMaxAndInitialCountPropertyLogic(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues, Map<PropertyNames, String> parentValues) { + private Boolean validateMinMaxAndInitialCountPropertyLogic(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues, Map<PropertyNames, String> parentValues) { - Either<Boolean, ResponseFormat> result; for (Entry<PropertyNames, String> entry : newValues.entrySet()) { PropertyNames currPropertyName = entry.getKey(); if (currPropertyName == PropertyNames.MIN_INSTANCES) { String minValue = parentValues.get(PropertyNames.MIN_INSTANCES); - String maxValue = newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT); - result = validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue), + String maxValue = getMaxValue(newValues, currValues); + validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue), new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue)); - if (result.isRight()) { - return result; - } } else if (currPropertyName == PropertyNames.INITIAL_COUNT) { String minValue = newValues.containsKey(PropertyNames.MIN_INSTANCES) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.MIN_INSTANCES); String maxValue = newValues.containsKey(PropertyNames.MAX_INSTANCES) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.MAX_INSTANCES); - result = validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue), + validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue), new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue)); - if (result.isRight()) { - return result; - } } else if (currPropertyName == PropertyNames.MAX_INSTANCES) { - String minValue = newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT); + String minValue = getMinValue(newValues, currValues); String maxValue = parentValues.get(PropertyNames.MAX_INSTANCES); - result = validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue), + validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue), new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue)); - if (result.isRight()) { - return result; - } } } - return Either.left(true); + return true; } - private Either<Boolean, ResponseFormat> validateValueInRange(ImmutablePair<PropertyNames, String> newValue, ImmutablePair<PropertyNames, String> min, ImmutablePair<PropertyNames, String> max) { - Either<Boolean, ResponseFormat> result; + private String getMaxValue(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues) { + return newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT); + } + + private String getMinValue(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues) { + return newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT); + } + + private Boolean validateValueInRange(ImmutablePair<PropertyNames, String> newValue, ImmutablePair<PropertyNames, String> min, ImmutablePair<PropertyNames, String> max) { final String warnMessage = "Failed to validate {} as property value of {}. It must be not higher than {}, and not lower than {}."; int newValueInt = parseIntValue(newValue.getValue(), newValue.getKey()); int minInt = parseIntValue(min.getValue(), min.getKey()); int maxInt = parseIntValue(max.getValue(), max.getKey()); if (newValueInt < 0 || minInt < 0 || maxInt < 0) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY)); + throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY); } else if (newValueInt < minInt || newValueInt > maxInt) { log.debug(warnMessage, newValue.getValue(), newValue.getKey().getPropertyName(), min.getValue(), max.getValue()); - result = Either - .right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE, newValue.getKey().getPropertyName(), maxInt == Integer.MAX_VALUE ? Constants.UNBOUNDED : max.getValue(), min.getValue())); - } else { - result = Either.left(true); + throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE, newValue.getKey().getPropertyName(), + maxInt == Integer.MAX_VALUE ? Constants.UNBOUNDED : max.getValue(), min.getValue()); } - return result; + return true; } private int parseIntValue(String value, PropertyNames propertyName) { @@ -843,13 +833,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic { Either<GroupInstance, ResponseFormat> actionResult = null; Either<GroupInstance, StorageOperationStatus> updateGroupInstanceResult = null; - Either<List<GroupInstanceProperty>, ResponseFormat> validateRes = validateReduceGroupInstancePropertiesBeforeUpdate(oldGroupInstance, newProperties); - if (validateRes.isRight()) { - log.debug("Failed to validate group instance {} properties before update. ", oldGroupInstance.getName()); - actionResult = Either.right(validateRes.right().value()); - } + List<GroupInstanceProperty> validateRes = validateReduceGroupInstancePropertiesBeforeUpdate(oldGroupInstance, newProperties); if (actionResult == null) { - List<GroupInstanceProperty> validatedReducedNewProperties = validateRes.left().value(); + List<GroupInstanceProperty> validatedReducedNewProperties = validateRes; updateGroupInstanceResult = groupsOperation.updateGroupInstancePropertyValuesOnGraph(componentId, instanceId, oldGroupInstance, validatedReducedNewProperties); if (updateGroupInstanceResult.isRight()) { log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName()); @@ -862,10 +848,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return actionResult; } - private Either<List<GroupInstanceProperty>, ResponseFormat> validateReduceGroupInstancePropertiesBeforeUpdate(GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties) { + private List<GroupInstanceProperty> validateReduceGroupInstancePropertiesBeforeUpdate(GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties) { - Either<Boolean, ResponseFormat> validationRes = null; - Either<List<GroupInstanceProperty>, ResponseFormat> actionResult; + Boolean validationRes = null; + List<GroupInstanceProperty> actionResult = null; Map<String, GroupInstanceProperty> existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream().collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p)); Map<PropertyNames, String> newPropertyValues = new EnumMap<>(PropertyNames.class); List<GroupInstanceProperty> reducedProperties = new ArrayList<>(); @@ -874,25 +860,19 @@ public class GroupBusinessLogic extends BaseBusinessLogic { for (GroupInstanceProperty currNewProperty : newProperties) { currPropertyName = currNewProperty.getName(); validationRes = handleAndAddProperty(reducedProperties, newPropertyValues, currNewProperty, existingProperties.get(currPropertyName)); - if (validationRes.isRight()) { - log.debug("Failed to handle property {} of group instance {}. ", currPropertyName, oldGroupInstance.getName()); - break; - } } - if (validationRes == null || validationRes.isLeft()) { + if (validationRes == null || validationRes) { Map<PropertyNames, String> existingPropertyValues = new EnumMap<>(PropertyNames.class); Map<PropertyNames, String> parentPropertyValues = new EnumMap<>(PropertyNames.class); fillValuesAndParentValuesFromExistingProperties(existingProperties, existingPropertyValues, parentPropertyValues); validationRes = validateMinMaxAndInitialCountPropertyLogic(newPropertyValues, existingPropertyValues, parentPropertyValues); } - if (validationRes.isLeft()) { - actionResult = Either.left(reducedProperties); - } else { - actionResult = Either.right(validationRes.right().value()); + if (validationRes) { + actionResult = reducedProperties; } } catch (Exception e) { log.error("Exception occured during validation and reducing group instance properties. The message is {}", e.getMessage(), e); - actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } return actionResult; } @@ -907,9 +887,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } } - private Either<Boolean, ResponseFormat> handleAndAddProperty(List<GroupInstanceProperty> reducedProperties, Map<PropertyNames, String> newPropertyValues, GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) { + private Boolean handleAndAddProperty(List<GroupInstanceProperty> reducedProperties, Map<PropertyNames, String> newPropertyValues, GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) { - Either<Boolean, ResponseFormat> validationRes = null; + Boolean validationRes = null; String currPropertyName = currNewProperty.getName(); PropertyNames propertyName = PropertyNames.findName(currPropertyName); try { @@ -917,20 +897,15 @@ public class GroupBusinessLogic extends BaseBusinessLogic { log.warn("The value of property with the name {} cannot be updated. The property not found on group instance. ", currPropertyName); } else if (isUpdatable(propertyName)) { validationRes = validateAndUpdatePropertyValue(currNewProperty, currExistingProperty); - if (validationRes.isRight()) { - log.debug("Failed to validate property value {} of property {}. ", currNewProperty.getValue(), currPropertyName); - } else { - addPropertyUpdatedValues(reducedProperties, propertyName, newPropertyValues, currNewProperty, currExistingProperty); - } + addPropertyUpdatedValues(reducedProperties, propertyName, newPropertyValues, currNewProperty, currExistingProperty); } else { validateImmutableProperty(currExistingProperty, currNewProperty); } if (validationRes == null) { - validationRes = Either.left(true); + validationRes = true; } } catch (Exception e) { log.error("Exception occured during handle and adding property. The message is {}", e.getMessage(), e); - validationRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } return validationRes; } @@ -970,9 +945,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return result; } - private Either<Boolean, ResponseFormat> validateAndUpdatePropertyValue(GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) { + private Boolean validateAndUpdatePropertyValue(GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) { - Either<Boolean, ResponseFormat> validationRes = null; String parentValue = existingProperty.getParentValue(); newProperty.setParentValue(parentValue); @@ -985,12 +959,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic { StorageOperationStatus status = groupOperation.validateAndUpdatePropertyValue(newProperty); if (status != StorageOperationStatus.OK) { log.debug("Failed to validate property value {} of property with name {}. Status is {}. ", newProperty.getValue(), newProperty.getName(), status); - validationRes = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status)); } - if (validationRes == null) { - validationRes = Either.left(true); - } - return validationRes; + return true; } private void validateImmutableProperty(GroupProperty oldProperty, GroupProperty newProperty) { @@ -1069,7 +1040,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { private int getNewGroupCounter(Component component) { List<String> existingNames = component.getGroups() .stream() - .map(GroupDataDefinition::getName) + .map(GroupDataDefinition::getInvariantName) .collect(toList()); List<String> existingIds = component.getGroups() .stream() @@ -1180,7 +1151,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { break; } GroupDefinition handledGroup = handleGroupRes.left().value(); - groups.put(handledGroup.getName(), new GroupDataDefinition(handledGroup)); + groups.put(handledGroup.getInvariantName(), new GroupDataDefinition(handledGroup)); } } @@ -1196,6 +1167,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (result == null) { result = Either.left(groupDefinitions); } + component.setGroups(groupDefinitions); return result; } @@ -1258,6 +1230,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (createGroupsResult.isRight()) { result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); } + component.addGroups(createGroupsResult.left().value()); } if (result == null) { addCalculatedCapabilitiesWithPropertiesToComponent(component, groupDefinitions, fromCsar); @@ -1278,6 +1251,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } else { deleteCalculatedCapabilitiesWithPropertiesFromComponent(component, groupDefinitions); } + if (component.getGroups()!=null) { + component.getGroups().removeAll(deleteGroupsResult.left().value()); + } return Either.left(deleteGroupsResult.left().value()); } @@ -1291,7 +1267,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { Either<List<GroupDefinition>, ResponseFormat> result = null; Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult; - createGroupsResult = groupsOperation.updateGroups(component, groupDefinitions.stream().map(GroupDataDefinition::new).collect(toList()), true); + createGroupsResult = groupsOperation.updateGroups(component, groupDefinitions.stream().map(GroupDataDefinition::new).collect(toList()), PromoteVersionEnum.MINOR); if (createGroupsResult.isRight()) { result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); } @@ -1307,6 +1283,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { private Either<GroupDefinition, ResponseFormat> handleGroup(Component component, GroupDefinition groupDefinition, Map<String, DataTypeDefinition> allDAtaTypes) { log.trace("Going to create group {}", groupDefinition); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(),StatusCode.STARTED,"Start to create group: {}",groupDefinition.getName()+ " for component " + component.getName()); // 3. verify group not already exist String groupDefinitionName = groupDefinition.getName(); if (groupExistsInComponent(groupDefinitionName, component)) { @@ -1322,6 +1299,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (getGroupType.isRight()) { StorageOperationStatus status = getGroupType.right().value(); if (status == StorageOperationStatus.NOT_FOUND) { + loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(), StatusCode.ERROR,"group {} cannot be found",groupDefinition.getName()); BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "group type " + groupType + " cannot be found", ErrorSeverity.INFO); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType)); } else { @@ -1351,6 +1329,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (CollectionUtils.isNotEmpty(properties)) { if (CollectionUtils.isEmpty(groupTypeProperties)) { BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "group type does not have properties", ErrorSeverity.INFO); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(), StatusCode.ERROR,"group {} does not have properties ",groupDefinition.getName()); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.MATCH_NOT_FOUND)))); } @@ -1379,7 +1358,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { groupDefinition.setGroupUUID(UniqueIdBuilder.generateUUID()); groupDefinition.setVersion(INITIAL_VERSION); groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId()); - + loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,"group {} has been created ",groupDefinition.getName()); return Either.left(groupDefinition); } @@ -1387,7 +1366,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic { boolean found = false; List<GroupDefinition> groups = component.getGroups(); if (CollectionUtils.isNotEmpty(groups)) { - found = groups.stream().filter(p -> p.getName().equalsIgnoreCase(groupDefinitionName)).findFirst().orElse(null) != null; + found = groups.stream().filter(p -> (p.getName().equalsIgnoreCase(groupDefinitionName)) + || p.getInvariantName().equalsIgnoreCase(groupDefinitionName)) + .findFirst().orElse(null) != null; } return found; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicNew.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicNew.java index 5a5e941c24..eb576a46f6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicNew.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicNew.java @@ -33,7 +33,12 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.GroupProperty; +import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation; import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -41,7 +46,11 @@ import org.openecomp.sdc.be.model.operations.impl.GroupOperation; import org.openecomp.sdc.common.util.ValidationUtils; import org.springframework.transaction.annotation.Transactional; -import java.util.*; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.stream.Collectors; import static org.openecomp.sdc.be.components.impl.BaseBusinessLogic.enumHasValueFilter; @@ -66,7 +75,7 @@ public class GroupBusinessLogicNew { Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentType, userId, "UPDATE GROUP MEMBERS"); GroupDefinition groupDefinition = getGroup(component, groupUniqueId); groupDefinition.setMembers(buildMembersMap(component, members)); - groupsOperation.updateGroupOnComponent(componentId, groupDefinition); + groupsOperation.updateGroupOnComponent(componentId, groupDefinition, PromoteVersionEnum.MINOR); return new ArrayList<>(groupDefinition.getMembers().values()); } @@ -75,7 +84,7 @@ public class GroupBusinessLogicNew { Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentType, userId, "UPDATE GROUP PROPERTIES"); GroupDefinition currentGroup = getGroup(component, groupUniqueId); validateUpdatedPropertiesAndSetEmptyValues(currentGroup, newProperties); - return groupsOperation.updateGroupPropertiesOnComponent(componentId, currentGroup, newProperties) + return groupsOperation.updateGroupPropertiesOnComponent(componentId, currentGroup, newProperties, PromoteVersionEnum.MINOR) .left() .on(this::onUpdatePropertyError); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java index 80d6d65a06..ee53c35884 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java @@ -57,7 +57,7 @@ public class GroupTypeBusinessLogic { public List<GroupTypeDefinition> getAllGroupTypes(String userId, String internalComponentType) { try { - userValidations.validateUserExists(userId, "get group types", true); + userValidations.validateUserExists(userId); Set<String> excludeGroupTypes = getExcludedGroupTypes(internalComponentType); return groupTypeOperation.getAllGroupTypes(excludeGroupTypes); } finally { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java index 7001c0c05f..d557de1dec 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java @@ -22,20 +22,32 @@ package org.openecomp.sdc.be.components.impl; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; import com.google.gson.reflect.TypeToken; import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringEscapeUtils; -import org.openecomp.sdc.be.components.impl.utils.ExceptionUtils; +import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.elements.Annotation; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.model.AnnotationTypeDefinition; +import org.openecomp.sdc.be.model.HeatParameterDefinition; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.PropertyConstraint; +import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.heat.HeatParameterType; import org.openecomp.sdc.be.model.operations.impl.AnnotationTypeOperations; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; +import org.openecomp.sdc.be.model.tosca.constraints.ConstraintType; +import org.openecomp.sdc.be.model.tosca.constraints.ValidValuesConstraint; +import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException; import org.openecomp.sdc.be.utils.TypeUtils; import org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; @@ -52,7 +64,14 @@ import org.yaml.snakeyaml.representer.Representer; import org.yaml.snakeyaml.resolver.Resolver; import java.lang.reflect.Type; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; import java.util.function.Consumer; import java.util.function.Function; @@ -303,21 +322,60 @@ public final class ImportUtils { } private static void setPropertyConstraints(Map<String, Object> propertyValue, PropertyDefinition property) { - Either<List<Object>, ResultStatusEnum> propertyFieldconstraints = findFirstToscaListElement(propertyValue, TypeUtils.ToscaTagNamesEnum.CONSTRAINTS); - if (propertyFieldconstraints.isLeft()) { - List<Object> jsonConstraintList = propertyFieldconstraints.left().value(); + List<PropertyConstraint> constraints = getPropertyConstraints(propertyValue, property.getType()); + if (CollectionUtils.isNotEmpty(constraints)) { + property.setConstraints(constraints); + } + } + private static List<PropertyConstraint> getPropertyConstraints(Map<String, Object> propertyValue, String propertyType) { + List<Object> propertyFieldConstraints = findCurrentLevelConstraintsElement(propertyValue); + if (CollectionUtils.isNotEmpty(propertyFieldConstraints)) { List<PropertyConstraint> constraintList = new ArrayList<>(); Type constraintType = new TypeToken<PropertyConstraint>() { }.getType(); Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); - for (Object constraintJson : jsonConstraintList) { - PropertyConstraint propertyConstraint = gson.fromJson(gson.toJson(constraintJson), constraintType); + for (Object constraintJson : propertyFieldConstraints) { + PropertyConstraint propertyConstraint = validateAndGetPropertyConstraint(propertyType, constraintType, gson, constraintJson); constraintList.add(propertyConstraint); } - property.setConstraints(constraintList); + return constraintList; } + return null; + } + + private static List<Object> findCurrentLevelConstraintsElement(Map<String, Object> toscaJson) { + List<Object> constraints = null; + if (toscaJson.containsKey(TypeUtils.ToscaTagNamesEnum.CONSTRAINTS.getElementName())) { + try { + constraints = (List<Object>) toscaJson.get(TypeUtils.ToscaTagNamesEnum.CONSTRAINTS.getElementName()); + } catch (ClassCastException e){ + throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_CONSTRAINTS_FORMAT, toscaJson.get(TypeUtils.ToscaTagNamesEnum.CONSTRAINTS.getElementName()).toString()); + } + } + return constraints; + + } + + private static PropertyConstraint validateAndGetPropertyConstraint(String propertyType, Type constraintType, Gson gson, Object constraintJson) { + PropertyConstraint propertyConstraint; + try{ + propertyConstraint = gson.fromJson(gson.toJson(constraintJson), constraintType); + } catch (ClassCastException|JsonParseException e){ + throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_CONSTRAINTS_FORMAT, constraintJson.toString()); + } + if(propertyConstraint!= null && propertyConstraint instanceof ValidValuesConstraint){ + try { + ((ValidValuesConstraint)propertyConstraint).validateType(propertyType); + } catch (ConstraintValueDoNotMatchPropertyTypeException e) { + BeEcompErrorManager.getInstance().logInternalFlowError("GetInitializedPropertyConstraint", + e.getMessage(), BeEcompErrorManager.ErrorSeverity.ERROR); + throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_CONSTRAINTS, ConstraintType.VALID_VALUES.name(), + ((ValidValuesConstraint) propertyConstraint).getValidValues().toString(), propertyType); + } + } + return propertyConstraint; } public static PropertyDefinition createModuleProperty(Map<String, Object> propertyValue) { @@ -445,35 +503,29 @@ public final class ImportUtils { } private static void setScheme(Map<String, Object> propertyValue, PropertyDefinition propertyDefinition) { - Either<SchemaDefinition, ResultStatusEnum> eitherSchema = getSchema(propertyValue); - if (eitherSchema.isLeft()) { - SchemaDefinition schemaDef = new SchemaDefinition(); - schemaDef.setProperty(eitherSchema.left().value().getProperty()); + Either<Object, ResultStatusEnum> schemaElementRes = findSchemaElement(propertyValue); + if (schemaElementRes.isLeft()) { + SchemaDefinition schemaDef = getSchema(schemaElementRes.left().value()); propertyDefinition.setSchema(schemaDef); } - } - private static Either<SchemaDefinition, ResultStatusEnum> getSchema(Map<String, Object> propertyValue) { - Either<SchemaDefinition, ResultStatusEnum> result = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - Either<Object, ResultStatusEnum> propertyFieldEntryScheme = findToscaElement(propertyValue, TypeUtils.ToscaTagNamesEnum.ENTRY_SCHEMA, ToscaElementTypeEnum.ALL); - if (propertyFieldEntryScheme.isLeft()) { - if (propertyFieldEntryScheme.left().value() instanceof String) { - String schemaType = (String) propertyFieldEntryScheme.left().value(); - SchemaDefinition schema = new SchemaDefinition(); - PropertyDefinition schemeProperty = new PropertyDefinition(); - schemeProperty.setType(schemaType); - schema.setProperty(schemeProperty); - result = Either.left(schema); + private static Either<Object,ResultStatusEnum> findSchemaElement(Map<String, Object> propertyValue) { + return findToscaElement(propertyValue, TypeUtils.ToscaTagNamesEnum.ENTRY_SCHEMA, ToscaElementTypeEnum.ALL); + } - } else if (propertyFieldEntryScheme.left().value() instanceof Map) { - PropertyDefinition schemeProperty = createModuleProperty((Map<String, Object>) propertyFieldEntryScheme.left().value()); - SchemaDefinition schema = new SchemaDefinition(); - schema.setProperty(schemeProperty); - result = Either.left(schema); - } + private static SchemaDefinition getSchema(Object propertyFieldEntryScheme) { + SchemaDefinition schema = new SchemaDefinition(); + if (propertyFieldEntryScheme instanceof String) { + String schemaType = (String) propertyFieldEntryScheme; + PropertyDefinition schemeProperty = new PropertyDefinition(); + schemeProperty.setType(schemaType); + schema.setProperty(schemeProperty); + } else if (propertyFieldEntryScheme instanceof Map) { + PropertyDefinition schemeProperty = createModuleProperty((Map<String, Object>) propertyFieldEntryScheme); + schema.setProperty(schemeProperty); } - return result; + return schema; } public static void setField(Map<String, Object> toscaJson, TypeUtils.ToscaTagNamesEnum tagName, Consumer<String> setter) { @@ -665,7 +717,7 @@ public final class ImportUtils { return null; } ToscaPropertyType validType = ToscaPropertyType.isValidType(type); - if (validType == null || validType.equals(ToscaPropertyType.JSON) ||validType.equals(ToscaPropertyType.MAP) || validType.equals(ToscaPropertyType.LIST)) { + if (validType == null || validType == ToscaPropertyType.JSON || validType == ToscaPropertyType.MAP || validType == ToscaPropertyType.LIST) { return gson.toJson(value); } return value.toString(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java index bcd48a24c0..02d6e0b565 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java @@ -22,21 +22,15 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.stream.Collectors; +import fj.data.Either; import org.apache.commons.collections4.ListUtils; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ReflectionToStringBuilder; +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.property.PropertyDeclarationOrchestrator; import org.openecomp.sdc.be.components.validation.ComponentValidations; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -69,11 +63,23 @@ 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.model.tosca.converters.PropertyValueConverter; +import org.openecomp.sdc.common.log.elements.LoggerSupportability; +import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions; +import org.openecomp.sdc.common.log.enums.StatusCode; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import fj.data.Either; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; @Component("inputsBusinessLogic") public class InputsBusinessLogic extends BaseBusinessLogic { @@ -87,6 +93,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { private static final String FAILED_TO_FOUND_INPUT_UNDER_COMPONENT_ERROR = "Failed to found input {} under component {}, error: {}"; private static final String GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP = "Going to execute rollback on create group."; private static final String GOING_TO_EXECUTE_COMMIT_ON_CREATE_GROUP = "Going to execute commit on create group."; + public LoggerSupportability loggerSupportability=LoggerSupportability.getLogger(InputsBusinessLogic.class.getName()); private final PropertyDeclarationOrchestrator propertyDeclarationOrchestrator; private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic; @@ -118,7 +125,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { */ public Either<List<InputDefinition>, ResponseFormat> getInputs(String userId, String componentId) { - validateUserExists(userId, "get Inputs", false); + validateUserExists(userId); ComponentParametersView filters = new ComponentParametersView(); filters.disableAll(); @@ -140,7 +147,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { public Either<List<ComponentInstanceInput>, ResponseFormat> getComponentInstanceInputs(String userId, String componentId, String componentInstanceId) { - validateUserExists(userId, "get Inputs", false); + validateUserExists(userId); ComponentParametersView filters = new ComponentParametersView(); filters.disableAll(); filters.setIgnoreInputs(false); @@ -159,6 +166,8 @@ public class InputsBusinessLogic extends BaseBusinessLogic { if(!ComponentValidations.validateComponentInstanceExist(component, componentInstanceId)){ ActionStatus actionStatus = ActionStatus.COMPONENT_INSTANCE_NOT_FOUND; log.debug("Failed to found component instance inputs {}, error: {}", componentInstanceId, actionStatus); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,component.getComponentMetadataForSupportLog(), + StatusCode.ERROR,"Failed to found component instance inputs componentInstanceId: {}",componentInstanceId); return Either.right(componentsUtils.getResponseFormat(actionStatus)); } Map<String, List<ComponentInstanceInput>> ciInputs = @@ -181,7 +190,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { */ public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesByInputId(String userId, String componentId, String instanceId, String inputId) { - validateUserExists(userId, GET_PROPERTIES_BY_INPUT, false); + validateUserExists(userId); String parentId = componentId; org.openecomp.sdc.be.model.Component component; ComponentParametersView filters = new ComponentParametersView(); @@ -234,7 +243,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { } - private Either<String,ResponseFormat> updateInputObjectValue(InputDefinition currentInput, InputDefinition newInput, Map<String, DataTypeDefinition> dataTypes) { + private String updateInputObjectValue(InputDefinition currentInput, InputDefinition newInput, Map<String, DataTypeDefinition> dataTypes) { String innerType = null; String propertyType = currentInput.getType(); ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); @@ -244,12 +253,12 @@ public class InputsBusinessLogic extends BaseBusinessLogic { SchemaDefinition def = currentInput.getSchema(); if (def == null) { log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)); } PropertyDataDefinition propDef = def.getProperty(); if (propDef == null) { log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)); } innerType = propDef.getType(); } @@ -261,8 +270,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { if (isValid.isRight()) { Boolean res = isValid.right().value(); if (Boolean.FALSE.equals(res)) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus( - JanusGraphOperationStatus.ILLEGAL_ARGUMENT)))); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))); } } else { Object object = isValid.left().value(); @@ -270,7 +278,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { newValue = object.toString(); } } - return Either.left(newValue); + return newValue; } private InputDefinition getInputFromInputsListById(List<InputDefinition> componentsOldInputs, InputDefinition input) { @@ -284,7 +292,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { org.openecomp.sdc.be.model.Component component = null; try { - validateUserExists(userId, "get input", false); + validateUserExists(userId); ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.disableAll(); @@ -294,43 +302,29 @@ public class InputsBusinessLogic extends BaseBusinessLogic { componentParametersView.setIgnoreComponentInstancesProperties(false); componentParametersView.setIgnoreComponentInstances(false); - Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView); - - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - component = validateComponent.left().value(); + component = validateComponentExists(componentId, componentType, componentParametersView); if (shouldLockComp) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, UPDATE_INPUT); - if (lockComponent.isRight()) { - result = Either.right(lockComponent.right().value()); + try { + lockComponent(component, UPDATE_INPUT); + }catch (ComponentException e){ + result = Either.right(e.getResponseFormat()); return result; } } - Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId); - if (canWork.isRight()) { - result = Either.right(canWork.right().value()); - return result; - } - - //Validate value and Constraint of input + //Validate value and Constraint of input Either<Boolean, ResponseFormat> constraintValidatorResponse = validateInputValueConstraint(inputs); - if (constraintValidatorResponse.isRight()) { - log.error("Failed validation value and constraint of property: {}", - constraintValidatorResponse.right().value()); - return Either.right(constraintValidatorResponse.right().value()); - } - - Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); - if (allDataTypes.isRight()) { - result = Either.right(allDataTypes.right().value()); - return result; + if (constraintValidatorResponse.isRight()) { + log.error("Failed validation value and constraint of property: {}", + constraintValidatorResponse.right().value()); + return Either.right(constraintValidatorResponse.right().value()); } - Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value(); + validateCanWorkOnComponent(component, userId); + Map<String, DataTypeDefinition> dataTypes; + dataTypes = getAllDataTypes(applicationDataTypeCache); + List<InputDefinition> componentsOldInputs = Optional.ofNullable(component.getInputs()).orElse(Collections.emptyList()); for (InputDefinition newInput: inputs) { InputDefinition currInput = getInputFromInputsListById(componentsOldInputs, newInput); @@ -340,13 +334,8 @@ public class InputsBusinessLogic extends BaseBusinessLogic { result = Either.right(componentsUtils.getResponseFormat(actionStatus)); return result; } - Either<String, ResponseFormat> updateInputObjectValue = updateInputObjectValue(currInput, newInput, dataTypes); - if ( updateInputObjectValue.isRight()) { - return Either.right(updateInputObjectValue.right().value()); - } - String newValue = updateInputObjectValue.left().value(); - currInput.setValue(newValue); - currInput.setDefaultValue(newValue); + String updateInputObjectValue = updateInputObjectValue(currInput, newInput, dataTypes); + currInput.setDefaultValue(updateInputObjectValue); currInput.setOwnerId(userId); Either<InputDefinition, StorageOperationStatus> status = toscaOperationFacade.updateInputOfComponent(component, currInput); if(status.isRight()){ @@ -358,22 +347,16 @@ public class InputsBusinessLogic extends BaseBusinessLogic { } } result = Either.left(returnInputs); - return result; - } finally { - if (!inTransaction) { - if (result == null || result.isRight()) { - log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP); - janusGraphDao.rollback(); - } else { - log.debug(GOING_TO_EXECUTE_COMMIT_ON_CREATE_GROUP); - janusGraphDao.commit(); - } - } - // unlock resource - if (shouldLockComp && component != null) { - graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); - } - } + }catch (ComponentException e) { + log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP); + unlockRollbackWithException(component, e); + } catch (Exception e){ + unlockRollbackWithException(component, new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR)); + } + log.debug(GOING_TO_EXECUTE_COMMIT_ON_CREATE_GROUP); + unlockWithCommit(component); + return result; + } private Either<Boolean, ResponseFormat> validateInputValueConstraint(List<InputDefinition> inputs) { @@ -399,7 +382,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { } public Either<List<ComponentInstanceInput>, ResponseFormat> getInputsForComponentInput(String userId, String componentId, String inputId) { - validateUserExists(userId, GET_PROPERTIES_BY_INPUT, false); + validateUserExists(userId); org.openecomp.sdc.be.model.Component component = null; ComponentParametersView filters = new ComponentParametersView(); filters.disableAll(); @@ -442,7 +425,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { org.openecomp.sdc.be.model.Component component = null; try { - validateUserExists(userId, GET_PROPERTIES_BY_INPUT, false); + validateUserExists(userId); component = getAndValidateComponentForCreate(userId, componentId, componentType, shouldLockComp); @@ -498,7 +481,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { try { /* check if user exists */ - validateUserExists(userId, GET_PROPERTIES_BY_INPUT, false); + validateUserExists(userId); component = getAndValidateComponentForCreate(userId, componentId, componentType, shouldLockComp); @@ -579,23 +562,14 @@ public class InputsBusinessLogic extends BaseBusinessLogic { private org.openecomp.sdc.be.model.Component getAndValidateComponentForCreate( String userId, String componentId, ComponentTypeEnum componentType, boolean shouldLockComp ) { - ComponentParametersView componentParametersView = getBaseComponentParametersView(); - - Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = - // get Component Object - validateComponentExists(componentId, componentType, componentParametersView) - .left().bind(component -> { - if (shouldLockComp) { - // lock the component - return lockComponent(component, CREATE_INPUT).left().map(result -> component); - } - return Either.left(component); - }).left().bind(component -> validateCanWorkOnComponent(component, userId).left().map(result -> component)); - if (componentEither.isRight()) { - throw new ByResponseFormatComponentException(componentEither.right().value()); + org.openecomp.sdc.be.model.Component component = validateComponentExists(componentId, componentType, componentParametersView); + if (shouldLockComp) { + // lock the component + lockComponent(component, CREATE_INPUT); } - return componentEither.left().value(); + validateCanWorkOnComponent(component, userId); + return component; } private DataTypeDefinition prepareDataTypeForListInput(ComponentInstInputsMap inputsMap, InputDefinition input) { @@ -615,7 +589,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { DataTypeDefinition dataType = new DataTypeDefinition(); List<ComponentInstancePropInput> propInputs = inputsMap.resolvePropertiesToDeclare().getRight(); dataType.setName(desiredTypeName); - dataType.setDerivedFromName(ToscaPropertyType.Root.getType()); + dataType.setDerivedFromName(ToscaPropertyType.ROOT.getType()); // Copy properties from inputsMap dataType.setProperties(propInputs.stream().map(PropertyDefinition::new).collect(Collectors.toList())); return dataType; @@ -639,12 +613,8 @@ public class InputsBusinessLogic extends BaseBusinessLogic { public Either<List<InputDefinition>, ResponseFormat> createInputsInGraph(Map<String, InputDefinition> inputs, org.openecomp.sdc.be.model.Component component) { List<InputDefinition> resourceProperties = component.getInputs(); - Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); - if (allDataTypes.isRight()) { - return Either.right(allDataTypes.right().value()); - } - Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value(); + Map<String, DataTypeDefinition> dataTypes = getAllDataTypes(applicationDataTypeCache); for (Map.Entry<String, InputDefinition> inputDefinition : inputs.entrySet()) { String inputName = inputDefinition.getKey(); @@ -668,6 +638,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { Either<List<InputDefinition>, StorageOperationStatus> associateInputsEither = toscaOperationFacade.createAndAssociateInputs(inputs, component.getUniqueId()); if(associateInputsEither.isRight()){ log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), associateInputsEither.right().value()); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(associateInputsEither.right().value()))); } return Either.left(associateInputsEither.left().value()); @@ -677,13 +648,9 @@ public class InputsBusinessLogic extends BaseBusinessLogic { Map<String, DataTypeDefinition> privateDataTypes, org.openecomp.sdc.be.model.Component component) { log.trace("#createListInputsInGraph: enter"); - Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes( - applicationDataTypeCache); - if (allDataTypes.isRight()) { - return Either.right(allDataTypes.right().value()); - } - Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value(); + Map<String, DataTypeDefinition> dataTypes = getAllDataTypes( + applicationDataTypeCache); dataTypes.putAll(privateDataTypes); for (Map.Entry<String, InputDefinition> inputDefinition : inputs.entrySet()) { @@ -717,14 +684,14 @@ public class InputsBusinessLogic extends BaseBusinessLogic { * @param inputId * @return */ - public Either<InputDefinition, ResponseFormat> deleteInput(String componentId, String userId, String inputId) { + public InputDefinition deleteInput(String componentId, String userId, String inputId) { Either<InputDefinition, ResponseFormat> deleteEither = null; if (log.isDebugEnabled()) { log.debug("Going to delete input id: {}", inputId); } - validateUserExists(userId, "Delete input", true); + validateUserExists(userId); ComponentParametersView componentParametersView = getBaseComponentParametersView(); componentParametersView.setIgnoreInterfaces(false); @@ -734,9 +701,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentEither = toscaOperationFacade.getToscaElement(componentId, componentParametersView); if (componentEither.isRight()) { - deleteEither = Either.right(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(componentEither.right().value()))); - return deleteEither; + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(componentEither.right().value())); } org.openecomp.sdc.be.model.Component component = componentEither.left().value(); @@ -747,57 +712,43 @@ public class InputsBusinessLogic extends BaseBusinessLogic { // Get the input findAny(); if (!optionalInput.isPresent()) { - return Either.right( - componentsUtils.getResponseFormat(ActionStatus.INPUT_IS_NOT_CHILD_OF_COMPONENT, inputId, componentId)); + throw new ByActionStatusComponentException(ActionStatus.INPUT_IS_NOT_CHILD_OF_COMPONENT, inputId, componentId); } InputDefinition inputForDelete = optionalInput.get(); // Lock component - Either<Boolean, ResponseFormat> lockResultEither = - lockComponent(componentId, component, "deleteInput"); - if (lockResultEither.isRight()) { - ResponseFormat responseFormat = lockResultEither.right().value(); - deleteEither = Either.right(responseFormat); - return deleteEither; - } - + lockComponent(componentId, component, "deleteInput"); // Delete input operations + boolean failed = false; try { StorageOperationStatus status = toscaOperationFacade.deleteInputOfResource(component, inputForDelete.getName()); if (status != StorageOperationStatus.OK) { log.debug("Component id: {} delete input id: {} failed", componentId, inputId); - deleteEither = Either.right(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(status), component.getName())); - return deleteEither; + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), component.getName()); } if (BooleanUtils.isTrue(inputForDelete.getIsDeclaredListInput())){ deleteEither = deleteListInput(componentId, inputId, component, inputForDelete, status); - return deleteEither; + if (deleteEither.isRight()){ + throw new ByResponseFormatComponentException(deleteEither.right().value()); + } + return deleteEither.left().value(); } StorageOperationStatus storageOperationStatus = propertyDeclarationOrchestrator.unDeclarePropertiesAsInputs(component, inputForDelete); if (storageOperationStatus != StorageOperationStatus.OK) { log.debug("Component id: {} update properties declared as input for input id: {} failed", componentId, inputId); - deleteEither = Either.right(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(status), component.getName())); - return deleteEither; - } - - deleteEither = Either.left(inputForDelete); - return deleteEither; - } finally { - if (deleteEither == null || deleteEither.isRight()) { - log.debug("Component id: {} delete input id: {} failed", componentId, inputId); - janusGraphDao.rollback(); - } else { - log.debug("Component id: {} delete input id: {} success", componentId, inputId); - janusGraphDao.commit(); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), component.getName()); } - unlockComponent(deleteEither, component); + return inputForDelete; + }catch (ComponentException e){ + failed = true; + throw e; + }finally { + unlockComponent(failed, component); } } @@ -858,7 +809,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { Either<InputDefinition, ResponseFormat> result = null; try { - validateUserExists(userId, GET_PROPERTIES_BY_INPUT, false); + validateUserExists(userId); ComponentParametersView filters = new ComponentParametersView(); filters.disableAll(); filters.setIgnoreComponentInstances(false); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java index 7a1c96e1ef..f6a2e5bd3e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java @@ -32,7 +32,11 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Component; import javax.annotation.Resource; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; @Component("interfaceLifecycleTypeImportManager") public class InterfaceLifecycleTypeImportManager { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java index add5df225c..a0ea5c9d04 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java @@ -17,33 +17,11 @@ package org.openecomp.sdc.be.components.impl; -import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedCapabilityPropertyDefaultValue; -import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedInputPropertyDefaultValue; -import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedOutputDefaultValue; -import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceId; -import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceType; -import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getOperationFromInterfaceDefinition; -import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.isOperationInputMappedToComponentInput; -import static org.openecomp.sdc.be.components.utils.PropertiesUtils.getPropertyCapabilityFromAllCapProps; -import static org.openecomp.sdc.be.components.utils.PropertiesUtils.isCapabilityProperty; -import static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.SELF; - import com.google.gson.Gson; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.UUID; -import java.util.stream.Collectors; - import fj.data.Either; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; +import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; import org.openecomp.sdc.be.components.utils.InterfaceOperationUtils; import org.openecomp.sdc.be.components.validation.InterfaceOperationValidation; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -77,6 +55,28 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Collectors; + +import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedCapabilityPropertyDefaultValue; +import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedInputPropertyDefaultValue; +import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedOutputDefaultValue; +import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceId; +import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceType; +import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getOperationFromInterfaceDefinition; +import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.isOperationInputMappedToComponentInput; +import static org.openecomp.sdc.be.components.utils.PropertiesUtils.getPropertyCapabilityFromAllCapProps; +import static org.openecomp.sdc.be.components.utils.PropertiesUtils.isCapabilityProperty; +import static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.SELF; + @Component("interfaceOperationBusinessLogic") public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { @@ -107,7 +107,7 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { public Either<List<InterfaceDefinition>, ResponseFormat> deleteInterfaceOperation(String componentId, String interfaceId, List<String> operationsToDelete, User user, boolean lock) { - validateUserExists(user.getUserId(), DELETE_INTERFACE_OPERATION, true); + validateUserExists(user.getUserId()); Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId); if (componentEither.isRight()) { @@ -115,11 +115,8 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { } org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value(); - Either<Boolean, ResponseFormat> lockResult = - lockComponentResult(lock, storedComponent, DELETE_INTERFACE_OPERATION); - if (lockResult.isRight()) { - return Either.right(lockResult.right().value()); - } + lockComponentResult(lock, storedComponent, DELETE_INTERFACE_OPERATION); + try { Optional<InterfaceDefinition> optionalInterface = getInterfaceDefinitionFromComponentByInterfaceId( @@ -208,10 +205,8 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_DELETED)); } finally { - if (lockResult.isLeft() && lockResult.left().value()) { - graphLockOperation.unlockComponent(storedComponent.getUniqueId(), - NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); - } + graphLockOperation.unlockComponent(storedComponent.getUniqueId(), + NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); } } @@ -228,18 +223,19 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { private Either<Boolean, ResponseFormat> lockComponentResult(boolean lock, org.openecomp.sdc.be.model.Component component, String action) { if (lock) { - Either<Boolean, ResponseFormat> lockResult = lockComponent(component.getUniqueId(), component, action); - if (lockResult.isRight()) { - janusGraphDao.rollback(); - return Either.right(lockResult.right().value()); - } + try { + lockComponent(component.getUniqueId(), component, action); + } catch (ComponentException e) { + janusGraphDao.rollback(); + throw e; } + } return Either.left(true); } public Either<List<InterfaceDefinition>, ResponseFormat> getInterfaceOperation(String componentId, String interfaceId, List<String> operationsToGet, User user, boolean lock) { - validateUserExists(user.getUserId(), GET_INTERFACE_OPERATION, true); + validateUserExists(user); Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId); if (componentEither.isRight()) { @@ -247,11 +243,7 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { } org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value(); - Either<Boolean, ResponseFormat> lockResult = - lockComponentResult(lock, storedComponent, GET_INTERFACE_OPERATION); - if (lockResult.isRight()) { - return Either.right(lockResult.right().value()); - } + lockComponentResult(lock, storedComponent, GET_INTERFACE_OPERATION); try { Optional<InterfaceDefinition> optionalInterface = getInterfaceDefinitionFromComponentByInterfaceId( @@ -280,10 +272,8 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { return Either.right( componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentId)); } finally { - if (lockResult.isLeft() && lockResult.left().value()) { - graphLockOperation.unlockComponent(storedComponent.getUniqueId(), - NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); - } + graphLockOperation.unlockComponent(storedComponent.getUniqueId(), + NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); } } @@ -296,7 +286,7 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { private Either<List<InterfaceDefinition>, ResponseFormat> createOrUpdateInterfaceOperation(String componentId, List<InterfaceDefinition> interfaceDefinitions, User user, boolean isUpdate, String errorContext, boolean lock) { - validateUserExists(user.getUserId(), errorContext, true); + validateUserExists(user); Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId); if (componentEither.isRight()) { @@ -304,10 +294,8 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { } org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value(); - Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock, storedComponent, errorContext); - if (lockResult.isRight()) { - return Either.right(lockResult.right().value()); - } + lockComponentResult(lock, storedComponent, errorContext); + Either<Map<String, InterfaceDefinition>, ResponseFormat> interfaceLifecycleTypes = getAllInterfaceLifecycleTypes(); @@ -416,10 +404,8 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { LOGGER.error(EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION, "addOrUpdate", e); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } finally { - if (lockResult.isLeft() && lockResult.left().value()) { - graphLockOperation.unlockComponent(storedComponent.getUniqueId(), - NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); - } + graphLockOperation.unlockComponent(storedComponent.getUniqueId(), + NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); } } @@ -566,7 +552,7 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { } org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value(); - validateUserExists(user.getUserId(), GET_INTERFACE_OPERATION, true); + validateUserExists(user.getUserId()); Either<Boolean, ResponseFormat> lockResult = lockComponentResult(true, storedComponent, GET_INTERFACE_OPERATION); if (lockResult.isRight()) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/MonitoringBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/MonitoringBusinessLogic.java deleted file mode 100644 index b0bdf45c5a..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/MonitoringBusinessLogic.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.components.impl; - -import fj.data.Either; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.impl.MonitoringDao; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.openecomp.sdc.common.monitoring.MonitoringEvent; -import org.openecomp.sdc.exception.ResponseFormat; -import org.springframework.stereotype.Component; - -@Component("monitoringBusinessLogic") -public class MonitoringBusinessLogic { - - private static final Logger log = Logger.getLogger(MonitoringBusinessLogic.class); - - @javax.annotation.Resource - private MonitoringDao monitoringDao; - - @javax.annotation.Resource - private ComponentsUtils componentsUtils; - - public Either<Boolean, ResponseFormat> logMonitoringEvent(MonitoringEvent monitoringEvent) { - if (monitoringDao == null) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - ActionStatus status = monitoringDao.addRecord(monitoringEvent); - if (!status.equals(ActionStatus.OK)) { - log.warn("Failed to persist monitoring event: {}", status); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return Either.left(true); - } - - public String getEsHost() { - - String res = monitoringDao.getEsHost(); - res = res.replaceAll("[\\[\\]]", ""); - res = res.split(",")[0]; - res = res.replaceAll("[']", ""); - res = res.split(":")[0]; - return res; - } - - public String getEsPort() { - return monitoringDao.getEsPort(); - } - -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/NodeFilterUploadCreator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/NodeFilterUploadCreator.java index e622a3037a..927c8b17b7 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/NodeFilterUploadCreator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/NodeFilterUploadCreator.java @@ -16,17 +16,18 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; import org.onap.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.be.model.UploadNodeFilterCapabilitiesInfo; import org.openecomp.sdc.be.model.UploadNodeFilterInfo; import org.openecomp.sdc.be.model.UploadNodeFilterPropertyInfo; import org.openecomp.sdc.be.utils.TypeUtils; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + public class NodeFilterUploadCreator { public UploadNodeFilterInfo createNodeFilterData(Object obj) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java index 17233d6663..2d0ee0dd66 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java @@ -20,31 +20,19 @@ package org.openecomp.sdc.be.components.impl; -import static java.util.stream.Collectors.toMap; -import static org.openecomp.sdc.be.components.validation.PolicyUtils.getExcludedPolicyTypesByComponent; -import static org.openecomp.sdc.be.components.validation.PolicyUtils.getNextPolicyCounter; -import static org.openecomp.sdc.be.components.validation.PolicyUtils.validatePolicyFields; - import fj.data.Either; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.function.Function; -import java.util.stream.Collectors; -import javax.inject.Inject; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; +import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; +import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; import org.openecomp.sdc.be.components.property.PropertyDeclarationOrchestrator; import org.openecomp.sdc.be.components.validation.PolicyUtils; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.elements.GetPolicyValueDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstInputsMap; import org.openecomp.sdc.be.model.ComponentInstanceProperty; @@ -65,6 +53,20 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static java.util.stream.Collectors.toMap; +import static org.openecomp.sdc.be.components.validation.PolicyUtils.getExcludedPolicyTypesByComponent; +import static org.openecomp.sdc.be.components.validation.PolicyUtils.getNextPolicyCounter; +import static org.openecomp.sdc.be.components.validation.PolicyUtils.validatePolicyFields; + /** * Provides specified business logic to create, retrieve, update, delete a policy */ @@ -105,7 +107,23 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { * @return a policy or an error in a response format */ - public Either<PolicyDefinition, ResponseFormat> createPolicy(ComponentTypeEnum componentType, String componentId, String policyTypeName, String userId, boolean shouldLock) { + public PolicyDefinition createPolicy(ComponentTypeEnum componentType, String componentId, String policyTypeName, String userId, boolean shouldLock) { + + log.trace("#createPolicy - starting to create policy of the type {} on the component {}. ", policyTypeName, componentId); + Component component = null; + boolean failed = false; + try { + component = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock); + return createPolicy(policyTypeName, component); + }catch (ComponentException e){ + failed = true; + throw e; + }finally { + unlockComponent(shouldLock, failed, component); + } + } + + /*public Either<PolicyDefinition, ResponseFormat> createPolicy(ComponentTypeEnum componentType, String componentId, String policyTypeName, String userId, boolean shouldLock) { Either<PolicyDefinition, ResponseFormat> result = null; log.trace("#createPolicy - starting to create policy of the type {} on the component {}. ", policyTypeName, componentId); @@ -118,22 +136,24 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { return createPolicy(policyTypeName, c); }); } catch (Exception e) { + if (ComponentException.class.equals(e.getClass())) { + throw e; + } log.error("#createPolicy - the exception occurred upon creation of a policy of the type {} for the component {}: ", policyTypeName, componentId, e); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } finally { - + //TODO Andrey result = boolean unlockComponent(shouldLock, result, component); } return result; - } + }*/ public Either<List<PolicyDefinition>, ResponseFormat> getPoliciesList(ComponentTypeEnum componentType, String componentId, String userId) { Either<List<PolicyDefinition>, ResponseFormat> result; log.trace("#getPolicies - starting to retrieve policies of component {}. ", componentId); try { - result = validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId) - .left() - .bind(c -> Either.left(c.resolvePoliciesList())); + Component component = validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId); + result = Either.left(component.resolvePoliciesList()); } catch (Exception e) { log.error("#getPolicy - the exception occurred upon retrieving policies list of component {}: ", componentId, e); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -141,6 +161,8 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { return result; } + + /** * Retrieves the policy of the component by UniqueId * @@ -148,9 +170,15 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { * @param componentId the ID of the component * @param policyId the ID of the policy * @param userId the ID of the user - * @return either policy or error response + * @return either policy or error response */ - public Either<PolicyDefinition, ResponseFormat> getPolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId) { + public PolicyDefinition getPolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId) { + log.trace("#getPolicy - starting to retrieve the policy {} of the component {}. ", policyId, componentId); + Component component = validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId); + return getPolicyById(component, policyId); + } + + /*public Either<PolicyDefinition, ResponseFormat> getPolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId) { Either<PolicyDefinition, ResponseFormat> result; log.trace("#getPolicy - starting to retrieve the policy {} of the component {}. ", policyId, componentId); try { @@ -162,7 +190,7 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } return result; - } + }*/ /** * Updates the policy of the component @@ -174,7 +202,25 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { * @param shouldLock the flag defining if the component should be locked * @return a policy or an error in a response format */ - public Either<PolicyDefinition, ResponseFormat> updatePolicy(ComponentTypeEnum componentType, String componentId, PolicyDefinition policy, String userId, boolean shouldLock) { + public PolicyDefinition updatePolicy(ComponentTypeEnum componentType, String componentId, PolicyDefinition policy, String userId, boolean shouldLock) { + Component component = null; + boolean failed = false; + log.trace("#updatePolicy - starting to update the policy {} on the component {}. ", policy.getUniqueId(), componentId); + try { + component = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock); + return validateAndUpdatePolicy(component, policy); + } catch (ComponentException e) { + failed = true; + log.error("#updatePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policy.getUniqueId(), componentId, e); + throw e; + } finally { + //TODO Andrey result = boolean + unlockComponent(shouldLock, failed, component); + } + } + + + /*public Either<PolicyDefinition, ResponseFormat> updatePolicy(ComponentTypeEnum componentType, String componentId, PolicyDefinition policy, String userId, boolean shouldLock) { Either<PolicyDefinition, ResponseFormat> result = null; log.trace("#updatePolicy - starting to update the policy {} on the component {}. ", policy.getUniqueId(), componentId); Wrapper<Component> component = new Wrapper<>(); @@ -189,10 +235,11 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { log.error("#updatePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policy.getUniqueId(), componentId, e); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } finally { + //TODO Andrey result = boolean unlockComponent(shouldLock, result, component); } return result; - } + }*/ /** * Deletes the policy from the component @@ -204,7 +251,25 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { * @param shouldLock the flag defining if the component should be locked * @return a policy or an error in a response format */ - public Either<PolicyDefinition, ResponseFormat> deletePolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId, boolean shouldLock) { + public PolicyDefinition deletePolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId, boolean shouldLock) { + PolicyDefinition result = null; + log.trace("#deletePolicy - starting to update the policy {} on the component {}. ", policyId, componentId); + Component component = null; + boolean failed= false; + try { + component = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock); + return deletePolicy(component, policyId); + } catch (ComponentException e) { + failed = true; + log.error("#deletePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policyId, componentId, e); + throw e; + } finally { + unlockComponent(shouldLock, failed, component); + } + } + + + /*public Either<PolicyDefinition, ResponseFormat> deletePolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId, boolean shouldLock) { Either<PolicyDefinition, ResponseFormat> result = null; log.trace("#deletePolicy - starting to update the policy {} on the component {}. ", policyId, componentId); Wrapper<Component> component = new Wrapper<>(); @@ -254,18 +319,14 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { } finally { unlockComponent(shouldLock, result, component); } - } + }*/ public Either<PolicyDefinition, ResponseFormat> undeclarePolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId, boolean shouldLock) { Either<PolicyDefinition, ResponseFormat> result = null; log.trace("#undeclarePolicy - starting to undeclare policy {} on component {}. ", policyId, componentId); Wrapper<Component> component = new Wrapper<>(); try { - Either<Component, ResponseFormat> componentEither = - validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock); - if (componentEither.isRight()) { - return Either.right(componentEither.right().value()); - } + validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock); ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.disableAll(); @@ -287,117 +348,113 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { } return result; - } catch (Exception e) { + }catch (Exception e) { log.error("#undeclarePolicy - the exception occurred upon update of a policy of type {} for component {}: ", policyId, componentId, e); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, e.getMessage())); } finally { - unlockComponent(shouldLock, result, component); + if (result == null || result.isRight()){ + unlockComponent(shouldLock, true, component); + } else { + unlockComponent(shouldLock, false, component); + } } } - - private Either<PolicyDefinition, ResponseFormat> undeclarePolicy(PolicyDefinition policyDefinition, Component containerComponent) { - StorageOperationStatus undeclareStatus = propertyDeclarationOrchestrator - .unDeclarePropertiesAsPolicies(containerComponent, policyDefinition); - if(undeclareStatus != StorageOperationStatus.OK){ - return Either.right(componentsUtils.getResponseFormat(undeclareStatus)); - } else { - return Either.left(policyDefinition); + private Either<PolicyDefinition, ResponseFormat> undeclarePolicy(PolicyDefinition policyDefinition, Component containerComponent) { + StorageOperationStatus undeclareStatus = propertyDeclarationOrchestrator + .unDeclarePropertiesAsPolicies(containerComponent, policyDefinition); + if(undeclareStatus != StorageOperationStatus.OK){ + return Either.right(componentsUtils.getResponseFormat(undeclareStatus)); + } else { + return Either.left(policyDefinition); + } } - } - private Optional<PolicyDefinition> getPolicyForUndeclaration(String policyId, Component component) { - Map<String, PolicyDefinition> policies = component.getPolicies(); - if(MapUtils.isNotEmpty(policies) && policies.containsKey(policyId)) { - return Optional.of(policies.get(policyId)); - } + private Optional<PolicyDefinition> getPolicyForUndeclaration(String policyId, Component component) { + Map<String, PolicyDefinition> policies = component.getPolicies(); + if(MapUtils.isNotEmpty(policies) && policies.containsKey(policyId)) { + return Optional.of(policies.get(policyId)); + } - Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = - MapUtils.isEmpty(component.getComponentInstancesProperties()) ? new HashMap<>() : component.getComponentInstancesProperties(); + Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = + MapUtils.isEmpty(component.getComponentInstancesProperties()) ? new HashMap<>() : component.getComponentInstancesProperties(); - for(Map.Entry<String, List<ComponentInstanceProperty>> instancePropertyEntry : componentInstancesProperties.entrySet()) { - Optional<ComponentInstanceProperty> propertyCandidate = getPropertyForDeclaredPolicy(policyId, instancePropertyEntry.getValue()); + for(Map.Entry<String, List<ComponentInstanceProperty>> instancePropertyEntry : componentInstancesProperties.entrySet()) { + Optional<ComponentInstanceProperty> propertyCandidate = getPropertyForDeclaredPolicy(policyId, instancePropertyEntry.getValue()); - if(propertyCandidate.isPresent()) { - return Optional.of( - PolicyUtils.getDeclaredPolicyDefinition(instancePropertyEntry.getKey(), propertyCandidate.get())); + if(propertyCandidate.isPresent()) { + return Optional.of( + PolicyUtils.getDeclaredPolicyDefinition(instancePropertyEntry.getKey(), propertyCandidate.get())); + } } - } - return Optional.empty(); - } + return Optional.empty(); + } - private Optional<ComponentInstanceProperty> getPropertyForDeclaredPolicy(String policyId, List<ComponentInstanceProperty> componentInstanceProperties) { - for(ComponentInstanceProperty property : componentInstanceProperties) { - Optional<GetPolicyValueDataDefinition> getPolicyCandidate = property.safeGetGetPolicyValues().stream() - .filter(getPolicyValue -> getPolicyValue.getPolicyId() - .equals(policyId)) - .findAny(); + private Optional<ComponentInstanceProperty> getPropertyForDeclaredPolicy(String policyId, List<ComponentInstanceProperty> componentInstanceProperties) { + for(ComponentInstanceProperty property : componentInstanceProperties) { + Optional<GetPolicyValueDataDefinition> getPolicyCandidate = property.safeGetGetPolicyValues().stream() + .filter(getPolicyValue -> getPolicyValue.getPolicyId() + .equals(policyId)) + .findAny(); - if(getPolicyCandidate.isPresent()) { - return Optional.of(property); + if(getPolicyCandidate.isPresent()) { + return Optional.of(property); + } } + + return Optional.empty(); } - return Optional.empty(); - } - public Either<PolicyDefinition, ResponseFormat> updatePolicyTargets(ComponentTypeEnum componentTypeEnum, String componentId, String policyId, Map<PolicyTargetType, List<String>> targets, String userId) { + public PolicyDefinition updatePolicyTargets(ComponentTypeEnum componentTypeEnum, String componentId, String policyId, Map<PolicyTargetType, List<String>> targets, String userId) { Either<PolicyDefinition, ResponseFormat> result = null; log.debug("updating the policy id {} targets with the components {}. ", policyId, componentId); + boolean failed = false; try { //not right error response - result = validateAndLockComponentAndUserBeforeWriteOperation(componentTypeEnum, componentId, userId, true) - .left() - .bind(cmpt -> validateAndUpdatePolicyTargets(cmpt, policyId, targets)); - - return result; - } finally { - - unlockComponentById(result, componentId); - + Component component = validateAndLockComponentAndUserBeforeWriteOperation(componentTypeEnum, componentId, userId, true); + return validateAndUpdatePolicyTargets(component, policyId, targets); + }catch (ComponentException e){ + failed = true; + throw e; + }finally { + unlockComponentById(failed, componentId); } - } - private Either<PolicyDefinition, ResponseFormat> validateAndUpdatePolicyTargets(Component component, String policyId, Map<PolicyTargetType, List<String>> targets) { - return validateTargetsExistAndTypesCorrect(component.getUniqueId(), targets) - .left() - .bind(cmp ->updateTargets(component.getUniqueId(), component.getPolicyById(policyId), targets, policyId)); - + private PolicyDefinition validateAndUpdatePolicyTargets(Component component, String policyId, Map<PolicyTargetType, List<String>> targets) { + validateTargetsExistAndTypesCorrect(component.getUniqueId(), targets); + return updateTargets(component.getUniqueId(), component.getPolicyById(policyId), targets, policyId); } - private Either<Component, ResponseFormat> validateTargetsExistAndTypesCorrect(String componentId, Map<PolicyTargetType, List<String>> targets) { + private Component validateTargetsExistAndTypesCorrect(String componentId, Map<PolicyTargetType, List<String>> targets) { Either<Component, StorageOperationStatus> componentEither = toscaOperationFacade.getToscaFullElement(componentId); if (componentEither.isRight()) { - return Either.right(componentsUtils.getResponseFormat(componentEither.right().value())); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(componentEither.right().value())); } Component parentComponent = componentEither.left().value(); return validateTargetExists(parentComponent, targets.entrySet()); } - - private Either<Component, ResponseFormat> validateTargetExists(Component parentComponent, Set<Map.Entry<PolicyTargetType, List<String>>> entries) { - for(Map.Entry<PolicyTargetType, List<String>> entry : entries){ - Either<Component, ResponseFormat> result = checkTargetNotExistOnComponentByType(parentComponent, entry); - if(result.isRight()){ - return result; - } + private Component validateTargetExists(Component parentComponent, Set<Map.Entry<PolicyTargetType, List<String>>> entries) { + for (Map.Entry<PolicyTargetType, List<String>> entry : entries) { + checkTargetNotExistOnComponentByType(parentComponent, entry); } - return Either.left(parentComponent); + return parentComponent; } - private Either<Component, ResponseFormat> checkTargetNotExistOnComponentByType(Component parentComponent, Map.Entry<PolicyTargetType, List<String>> targetEntry) { + private Component checkTargetNotExistOnComponentByType(Component parentComponent, Map.Entry<PolicyTargetType, List<String>> targetEntry) { - for(String id : targetEntry.getValue()){ - if(checkNotPresenceInComponentByType(parentComponent, id, targetEntry.getKey().getName())){ - return Either.right(componentsUtils.getResponseFormat(ActionStatus.POLICY_TARGET_DOES_NOT_EXIST, id)); + for (String id : targetEntry.getValue()) { + if (checkNotPresenceInComponentByType(parentComponent, id, targetEntry.getKey().getName())) { + throw new ByActionStatusComponentException(ActionStatus.POLICY_TARGET_DOES_NOT_EXIST, id); } } - return Either.left(parentComponent); + return parentComponent; } private boolean checkNotPresenceInComponentByType(Component parentComponent, String uniqueId, String type) { @@ -422,7 +479,17 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { * @param userId the user id * @return a list of policy properties or an error in a response format */ - public Either<List<PropertyDataDefinition>, ResponseFormat> getPolicyProperties(ComponentTypeEnum componentType, String componentId, String policyId, String userId) { + public List<PropertyDataDefinition> getPolicyProperties(ComponentTypeEnum componentType, String componentId, String policyId, String userId) { + log.debug("#getPolicyProperties - fetching policy properties for component {} and policy {}", componentId, policyId); + try { + Component component = validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId); + return getPolicyById(component, policyId).getProperties(); + } finally { + janusGraphDao.commit(); + } + } + + /*public Either<List<PropertyDataDefinition>, ResponseFormat> getPolicyProperties(ComponentTypeEnum componentType, String componentId, String policyId, String userId) { log.debug("#getPolicyProperties - fetching policy properties for component {} and policy {}", componentId, policyId); try { return validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId) @@ -431,7 +498,7 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { } finally { janusGraphDao.commit(); } - } + }*/ /** * Updates the policy properties of the component @@ -444,19 +511,18 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { * @param shouldLock the flag defining if the component should be locked * @return a list of policy properties or anerrorin a response format */ - public Either<List<PropertyDataDefinition>, ResponseFormat> updatePolicyProperties(ComponentTypeEnum componentType, String componentId, String policyId, PropertyDataDefinition[] properties, String userId, boolean shouldLock) { - Either<List<PropertyDataDefinition>, ResponseFormat> result = null; + public List<PropertyDataDefinition> updatePolicyProperties(ComponentTypeEnum componentType, String componentId, String policyId, PropertyDataDefinition[] properties, String userId, boolean shouldLock) { + List<PropertyDataDefinition> result; + Component component = null; log.trace("#updatePolicyProperties - starting to update properties of the policy {} on the component {}. ", policyId, componentId); - Wrapper<Component> component = new Wrapper<>(); + boolean failed = true; try { - result = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock).left() - .bind(c -> setComponentValidateUpdatePolicyProperties(policyId, properties, component, c)); - } catch (Exception e) { - log.error("#updatePolicyProperties - the exception {} occurred upon update properties of the policy {} for the component {}: ", policyId, componentId, e); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + component = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock); + failed = false; + result = setComponentValidateUpdatePolicyProperties(policyId, properties, component); } finally { - if (shouldLock && !component.isEmpty()) { - unlockComponent(result, component.getInnerElement()); + if (shouldLock && !failed) { + unlockComponent(failed, component); } } return result; @@ -476,7 +542,7 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { org.openecomp.sdc.be.model.Component component = null; try { - validateUserExists(userId, DECLARE_PROPERTIES_TO_POLICIES, false); + validateUserExists(userId); ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.disableAll(); @@ -485,27 +551,13 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { componentParametersView.setIgnorePolicies(false); componentParametersView.setIgnoreUsers(false); - Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentTypeEnum, componentParametersView); - - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - component = validateComponent.left().value(); + component = validateComponentExists(componentId, componentTypeEnum, componentParametersView); if (shouldLock) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, DECLARE_PROPERTIES_TO_POLICIES); - if (lockComponent.isRight()) { - result = Either.right(lockComponent.right().value()); - return result; - } + lockComponent(component, DECLARE_PROPERTIES_TO_POLICIES); } - Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId); - if (canWork.isRight()) { - result = Either.right(canWork.right().value()); - return result; - } + validateCanWorkOnComponent(component, userId); Either<List<PolicyDefinition>, StorageOperationStatus> declarePropertiesEither = propertyDeclarationOrchestrator.declarePropertiesToPolicies(component, componentInstInputsMap); @@ -527,60 +579,96 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { } } - private Either<List<PropertyDataDefinition>, ResponseFormat> setComponentValidateUpdatePolicyProperties(String policyId, PropertyDataDefinition[] properties, Wrapper<Component> component, Component c) { - component.setInnerElement(c); + private List<PropertyDataDefinition> setComponentValidateUpdatePolicyProperties(String policyId, PropertyDataDefinition[] properties, Component component) { Set<String> updatedPropertyNames = Arrays.stream(properties).map(PropertyDataDefinition::getName).collect(Collectors.toSet()); - return validateAndUpdatePolicyProperties(c, policyId, properties) - .left() - .map(policyDefinition -> getFilteredProperties(policyDefinition.getProperties(), updatedPropertyNames)); + + PolicyDefinition policyDefinition = validateAndUpdatePolicyProperties(component, policyId, properties); + return getFilteredProperties(policyDefinition.getProperties(), updatedPropertyNames); } private List<PropertyDataDefinition> getFilteredProperties(List<PropertyDataDefinition> all, Set<String> filtered) { return all.stream().filter(pd -> filtered.contains(pd.getName())).collect(Collectors.toList()); } - private void unlockComponent(boolean shouldLock, Either<PolicyDefinition, ResponseFormat> result, Wrapper<Component> component) { + private void unlockComponent(boolean shouldLock, boolean result, Component component) { + if (shouldLock && component != null) { + unlockComponent(result, component); + } + } + + + private void unlockComponent(boolean shouldLock, boolean result, Wrapper<Component> component) { if (shouldLock && !component.isEmpty()) { unlockComponent(result, component.getInnerElement()); } } - private Either<PolicyDefinition, ResponseFormat> getPolicyById(Component component, String policyId) { + private PolicyDefinition getPolicyById(Component component, String policyId) { PolicyDefinition policyById = component.getPolicyById(policyId); if (policyById == null) { String cmptId = component.getUniqueId(); log.debug("#getPolicyById - policy with id {} does not exist on component with id {}", policyId, cmptId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER, policyId, cmptId)); + throw new ByActionStatusComponentException(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER, policyId, cmptId); } - return Either.left(policyById); + return policyById; + } + + private PolicyDefinition createPolicy(String policyTypeName, Component component) { + PolicyTypeDefinition policyTypeDefinition = validatePolicyTypeOnCreatePolicy(policyTypeName, component); + return addPolicyToComponent(policyTypeDefinition, component); } - private Either<PolicyDefinition, ResponseFormat> createPolicy(String policyTypeName, Component component) { + /*private Either<PolicyDefinition, ResponseFormat> createPolicy(String policyTypeName, Component component) { return validatePolicyTypeOnCreatePolicy(policyTypeName, component).left().bind(type -> addPolicyToComponent(type, component)); + }*/ + + private PolicyDefinition addPolicyToComponent(PolicyTypeDefinition policyType, Component component) { + Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent = + toscaOperationFacade.associatePolicyToComponent(component.getUniqueId(), new PolicyDefinition(policyType), getNextPolicyCounter(component.getPolicies())); + if(associatePolicyToComponent.isRight()){ + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(associatePolicyToComponent.right().value())); + } + return associatePolicyToComponent.left().value(); } - private Either<PolicyDefinition, ResponseFormat> addPolicyToComponent(PolicyTypeDefinition policyType, Component component) { + /*private Either<PolicyDefinition, ResponseFormat> addPolicyToComponent(PolicyTypeDefinition policyType, Component component) { return toscaOperationFacade.associatePolicyToComponent(component.getUniqueId(), new PolicyDefinition(policyType), getNextPolicyCounter(component.getPolicies())) .either(Either::left, r -> Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(r)))); + }*/ + + private PolicyTypeDefinition validatePolicyTypeOnCreatePolicy(String policyTypeName, Component component) { + Either<PolicyTypeDefinition, StorageOperationStatus> latestPolicyTypeByType = policyTypeOperation.getLatestPolicyTypeByType(policyTypeName); + if(latestPolicyTypeByType.isRight()){ + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(latestPolicyTypeByType.right().value())); + } + return validatePolicyTypeNotExcluded(latestPolicyTypeByType.left().value(), component); } - private Either<PolicyTypeDefinition, ResponseFormat> validatePolicyTypeOnCreatePolicy(String policyTypeName, Component component) { + /*private Either<PolicyTypeDefinition, ResponseFormat> validatePolicyTypeOnCreatePolicy(String policyTypeName, Component component) { return policyTypeOperation.getLatestPolicyTypeByType(policyTypeName) .either(l -> validatePolicyTypeNotExcluded(l, component), r -> Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(r)))); - } + }*/ - private Either<PolicyTypeDefinition, ResponseFormat> validatePolicyTypeNotExcluded(PolicyTypeDefinition policyType, Component component) { + private PolicyTypeDefinition validatePolicyTypeNotExcluded(PolicyTypeDefinition policyType, Component component) { if (getExcludedPolicyTypesByComponent(component).contains(policyType.getType())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCLUDED_POLICY_TYPE, policyType.getType(), getComponentOrResourceTypeName(component))); + throw new ByActionStatusComponentException(ActionStatus.EXCLUDED_POLICY_TYPE, policyType.getType(), getComponentOrResourceTypeName(component)); } - return Either.left(policyType); + return policyType; } private String getComponentOrResourceTypeName(Component component) { return component.getComponentType() == ComponentTypeEnum.SERVICE ? ComponentTypeEnum.SERVICE.name() : ((Resource) component).getResourceType().name(); } - private Either<Component, ResponseFormat> validateAndLockComponentAndUserBeforeWriteOperation(ComponentTypeEnum componentType, String componentId, String userId, boolean shouldLock) { + private Component validateAndLockComponentAndUserBeforeWriteOperation(ComponentTypeEnum componentType, String componentId, String userId, boolean shouldLock) { + Component component = validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId); + validateComponentIsTopologyTemplate(component); + validateCanWorkOnComponent(component, userId); + lockComponent(component, shouldLock, "policyWritingOperation"); + return component; + } + + /*private Either<Component, ResponseFormat> validateAndLockComponentAndUserBeforeWriteOperation(ComponentTypeEnum componentType, String componentId, String userId, boolean shouldLock) { Wrapper<Component> component = new Wrapper<>(); return validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId) .left() @@ -588,7 +676,8 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { .left() .bind(c -> { component.setInnerElement(c); - return validateCanWorkOnComponent(c, userId); + validateCanWorkOnComponent(c, userId); + return Either.left(component); }) .left() .bind(l -> lockComponent(component.getInnerElement(), shouldLock, "policyWritingOperation")) @@ -596,28 +685,32 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { log.error(FAILED_TO_VALIDATE_COMPONENT, componentId); return Either.right(r); }); + }*/ + + private Component validateComponentIsTopologyTemplate(Component component) { + if (!component.isTopologyTemplate()) { + log.error("#validateComponentIsTopologyTemplate - policy association to a component of Tosca type {} is not allowed. ", + component.getToscaType()); + throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_POLICIES, + "#validateAndLockComponentAndUserBeforeWriteOperation", component.getUniqueId(), component.getToscaType()); + } + return component; } - private Either<Component, ResponseFormat> validateComponentIsTopologyTemplate(Component component) { + /*private Either<Component, ResponseFormat> validateComponentIsTopologyTemplate(Component component) { if (!component.isTopologyTemplate()) { log.error("#validateComponentIsTopologyTemplate - policy association to a component of Tosca type {} is not allowed. ", component.getToscaType()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_POLICIES, "#validateAndLockComponentAndUserBeforeWriteOperation", component.getUniqueId(), component.getToscaType())); } return Either.left(component); - } - - private Either<Component, ResponseFormat> validateContainerComponentAndUserBeforeReadOperation(ComponentTypeEnum componentType, String componentId, String userId) { - Either<Component, ResponseFormat> result; + }*/ + private Component validateContainerComponentAndUserBeforeReadOperation(ComponentTypeEnum componentType, String componentId, String userId) { log.trace("#validateContainerComponentAndUserBeforeReadOperation - starting to validate the user {} before policy processing. ", userId); - validateUserExists(userId, "create Policy", false); - result = validateComponentExists(componentType, componentId); - if (result.isRight()) { - log.error(FAILED_TO_VALIDATE_COMPONENT, "#validateContainerComponentAndUserBeforeReadOperation", componentId); - } - return result; + validateUserExists(userId); + return validateComponentExists(componentType, componentId); } - private Either<Component, ResponseFormat> validateComponentExists(ComponentTypeEnum componentType, String componentId) { + private Component validateComponentExists(ComponentTypeEnum componentType, String componentId) { ComponentParametersView filter = new ComponentParametersView(true); filter.setIgnorePolicies(false); @@ -628,89 +721,101 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { } - private Either<PolicyDefinition, ResponseFormat> validateAndUpdatePolicy(Component component, PolicyDefinition policy) { + private PolicyDefinition validateAndUpdatePolicy(Component component, PolicyDefinition policy) { + PolicyDefinition policyById = getPolicyById(component, policy.getUniqueId()); + PolicyDefinition policyDefinition = validateUpdatePolicyBeforeUpdate(policy, policyById, component.getPolicies()); + return updatePolicyOfComponent(component, policyDefinition); + } + + /*private Either<PolicyDefinition, ResponseFormat> validateAndUpdatePolicy(Component component, PolicyDefinition policy) { return getPolicyById(component, policy.getUniqueId()) .left() .bind(np -> validateUpdatePolicyBeforeUpdate(policy, np, component.getPolicies())) .left() .bind(p -> updatePolicyOfComponent(component, p)); - } + }*/ - private Either<PolicyDefinition, ResponseFormat> validateAndUpdatePolicyProperties(Component component, String policyId, PropertyDataDefinition[] properties) { - return getPolicyById(component, policyId) - .left() - .bind(p -> validateUpdatePolicyPropertiesBeforeUpdate(p, properties)) - .left().bind(l -> updatePolicyOfComponent(component.getUniqueId(), l)); + private PolicyDefinition validateAndUpdatePolicyProperties(Component component, String policyId, PropertyDataDefinition[] properties) { + + PolicyDefinition policyById = getPolicyById(component, policyId); + policyById = validateUpdatePolicyPropertiesBeforeUpdate(policyById, properties); + return updatePolicyOfComponent(component.getUniqueId(), policyById); } - private Either<PolicyDefinition, ResponseFormat> updatePolicyOfComponent(String componentId, PolicyDefinition policy) { - return toscaOperationFacade.updatePolicyOfComponent(componentId, policy) - .right() - .bind(r -> Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(r)))); + private PolicyDefinition updatePolicyOfComponent(String componentId, PolicyDefinition policy) { + return toscaOperationFacade.updatePolicyOfComponent(componentId, policy, PromoteVersionEnum.MINOR) + .left() + .on(ce->componentExceptionPolicyDefinition(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(ce)))); } - private Either<PolicyDefinition, ResponseFormat> validateUpdatePolicyPropertiesBeforeUpdate(PolicyDefinition policy, PropertyDataDefinition[] newProperties) { + private PolicyDefinition validateUpdatePolicyPropertiesBeforeUpdate(PolicyDefinition policy, PropertyDataDefinition[] newProperties) { if (CollectionUtils.isEmpty(policy.getProperties())) { log.error("#validateUpdatePolicyPropertiesBeforeUpdate - failed to update properites of the policy. Properties were not found on the policy. "); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND)); + throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND); } return updatePropertyValues(policy, newProperties); } - private Either<PolicyDefinition, ResponseFormat> updatePropertyValues(PolicyDefinition policy, PropertyDataDefinition[] newProperties) { + private PolicyDefinition updatePropertyValues(PolicyDefinition policy, PropertyDataDefinition[] newProperties) { Map<String, PropertyDataDefinition> oldProperties = policy.getProperties().stream().collect(toMap(PropertyDataDefinition::getName, Function.identity())); for (PropertyDataDefinition newProperty : newProperties) { if (!oldProperties.containsKey(newProperty.getName())) { log.error("#updatePropertyValues - failed to update properites of the policy {}. Properties were not found on the policy. ", policy.getName()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, newProperty.getName())); - } - Either<String, ResponseFormat> newPropertyValueEither = updateInputPropertyObjectValue(newProperty); - if (newPropertyValueEither.isRight()) { - return Either.right(newPropertyValueEither.right().value()); + throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, newProperty.getName()); } - oldProperties.get(newProperty.getName()).setValue(newPropertyValueEither.left().value()); + String newPropertyValueEither = updateInputPropertyObjectValue(newProperty); + oldProperties.get(newProperty.getName()).setValue(newPropertyValueEither); } - return Either.left(policy); + return policy; } - private Either<PolicyDefinition, ResponseFormat> deletePolicy(Component component, String policyId) { - return getPolicyById(component, policyId) - .left() - .bind(p -> removePolicyFromComponent(component, p)); + private PolicyDefinition deletePolicy(Component component, String policyId) { + PolicyDefinition policyById = getPolicyById(component, policyId); + return removePolicyFromComponent(component, policyById); } - private Either<PolicyDefinition, ResponseFormat> updatePolicyOfComponent(Component component, PolicyDefinition policy) { - Either<PolicyDefinition, StorageOperationStatus> updatePolicyRes = toscaOperationFacade.updatePolicyOfComponent(component.getUniqueId(), policy); + private PolicyDefinition updatePolicyOfComponent(Component component, PolicyDefinition policy) { + + Either<PolicyDefinition, StorageOperationStatus> updatePolicyRes = toscaOperationFacade.updatePolicyOfComponent(component.getUniqueId(), policy, PromoteVersionEnum.MINOR); if (updatePolicyRes.isRight()) { log.error("#updatePolicyOfComponent - failed to update policy {} of the component {}. The status is {}. ", policy.getUniqueId(), component.getName(), updatePolicyRes.right().value()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updatePolicyRes.right().value()))); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(updatePolicyRes.right().value())); } else { log.trace("#updatePolicyOfComponent - the policy with the name {} was updated. ", updatePolicyRes.left().value().getName()); - return Either.left(updatePolicyRes.left().value()); + return updatePolicyRes.left().value(); } } - private Either<PolicyDefinition, ResponseFormat> removePolicyFromComponent(Component component, PolicyDefinition policy) { + private PolicyDefinition removePolicyFromComponent(Component component, PolicyDefinition policy) { StorageOperationStatus updatePolicyStatus = toscaOperationFacade.removePolicyFromComponent(component.getUniqueId(), policy.getUniqueId()); if (updatePolicyStatus != StorageOperationStatus.OK) { log.error("#removePolicyFromComponent - failed to remove policy {} from the component {}. The status is {}. ", policy.getUniqueId(), component.getName(), updatePolicyStatus); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updatePolicyStatus))); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(updatePolicyStatus)); } else { log.trace("#removePolicyFromComponent - the policy with the name {} was deleted. ", updatePolicyStatus); - return Either.left(policy); + return policy; } } - private Either<PolicyDefinition, ResponseFormat> validateUpdatePolicyBeforeUpdate(PolicyDefinition recievedPolicy, PolicyDefinition oldPolicy, Map<String, PolicyDefinition> policies) { + private PolicyDefinition validateUpdatePolicyBeforeUpdate(PolicyDefinition recievedPolicy, PolicyDefinition oldPolicy, Map<String, PolicyDefinition> policies) { + + Either<PolicyDefinition, ActionStatus> policyDefinitionActionStatusEither = validatePolicyFields(recievedPolicy, new PolicyDefinition(oldPolicy), policies); + if(policyDefinitionActionStatusEither.isRight()){ + throw new ByActionStatusComponentException(policyDefinitionActionStatusEither.right().value(), recievedPolicy.getName()); + } + return policyDefinitionActionStatusEither.left().value(); + } + + /*private Either<PolicyDefinition, ResponseFormat> validateUpdatePolicyBeforeUpdate(PolicyDefinition recievedPolicy, PolicyDefinition oldPolicy, Map<String, PolicyDefinition> policies) { return validatePolicyFields(recievedPolicy, new PolicyDefinition(oldPolicy), policies) .right() .bind(r -> Either.right(componentsUtils.getResponseFormat(r, recievedPolicy.getName()))); - } + }*/ - private Either<PolicyDefinition, ResponseFormat> updateTargets(String componentId, PolicyDefinition policy, Map<PolicyTargetType, List<String>> targets, String policyId) { - if(policy == null){ - return Either.right(componentsUtils.getResponseFormat(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER, policyId, componentId)); + private PolicyDefinition updateTargets(String componentId, PolicyDefinition policy, Map<PolicyTargetType, List<String>> targets, String policyId) { + if (policy == null) { + throw new ByActionStatusComponentException(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER, policyId, componentId); } PolicyDefinition updatedPolicy = setPolicyTargets(policy, targets); return updatePolicyOfComponent(componentId, updatedPolicy); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java index 2213719b41..6154061056 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java @@ -59,7 +59,7 @@ public class PolicyTypeBusinessLogic { @Transactional public List<PolicyTypeDefinition> getAllPolicyTypes(String userId, String internalComponentType) { Set<String> excludedPolicyTypes = getExcludedPolicyTypes(internalComponentType); - userValidations.validateUserExists(userId, "get policy types", true); + userValidations.validateUserExists(userId); return getPolicyTypes(excludedPolicyTypes); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java index 090d3b2d3c..377feb470d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java @@ -30,10 +30,10 @@ import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.GroupTypeDefinition; import org.openecomp.sdc.be.model.PolicyTypeDefinition; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; -import org.openecomp.sdc.be.model.operations.api.IGroupOperation; -import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation; import org.openecomp.sdc.be.model.operations.api.IPolicyTypeOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.GroupOperation; +import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation; import org.openecomp.sdc.be.utils.TypeUtils; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Component; @@ -47,14 +47,14 @@ public class PolicyTypeImportManager { private final IPolicyTypeOperation policyTypeOperation; private final ComponentsUtils componentsUtils; - private final IGroupOperation groupOperation; + private final GroupOperation groupOperation; private final ToscaOperationFacade toscaOperationFacade; private final CommonImportManager commonImportManager; - private final IGroupTypeOperation groupTypeOperation; + private final GroupTypeOperation groupTypeOperation; public PolicyTypeImportManager(IPolicyTypeOperation policyTypeOperation, ComponentsUtils componentsUtils, - IGroupOperation groupOperation, ToscaOperationFacade toscaOperationFacade, - CommonImportManager commonImportManager, IGroupTypeOperation groupTypeOperation) { + GroupOperation groupOperation, ToscaOperationFacade toscaOperationFacade, + CommonImportManager commonImportManager, GroupTypeOperation groupTypeOperation) { this.policyTypeOperation = policyTypeOperation; this.componentsUtils = componentsUtils; this.groupOperation = groupOperation; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java index 8f3d17b74d..c643d9f937 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java @@ -24,6 +24,14 @@ package org.openecomp.sdc.be.components.impl; import fj.data.Either; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; +import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; +import org.openecomp.sdc.be.components.validation.component.ComponentContactIdValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentDescriptionValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentIconValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentNameValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentProjectCodeValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentTagsValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentValidator; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -53,7 +61,12 @@ import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.stream.Collectors; @org.springframework.stereotype.Component("productBusinessLogic") @@ -80,9 +93,18 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsBusinessLogic artifactsBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBusinessLogic, - ArtifactsOperations artifactToscaOperation) { + ArtifactsOperations artifactToscaOperation, + ComponentContactIdValidator componentContactIdValidator, + ComponentNameValidator componentNameValidator, + ComponentTagsValidator componentTagsValidator, + ComponentValidator componentValidator, + ComponentIconValidator componentIconValidator, + ComponentProjectCodeValidator componentProjectCodeValidator, + ComponentDescriptionValidator componentDescriptionValidator){ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic, - interfaceOperation, interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation); + interfaceOperation, interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, + componentContactIdValidator, componentNameValidator, componentTagsValidator, componentValidator, + componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator); this.componentInstanceBusinessLogic = componentInstanceBusinessLogic; creationRoles = new ArrayList<>(); @@ -201,9 +223,10 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { return componentNameValidation; } - Either<Boolean, ResponseFormat> componentNameUniquenessValidation = validateComponentNameUnique(user, product, actionEnum); - if (componentNameUniquenessValidation.isRight()) { - return componentNameUniquenessValidation; + try { + componentNameValidator.validateComponentNameUnique(user, product, actionEnum); + } catch (ComponentException exp) { + return Either.right(exp.getResponseFormat()); } // To be removed in 1607 and replaced with generic @@ -215,11 +238,12 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { return tagsValidation; } - validateIcon(user, product, actionEnum); + componentTagsValidator.validateAndCorrectField(user, product, actionEnum); - Either<Boolean, ResponseFormat> projectCodeValidation = validateProjectCode(user, product, actionEnum); - if (projectCodeValidation.isRight()) { - return projectCodeValidation; + try { + componentProjectCodeValidator.validateAndCorrectField(user, product, actionEnum); + } catch (ComponentException exp) { + return Either.right(exp.getResponseFormat()); } Either<Boolean, ResponseFormat> categoryValidation = validateGrouping(user, product, actionEnum); if (categoryValidation.isRight()) { @@ -236,14 +260,14 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { return productFullNameValidation; } - validateDescriptionAndCleanup(user, product, actionEnum); + componentDescriptionValidator.validateAndCorrectField(user, product, actionEnum); return Either.left(true); } public Either<Map<String, Boolean>, ResponseFormat> validateProductNameExists(String productName, String userId) { - validateUserExists(userId, "validate Product Name Exists", false); + validateUserExists(userId); Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(productName, null, ComponentTypeEnum.PRODUCT); // DE242223 janusGraphDao.commit(); @@ -287,7 +311,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { User contactUser; try{ - contactUser = validateUserExists(contact, CREATE_PRODUCT, false); + contactUser = validateUserExists(contact); validateUserRole(contactUser, contactsRoles); } catch(ByActionStatusComponentException e){ log.debug("Cannot set contact with userId {} as product contact, error: {}", contact, e.getActionStatus()); @@ -465,13 +489,13 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { public Either<Product, ResponseFormat> getProduct(String productId, User user) { String ecompErrorContext = "Get product"; validateUserNotEmpty(user, ecompErrorContext); - validateUserExists(user, ecompErrorContext, false); + validateUserExists(user); Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(productId); if (storageStatus.isRight()) { log.debug("failed to get resource by id {}", productId); - if (storageStatus.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + if (storageStatus.right().value() == StorageOperationStatus.NOT_FOUND) { // TODO check error return Either.right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.getValue())); } else { @@ -484,7 +508,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { public Either<Product, ResponseFormat> deleteProduct(String productId, User user) { String ecompErrorContext = "Delete product"; validateUserNotEmpty(user, ecompErrorContext); - validateUserExists(user, ecompErrorContext, false); + validateUserExists(user); Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.deleteToscaComponent(productId); @@ -563,9 +587,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { // component name, and BE will add it by itself after all needed // normalizations. private Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Product product, String oldProductName, AuditingActionEnum actionEnum) { - List<String> tagsList = product.getTags(); - validateComponentTags(tagsList, oldProductName, ComponentTypeEnum.PRODUCT, user, product, actionEnum); - ValidationUtils.removeDuplicateFromList(tagsList); + componentTagsValidator.validateAndCorrectField(user, product, actionEnum); return Either.left(true); } @@ -587,7 +609,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(productId); if (storageStatus.isRight()) { - if (storageStatus.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + if (storageStatus.right().value() == StorageOperationStatus.NOT_FOUND) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.name().toLowerCase())); } return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), typeEnum), "")); @@ -608,10 +630,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { Product productToUpdate = validationRsponse.left().value(); // lock resource - Either<Boolean, ResponseFormat> lockResult = lockComponent(currentProduct.getUniqueId(), currentProduct, "Update Product Metadata"); - if (lockResult.isRight()) { - return Either.right(lockResult.right().value()); - } + lockComponent(currentProduct.getUniqueId(), currentProduct, "Update Product Metadata"); try { Either<Product, StorageOperationStatus> updateResponse = toscaOperationFacade.updateToscaElement(productToUpdate); if (updateResponse.isRight()) { @@ -704,9 +723,10 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { } updatedProductName = updatedProduct.getName(); if (!currentProductName.equals(updatedProductName)) { - Either<Boolean, ResponseFormat> productNameUniquenessValidation = validateComponentNameUnique(user, updatedProduct, null); - if (productNameUniquenessValidation.isRight()) { - return productNameUniquenessValidation; + try { + componentNameValidator.validateComponentNameUnique(user, updatedProduct, null); + } catch (ComponentException exp) { + return Either.right(exp.getResponseFormat()); } currentProduct.setName(updatedProductName); tags = updatedProductName; @@ -791,13 +811,8 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { return Either.left(new ArrayList<>()); } - @Override - protected boolean validateTagPattern(String tag) { - return ValidationUtils.validateCategoryDisplayNameFormat(tag); - } - public Either<Product, ResponseFormat> getProductByNameAndVersion(String productName, String productVersion, String userId) { - validateUserExists(userId, "get Service By Name And Version", false); + validateUserExists(userId); Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.PRODUCT, productName, productVersion); if (storageStatus.isRight()) { log.debug("failed to get service by name {} and version {}", productName, productVersion); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java index 1391e205cd..b271ea0137 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java @@ -22,13 +22,6 @@ package org.openecomp.sdc.be.components.impl; import com.google.gson.JsonElement; import fj.data.Either; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.function.Supplier; -import javax.servlet.ServletContext; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; @@ -72,6 +65,15 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.context.WebApplicationContext; +import javax.servlet.ServletContext; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Supplier; + + @org.springframework.stereotype.Component("propertyBusinessLogic") public class PropertyBusinessLogic extends BaseBusinessLogic { @@ -101,7 +103,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { return webApplicationContext.getBean(class1); } - public Either<Map<String, DataTypeDefinition>, ResponseFormat> getAllDataTypes() { + public Map<String, DataTypeDefinition> getAllDataTypes() { return getAllDataTypes(applicationDataTypeCache); } @@ -121,7 +123,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { String userId) { Either<EntryData<String, PropertyDefinition>, ResponseFormat> result = null; - validateUserExists(userId, "create Property", false); + validateUserExists(userId); Either<Component, StorageOperationStatus> serviceElement = toscaOperationFacade.getToscaElement(componentId); @@ -160,16 +162,10 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { } else { - Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); - if (allDataTypes.isRight()) { - result = Either.right(allDataTypes.right().value()); - return result; - } - - Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value(); + Map<String, DataTypeDefinition> allDataTypes = getAllDataTypes(applicationDataTypeCache); // validate property default values - Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newPropertyDefinition, dataTypes); + Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newPropertyDefinition, allDataTypes); if (defaultValuesValidation.isRight()) { result = Either.right(defaultValuesValidation.right().value()); return result; @@ -191,7 +187,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { String convertedValue = null; if (newPropertyDefinition.getDefaultValue() != null) { convertedValue = converter.convert( - newPropertyDefinition.getDefaultValue(), innerType, allDataTypes.left().value()); + newPropertyDefinition.getDefaultValue(), innerType, allDataTypes); newPropertyDefinition.setDefaultValue(convertedValue); } } @@ -208,16 +204,13 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { return result; } } - result = Either.left(new EntryData<>(propertyName, newPropertyDefinition)); return result; - } finally { commitOrRollback(result); // unlock component graphLockOperation.unlockComponent(componentId, nodeType); } - } /** @@ -300,7 +293,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { public Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> getComponentProperty(String componentId, String propertyId, String userId) { - validateUserExists(userId, "create Component Instance", false); + validateUserExists(userId); // Get the resource from DB Either<Component, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(componentId); @@ -324,7 +317,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { public Either<List<PropertyDefinition>, ResponseFormat> getPropertiesList(String componentId, String userId) { - validateUserExists(userId, "create Component Instance", false); + validateUserExists(userId); // Get the resource from DB ComponentParametersView filter = new ComponentParametersView(true); @@ -354,7 +347,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> result = null; - validateUserExists(userId, "delete Property", false); + validateUserExists(userId); // Get the resource from DB Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaElement(componentId); @@ -605,8 +598,8 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { } Optional<PropertyDefinition> propertyCandidate = - properties.stream().filter(property -> property.getName().equals(propertyName)) - .findAny(); + properties.stream().filter(property -> property.getName().equals(propertyName)) + .findAny(); return propertyCandidate.isPresent(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeBusinessLogic.java index 5ca6255db8..e231ed7ffe 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeBusinessLogic.java @@ -16,8 +16,6 @@ package org.openecomp.sdc.be.components.impl; -import java.util.Map; - import fj.data.Either; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -29,6 +27,8 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.Map; + @Component("relationshipTypeBusinessLogic") public class RelationshipTypeBusinessLogic { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeImportManager.java index a2da4cca2f..993d0136f6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeImportManager.java @@ -16,9 +16,6 @@ package org.openecomp.sdc.be.components.impl; -import java.util.List; -import java.util.Map; - import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum; @@ -32,6 +29,9 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.List; +import java.util.Map; + @Component("relationshipTypeImportManager") public class RelationshipTypeImportManager { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementBusinessLogic.java index 067b5db97c..f3aca5696a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementBusinessLogic.java @@ -19,6 +19,7 @@ package org.openecomp.sdc.be.components.impl; import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; +import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; import org.openecomp.sdc.be.components.validation.RequirementValidation; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -88,7 +89,7 @@ public class RequirementBusinessLogic extends BaseBusinessLogic { public Either<List<RequirementDefinition>, ResponseFormat> createRequirements( String componentId, List<RequirementDefinition> requirementDefinitions, User user, String errorContext, boolean lock) { - validateUserExists(user.getUserId(), errorContext, true); + validateUserExists(user.getUserId()); Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId); if (componentEither.isRight()) { @@ -160,7 +161,7 @@ public class RequirementBusinessLogic extends BaseBusinessLogic { public Either<List<RequirementDefinition>, ResponseFormat> updateRequirements( String componentId, List<RequirementDefinition> requirementDefinitions, User user, String errorContext, boolean lock) { - validateUserExists(user.getUserId(), errorContext, true); + validateUserExists(user.getUserId()); Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId); if (componentEither.isRight()) { @@ -327,7 +328,7 @@ public class RequirementBusinessLogic extends BaseBusinessLogic { public Either<RequirementDefinition, ResponseFormat> getRequirement(String componentId, String requirementIdToGet, User user, boolean lock) { - validateUserExists(user.getUserId(), GET_REQUIREMENTS, true); + validateUserExists(user.getUserId()); Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId); if (componentEither.isRight()) { return Either.right(componentEither.right().value()); @@ -369,7 +370,7 @@ public class RequirementBusinessLogic extends BaseBusinessLogic { public Either<RequirementDefinition, ResponseFormat> deleteRequirement(String componentId, String requirementIdToDelete, User user, boolean lock) { - validateUserExists(user.getUserId(), DELETE_REQUIREMENTS, true); + validateUserExists(user.getUserId()); Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId); if (componentEither.isRight()) { @@ -476,12 +477,13 @@ public class RequirementBusinessLogic extends BaseBusinessLogic { org.openecomp.sdc.be.model.Component component, String action) { if (lock) { - Either<Boolean, ResponseFormat> lockResult = lockComponent(component.getUniqueId(), component, action); - if (lockResult.isRight()) { + try{ + lockComponent(component.getUniqueId(), component, action); + } catch (ComponentException e){ LOGGER.debug(FAILED_TO_LOCK_COMPONENT_RESPONSE_IS, component.getName(), - lockResult.right().value().getFormattedMessage()); + e.getMessage()); janusGraphDao.rollback(); - return Either.right(lockResult.right().value()); + throw e; } } return Either.left(true); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java index bf848bf8f3..99f4dc6ddd 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java @@ -16,46 +16,19 @@ * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= - * Modifications copyright (c) 2019 Nokia - * ================================================================================ */ package org.openecomp.sdc.be.components.impl; -import static java.util.stream.Collectors.joining; -import static java.util.stream.Collectors.toList; -import static java.util.stream.Collectors.toMap; -import static java.util.stream.Collectors.toSet; -import static org.apache.commons.collections.CollectionUtils.isNotEmpty; -import static org.apache.commons.collections.MapUtils.isEmpty; -import static org.apache.commons.collections.MapUtils.isNotEmpty; -import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement; -import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue; -import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN; - +import com.google.common.annotations.VisibleForTesting; import fj.data.Either; -import java.util.ArrayList; -import java.util.Collection; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.function.Function; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import javax.servlet.ServletContext; import org.apache.commons.codec.binary.Base64; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.collections4.ListUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum; import org.openecomp.sdc.be.components.csar.CsarArtifactsAndGroupsBusinessLogic; import org.openecomp.sdc.be.components.csar.CsarBusinessLogic; import org.openecomp.sdc.be.components.csar.CsarInfo; @@ -70,8 +43,18 @@ import org.openecomp.sdc.be.components.impl.utils.CINodeFilterUtils; 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.merge.TopologyComparator; +import org.openecomp.sdc.be.components.merge.property.PropertyDataValueMergeBusinessLogic; import org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic; import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils; +import org.openecomp.sdc.be.components.property.PropertyConstraintsUtils; +import org.openecomp.sdc.be.components.validation.component.ComponentContactIdValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentDescriptionValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentIconValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentNameValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentProjectCodeValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentTagsValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentValidator; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -83,6 +66,7 @@ import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ToscaArtifactDataDefinition; @@ -152,7 +136,6 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo; import org.openecomp.sdc.be.tosca.CsarUtils; import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo; import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; -import org.openecomp.sdc.be.user.IUserBusinessLogic; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.be.utils.CommonBeUtils; import org.openecomp.sdc.be.utils.TypeUtils; @@ -161,37 +144,67 @@ import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.kpi.api.ASDCKpiApi; +import org.openecomp.sdc.common.log.elements.LoggerSupportability; import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions; +import org.openecomp.sdc.common.log.enums.StatusCode; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.GeneralUtility; import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.web.context.WebApplicationContext; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; +import javax.servlet.ServletContext; +import java.util.ArrayList; +import java.util.Collection; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import static java.util.stream.Collectors.joining; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toMap; +import static java.util.stream.Collectors.toSet; +import static org.apache.commons.collections.CollectionUtils.isNotEmpty; +import static org.apache.commons.collections.MapUtils.isEmpty; +import static org.apache.commons.collections.MapUtils.isNotEmpty; +import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement; +import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue; +import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN; +import static org.openecomp.sdc.common.api.Constants.DEFAULT_GROUP_VF_MODULE; + @org.springframework.stereotype.Component("resourceBusinessLogic") public class ResourceBusinessLogic extends ComponentBusinessLogic { - private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ResourceBusinessLogic.class); - - private static final String DELETE_RESOURCE = "Delete Resource"; - private static final String IN_RESOURCE = " in resource {} "; - private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes"; - public static final String INITIAL_VERSION = "0.1"; - private static final Logger log = Logger.getLogger(ResourceBusinessLogic.class); - private static final String CERTIFICATION_ON_IMPORT = "certification on import"; - private static final String CREATE_RESOURCE = "Create Resource"; - private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update"; - private static final String CATEGORY_IS_EMPTY = "Resource category is empty"; - private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate"; - private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name "; - private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {} in resource {} "; - - private ICapabilityTypeOperation capabilityTypeOperation; + private static final String DELETE_RESOURCE = "Delete Resource"; + private static final String IN_RESOURCE = " in resource {} "; + private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes"; + public static final String INITIAL_VERSION = "0.1"; + private static final Logger log = Logger.getLogger(ResourceBusinessLogic.class); + private static final String CERTIFICATION_ON_IMPORT = "certification on import"; + private static final String CREATE_RESOURCE = "Create Resource"; + private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update"; + private static final String CATEGORY_IS_EMPTY = "Resource category is empty"; + private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate"; + private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name "; + private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {} in resource {} "; + public LoggerSupportability loggerSupportability=LoggerSupportability.getLogger(ResourceBusinessLogic.class.getName()); + + private IInterfaceLifecycleOperation interfaceTypeOperation; private LifecycleBusinessLogic lifecycleBusinessLogic; @@ -205,7 +218,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { private final UiComponentDataConverter uiComponentDataConverter; private final CsarBusinessLogic csarBusinessLogic; private final PropertyBusinessLogic propertyBusinessLogic; - private final SoftwareInformationBusinessLogic softwareInformationBusinessLogic; @Autowired public ResourceBusinessLogic(IElementOperation elementDao, @@ -222,9 +234,16 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic, MergeInstanceUtils mergeInstanceUtils, UiComponentDataConverter uiComponentDataConverter, CsarBusinessLogic csarBusinessLogic, ArtifactsOperations artifactToscaOperation, PropertyBusinessLogic propertyBusinessLogic, - SoftwareInformationBusinessLogic softwareInformationBusinessLogic) { + ComponentContactIdValidator componentContactIdValidator, + ComponentNameValidator componentNameValidator, ComponentTagsValidator componentTagsValidator, + ComponentValidator componentValidator, + ComponentIconValidator componentIconValidator, + ComponentProjectCodeValidator componentProjectCodeValidator, + ComponentDescriptionValidator componentDescriptionValidator) { super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic, - interfaceOperation, interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation); + interfaceOperation, interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, + componentContactIdValidator, componentNameValidator, componentTagsValidator, componentValidator, + componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator); this.componentInstanceBusinessLogic = componentInstanceBusinessLogic; this.resourceImportManager = resourceImportManager; this.inputsBusinessLogic = inputsBusinessLogic; @@ -235,43 +254,75 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { this.uiComponentDataConverter = uiComponentDataConverter; this.csarBusinessLogic = csarBusinessLogic; this.propertyBusinessLogic = propertyBusinessLogic; - this.softwareInformationBusinessLogic = softwareInformationBusinessLogic; } - public LifecycleBusinessLogic getLifecycleBusinessLogic() { - return lifecycleBusinessLogic; - } + @Autowired + private ICapabilityTypeOperation capabilityTypeOperation; + + @Autowired + private TopologyComparator topologyComparator; + + @Autowired + private ComponentValidator componentValidator; + + @Autowired + private PropertyDataValueMergeBusinessLogic propertyDataValueMergeBusinessLogic; + + @Autowired + private SoftwareInformationBusinessLogic softwareInformationBusinessLogic; + + + public LifecycleBusinessLogic getLifecycleBusinessLogic() { + return lifecycleBusinessLogic; + } @Autowired public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) { this.lifecycleBusinessLogic = lifecycleBusinessLogic; } - public IElementOperation getElementDao() { - return elementDao; - } + @VisibleForTesting + protected void setComponentValidator(ComponentValidator componentValidator) { + this.componentValidator = componentValidator; + } - public IUserBusinessLogic getUserAdmin() { - return this.userAdmin; - } + public IElementOperation getElementDao() { + return elementDao; + } - @Autowired - public void setUserAdmin(UserBusinessLogic userAdmin) { - this.userAdmin = userAdmin; - } + public void setElementDao(IElementOperation elementDao) { + this.elementDao = elementDao; + } - public ComponentsUtils getComponentsUtils() { - return this.componentsUtils; - } + public UserBusinessLogic getUserAdmin() { + return this.userAdmin; + } - @Autowired - public void setComponentsUtils(ComponentsUtils componentsUtils) { - this.componentsUtils = componentsUtils; - } + @Autowired + public void setUserAdmin(UserBusinessLogic userAdmin) { + this.userAdmin = userAdmin; + } - public ApplicationDataTypeCache getApplicationDataTypeCache() { - return applicationDataTypeCache; - } + public ComponentsUtils getComponentsUtils() { + return this.componentsUtils; + } + + @Autowired + public void setComponentsUtils(ComponentsUtils componentsUtils) { + this.componentsUtils = componentsUtils; + } + + public ArtifactsBusinessLogic getArtifactsManager() { + return artifactsBusinessLogic; + } + + public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) { + this.artifactsBusinessLogic = artifactsManager; + } + + public ApplicationDataTypeCache getApplicationDataTypeCache() { + return applicationDataTypeCache; + } @Autowired public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) { @@ -283,1066 +334,1241 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { this.interfaceTypeOperation = interfaceTypeOperation; } - /** - * the method returns a list of all the resources that are certified, the - * returned resources are only abstract or only none abstract according to - * the given param - * - * @param getAbstract - * @param userId TODO - * @return - */ - public List<Resource> getAllCertifiedResources(boolean getAbstract, - HighestFilterEnum highestFilter, String userId) { - User user = validateUserExists(userId, "get All Certified Resources", false); - Boolean isHighest = null; - switch (highestFilter) { - case ALL: - break; - case HIGHEST_ONLY: - isHighest = true; - break; - case NON_HIGHEST_ONLY: - isHighest = false; - break; - default: - break; - } - Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade - .getAllCertifiedResources(getAbstract, isHighest); + /** + * the method returns a list of all the resources that are certified, the + * returned resources are only abstract or only none abstract according to + * the given param + * + * @param getAbstract + * @param userId + * TODO + * @return + */ + public List<Resource> getAllCertifiedResources(boolean getAbstract, HighestFilterEnum highestFilter, + String userId) { + User user = validateUserExists(userId); + Boolean isHighest = null; + switch (highestFilter) { + case ALL: + break; + case HIGHEST_ONLY: + isHighest = true; + break; + case NON_HIGHEST_ONLY: + isHighest = false; + break; + default: + break; + } + Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade + .getAllCertifiedResources(getAbstract, isHighest); - if (getResponse.isRight()) { - throw new StorageException(getResponse.right().value()); - } + if (getResponse.isRight()) { + throw new StorageException(getResponse.right() + .value()); + } - return getResponse.left().value(); - } + return getResponse.left() + .value(); + } - public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName, - ResourceTypeEnum resourceTypeEnum, String userId) { + public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName, + ResourceTypeEnum resourceTypeEnum, String userId) { - validateUserExists(userId, "validate Resource Name Exists", false); + validateUserExists(userId); - Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade - .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE); - // DE242223 + Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade + .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE); + // DE242223 janusGraphDao.commit(); - if (dataModelResponse.isLeft()) { - Map<String, Boolean> result = new HashMap<>(); - result.put("isValid", dataModelResponse.left().value()); - log.debug("validation was successfully performed."); - return Either.left(result); - } - - ResponseFormat responseFormat = componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value())); - - return Either.right(responseFormat); - } - - public Resource createResource(Resource resource, AuditingActionEnum auditingAction, - User user, Map<String, byte[]> csarUIPayload, String payloadName) { - validateResourceBeforeCreate(resource, user, false); - String csarUUID = payloadName == null ? resource.getCsarUUID() : payloadName; - if (StringUtils.isNotEmpty(csarUUID)) { - csarBusinessLogic.validateCsarBeforeCreate(resource, auditingAction, user, csarUUID); - log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID); - return createResourceFromCsar(resource, user, csarUIPayload, csarUUID); - } - - return createResourceByDao(resource, user, auditingAction, false, false); - } + if (dataModelResponse.isLeft()) { + Map<String, Boolean> result = new HashMap<>(); + result.put("isValid", dataModelResponse.left() + .value()); + log.debug("validation was successfully performed."); + return Either.left(result); + } - public Resource validateAndUpdateResourceFromCsar(Resource resource, User user, - Map<String, byte[]> csarUIPayload, String payloadName, String resourceUniqueId) { - String csarUUID = payloadName; - String csarVersion = null; - Resource updatedResource = null; - if (payloadName == null) { - csarUUID = resource.getCsarUUID(); - csarVersion = resource.getCsarVersion(); - } - if (csarUUID != null && !csarUUID.isEmpty()) { - Resource oldResource = getResourceByUniqueId(resourceUniqueId); - validateCsarUuidMatching(oldResource, resource, csarUUID, resourceUniqueId, user); - validateCsarIsNotAlreadyUsed(oldResource, resource, csarUUID, user); - if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) { - overrideImmutableMetadata(oldResource, resource); - } - validateResourceBeforeCreate(resource, user, false); - String oldCsarVersion = oldResource.getCsarVersion(); - log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID, - resourceUniqueId); - // (on boarding flow): If the update includes same csarUUID and - // same csarVersion as already in the VF - no need to import the - // csar (do only metadata changes if there are). - if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) { - updatedResource = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, - false); - } else { - updatedResource = updateResourceFromCsar(oldResource, resource, user, - AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, csarUIPayload, csarUUID); - } - } else { - log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID, - resource.getName()); - componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE); - throw new ByActionStatusComponentException(ActionStatus.MISSING_CSAR_UUID, resource.getName()); - } - return updatedResource; - } + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right() + .value())); - private void validateCsarIsNotAlreadyUsed(Resource oldResource, - Resource resource, String csarUUID, User user) { - // (on boarding flow): If the update includes a csarUUID: verify this - // csarUUID is not in use by another VF, If it is - use same error as - // above: - // "Error: The VSP with UUID %1 was already imported for VF %2. Please - // select another or update the existing VF." %1 - csarUUID, %2 - VF - // name - Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade - .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName()); - if (resourceLinkedToCsarRes.isRight()) { - if (!StorageOperationStatus.NOT_FOUND.equals(resourceLinkedToCsarRes.right().value())) { - log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID, - resource.getSystemName()); - throw new StorageException(resourceLinkedToCsarRes.right().value()); - } - } else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId()) - && !resourceLinkedToCsarRes.left().value().getName().equals(oldResource.getName())) { - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, - resourceLinkedToCsarRes.left().value().getName()); - componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA); - throw new ByActionStatusComponentException(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, - resourceLinkedToCsarRes.left().value().getName()); - } - } + return Either.right(responseFormat); + } - private void validateCsarUuidMatching(Resource resource, - Resource oldResource, String csarUUID, String resourceUniqueId, User user) { - // (on boarding flow): If the update includes csarUUID which is - // different from the csarUUID of the VF - fail with - // error: "Error: Resource %1 cannot be updated using since it is linked - // to a different VSP" %1 - VF name - String oldCsarUUID = oldResource.getCsarUUID(); - if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) { - log.debug( - "Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}", - resourceUniqueId, csarUUID, oldCsarUUID); - ResponseFormat errorResponse = componentsUtils.getResponseFormat( - ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID); - componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA); - throw new ByActionStatusComponentException(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID); - } - } + public Resource createResource(Resource resource, AuditingActionEnum auditingAction, User user, + Map<String, byte[]> csarUIPayload, String payloadName) { + validateResourceBeforeCreate(resource, user, false); + String csarUUID = payloadName == null ? resource.getCsarUUID() : payloadName; + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Starting to create resource from CSAR by user {} ", user.getUserId()); + if (StringUtils.isNotEmpty(csarUUID)) { + csarBusinessLogic.validateCsarBeforeCreate(resource, auditingAction, user, csarUUID); + log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID); + + Resource createResourceFromCsar = createResourceFromCsar(resource, user, csarUIPayload, csarUUID); + return updateCatalog(createResourceFromCsar, ChangeTypeEnum.LIFECYCLE).left() + .map(r -> (Resource) r) + .left() + .value(); + } - private Resource getResourceByUniqueId(String resourceUniqueId) { - Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade.getToscaFullElement(resourceUniqueId); - if (oldResourceRes.isRight()) { - log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId, - oldResourceRes.right().value()); - throw new StorageException(oldResourceRes.right().value()); - } - return oldResourceRes.left().value(); - } + final Resource createResourceByDao = createResourceByDao(resource, user, auditingAction, false, false); + return updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left() + .map(r -> (Resource) r) + .left() + .value(); + } - private void overrideImmutableMetadata(Resource oldRresource, Resource resource) { - resource.setName(oldRresource.getName()); - resource.setIcon(oldRresource.getIcon()); - resource.setTags(oldRresource.getTags()); - resource.setCategories(oldRresource.getCategories()); - resource.setDerivedFrom(oldRresource.getDerivedFrom()); - } + public Resource validateAndUpdateResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload, + String payloadName, String resourceUniqueId) { + String csarUUID = payloadName; + String csarVersion = null; + Resource updatedResource = null; + if (payloadName == null) { + csarUUID = resource.getCsarUUID(); + csarVersion = resource.getCsarVersion(); + } + if (csarUUID != null && !csarUUID.isEmpty()) { + Resource oldResource = getResourceByUniqueId(resourceUniqueId); + validateCsarUuidMatching(oldResource, resource, csarUUID, resourceUniqueId, user); + validateCsarIsNotAlreadyUsed(oldResource, resource, csarUUID, user); + if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) { + overrideImmutableMetadata(oldResource, resource); + } + validateResourceBeforeCreate(resource, user, false); + String oldCsarVersion = oldResource.getCsarVersion(); + log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID, + resourceUniqueId); + // (on boarding flow): If the update includes same csarUUID and + // same csarVersion as already in the VF - no need to import the + // csar (do only metadata changes if there are). + if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) { + updatedResource = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, false); + } else { + updatedResource = updateResourceFromCsar(oldResource, resource, user, + AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, csarUIPayload, csarUUID); + } + } else { + log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName()); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID, + resource.getName()); + componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE); + throw new ByActionStatusComponentException(ActionStatus.MISSING_CSAR_UUID, resource.getName()); + } + return updatedResource; + } - private Resource updateResourceFromCsar(Resource oldResource, Resource newResource, - User user, AuditingActionEnum updateResource, boolean inTransaction, - Map<String, byte[]> csarUIPayload, String csarUUID) { - Resource updatedResource = null; - validateLifecycleState(oldResource, user); - String lockedResourceId = oldResource.getUniqueId(); - List<ArtifactDefinition> createdArtifacts = new ArrayList<>(); - CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(newResource, oldResource, user, csarUIPayload, csarUUID); - Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldResource, - "update Resource From Csar"); - if (lockResult.isRight()) { - throw new ByResponseFormatComponentException(lockResult.right().value()); - } + private void validateCsarIsNotAlreadyUsed(Resource oldResource, Resource resource, String csarUUID, User user) { + // (on boarding flow): If the update includes a csarUUID: verify this + // csarUUID is not in use by another VF, If it is - use same error as + // above: + // "Error: The VSP with UUID %1 was already imported for VF %2. Please + // select another or update the existing VF." %1 - csarUUID, %2 - VF + // name + Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade + .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName()); + if (resourceLinkedToCsarRes.isRight()) { + if (StorageOperationStatus.NOT_FOUND != resourceLinkedToCsarRes.right().value()) { + log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID, + resource.getSystemName()); + throw new StorageException(resourceLinkedToCsarRes.right() + .value()); + } + } else if (!resourceLinkedToCsarRes.left() + .value() + .getUniqueId() + .equals(oldResource.getUniqueId()) + && !resourceLinkedToCsarRes.left() + .value() + .getName() + .equals(oldResource.getName())) { + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, + resourceLinkedToCsarRes.left() + .value() + .getName()); + componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA); + throw new ByActionStatusComponentException(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left() + .value() + .getName()); + } + } - Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo(); + private void validateCsarUuidMatching(Resource resource, Resource oldResource, String csarUUID, + String resourceUniqueId, User user) { + // (on boarding flow): If the update includes csarUUID which is + // different from the csarUUID of the VF - fail with + // error: "Error: Resource %1 cannot be updated using since it is linked + // to a different VSP" %1 - VF name + String oldCsarUUID = oldResource.getCsarUUID(); + if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) { + log.debug( + "Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}", + resourceUniqueId, csarUUID, oldCsarUUID); + ResponseFormat errorResponse = componentsUtils.getResponseFormat( + ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID); + componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA); + throw new ByActionStatusComponentException(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, + oldCsarUUID); + } + } - Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle( - nodeTypesInfo, csarInfo, oldResource); - if (findNodeTypesArtifactsToHandleRes.isRight()) { - log.debug("failed to find node types for update with artifacts during import csar {}. ", - csarInfo.getCsarUUID()); - throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value()); - } - Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes - .left().value(); - try { - updatedResource = updateResourceFromYaml(oldResource, newResource, updateResource, createdArtifacts, csarInfo.getMainTemplateName(), - csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false); + private Resource getResourceByUniqueId(String resourceUniqueId) { + Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade + .getToscaFullElement(resourceUniqueId); + if (oldResourceRes.isRight()) { + log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId, + oldResourceRes.right() + .value()); + throw new StorageException(oldResourceRes.right() + .value()); + } + return oldResourceRes.left() + .value(); + } - connectUiRelations(oldResource, updatedResource); + private void overrideImmutableMetadata(Resource oldResource, Resource resource) { + resource.setName(oldResource.getName()); + resource.setIcon(oldResource.getIcon()); + resource.setTags(oldResource.getTags()); + resource.setCategories(oldResource.getCategories()); + resource.setDerivedFrom(oldResource.getDerivedFrom()); + } - } catch (ComponentException|StorageException e){ - rollback(inTransaction, newResource, createdArtifacts, null); - throw e; + private Resource updateResourceFromCsar(Resource oldResource, Resource newResource, User user, + AuditingActionEnum updateResource, boolean inTransaction, Map<String, byte[]> csarUIPayload, + String csarUUID) { + Resource updatedResource = null; + validateLifecycleState(oldResource, user); + String lockedResourceId = oldResource.getUniqueId(); + List<ArtifactDefinition> createdArtifacts = new ArrayList<>(); + CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(newResource, oldResource, user, csarUIPayload, csarUUID); + lockComponent(lockedResourceId, oldResource, "update Resource From Csar"); + + Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo(); + + Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle( + nodeTypesInfo, csarInfo, oldResource); + if (findNodeTypesArtifactsToHandleRes.isRight()) { + log.debug("failed to find node types for update with artifacts during import csar {}. ", + csarInfo.getCsarUUID()); + throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right() + .value()); + } + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes + .left() + .value(); + try { + updatedResource = updateResourceFromYaml(oldResource, newResource, updateResource, createdArtifacts, + csarInfo.getMainTemplateName(), csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo, + nodeTypesArtifactsToHandle, null, false); + + } catch (ComponentException | StorageException e) { + rollback(inTransaction, newResource, createdArtifacts, null); + throw e; } finally { janusGraphDao.commit(); - log.debug("unlock resource {}", lockedResourceId); - graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource); - } - return updatedResource; - - } - - private void validateLifecycleState(Resource oldResource, User user) { - if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldResource.getLifecycleState()) && - !oldResource.getLastUpdaterUserId().equals(user.getUserId())) { - log.debug("#validateLifecycleState - Current user is not last updater, last updater userId: {}, current user userId: {}", - oldResource.getLastUpdaterUserId(), user.getUserId()); - throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION); - } - } - - private Either<Resource, ResponseFormat> connectUiRelations(Resource oldResource, Resource newResource) { - Either<Resource, ResponseFormat> result; - - List<RequirementCapabilityRelDef> updatedUiRelations = mergeInstanceUtils.updateUiRelationsInResource(oldResource, newResource); + log.debug("unlock resource {}", lockedResourceId); + graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource); + } + return updatedResource; - StorageOperationStatus status = toscaOperationFacade.associateResourceInstances(newResource.getUniqueId(), updatedUiRelations); - if (status == StorageOperationStatus.OK) { - newResource.getComponentInstancesRelations().addAll(updatedUiRelations); - result = Either.left(newResource); - } else { - result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), newResource)); - } + } - return result; - } + private void validateLifecycleState(Resource oldResource, User user) { + if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT == oldResource.getLifecycleState() + && !oldResource.getLastUpdaterUserId() + .equals(user.getUserId())) { + log.debug( + "#validateLifecycleState - Current user is not last updater, last updater userId: {}, current user userId: {}", + oldResource.getLastUpdaterUserId(), user.getUserId()); + throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION); + } + } - private Resource updateResourceFromYaml(Resource oldRresource, Resource newRresource, - AuditingActionEnum actionEnum, List<ArtifactDefinition> createdArtifacts, - String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo, - Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, - String nodeName, boolean isNested) { - boolean inTransaction = true; - boolean shouldLock = false; - Resource preparedResource = null; - ParsedToscaYamlInfo uploadComponentInstanceInfoMap = null; - try { - uploadComponentInstanceInfoMap = csarBusinessLogic.getParsedToscaYamlInfo(yamlFileContent, yamlFileName, nodeTypesInfo, csarInfo, nodeName); - Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances(); - if (MapUtils.isEmpty(instances) && newRresource.getResourceType() != ResourceTypeEnum.PNF) { + private Resource updateResourceFromYaml(Resource oldResource, Resource newResource, AuditingActionEnum actionEnum, + List<ArtifactDefinition> createdArtifacts, String yamlFileName, String yamlFileContent, CsarInfo csarInfo, + Map<String, NodeTypeInfo> nodeTypesInfo, + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, + String nodeName, boolean isNested) { + boolean inTransaction = true; + boolean shouldLock = false; + Resource preparedResource = null; + ParsedToscaYamlInfo uploadComponentInstanceInfoMap; + try { + uploadComponentInstanceInfoMap = csarBusinessLogic.getParsedToscaYamlInfo(yamlFileContent, yamlFileName, + nodeTypesInfo, csarInfo, nodeName); + Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances(); + if (MapUtils.isEmpty(instances) && newResource.getResourceType() != ResourceTypeEnum.PNF) { throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName); } - preparedResource = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(), - inTransaction, shouldLock, isNested).left; - log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent); - handleResourceGenericType(preparedResource); - handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, - shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName); - preparedResource = createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs()); - preparedResource = createResourceInstances(yamlFileName, preparedResource, instances, csarInfo.getCreatedNodes()); - preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances); - } catch (ByResponseFormatComponentException e) { - ResponseFormat responseFormat = e.getResponseFormat(); - log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum); - throw e; - } catch (ByActionStatusComponentException e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); - log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum); - throw e; - } catch (StorageException e){ - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus())); - log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum); - throw e; - } - Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic - .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(), - preparedResource.getSystemName()); - if (validateUpdateVfGroupNamesRes.isRight()) { + preparedResource = updateExistingResourceByImport(newResource, oldResource, csarInfo.getModifier(), + inTransaction, shouldLock, isNested).left; + log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent); + handleResourceGenericType(preparedResource); + handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle, + createdArtifacts, nodeTypesInfo, csarInfo, nodeName); + preparedResource = createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs()); + Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>(); + preparedResource = createResourceInstances(yamlFileName, preparedResource, oldResource, instances, csarInfo.getCreatedNodes(), existingNodeTypesByResourceNames); + preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, oldResource, instances, existingNodeTypesByResourceNames); + } catch (ComponentException e) { + ResponseFormat responseFormat = e.getResponseFormat() == null + ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat(); + log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName, + responseFormat); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), + preparedResource == null ? oldResource : preparedResource, actionEnum); + throw e; + } catch (StorageException e) { + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus())); + log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName, + responseFormat); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), + preparedResource == null ? oldResource : preparedResource, actionEnum); + throw e; + } + Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic + .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(), + preparedResource.getSystemName()); + if (validateUpdateVfGroupNamesRes.isRight()) { - throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right().value()); - } - // add groups to resource - Map<String, GroupDefinition> groups; + throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right() + .value()); + } + // add groups to newResource + Map<String, GroupDefinition> groups; + + if (!validateUpdateVfGroupNamesRes.left() + .value() + .isEmpty()) { + groups = validateUpdateVfGroupNamesRes.left() + .value(); + } else { + groups = uploadComponentInstanceInfoMap.getGroups(); + } + handleGroupsProperties(preparedResource, groups); + Either<Boolean, ActionStatus> isTopologyChanged = topologyComparator.isTopologyChanged(oldResource, preparedResource); + + preparedResource = updateGroupsOnResource(preparedResource, groups); + + NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, + nodeTypesArtifactsToHandle); + + Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE, + createdArtifacts, yamlFileName, csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, + inTransaction, shouldLock); + if (updateArtifactsEither.isRight()) { + log.debug("failed to update artifacts {}", updateArtifactsEither.right() + .value()); + throw new ByResponseFormatComponentException(updateArtifactsEither.right() + .value()); + } + preparedResource = getResourceWithGroups(updateArtifactsEither.left() + .value() + .getUniqueId()); - if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) { - groups = validateUpdateVfGroupNamesRes.left().value(); - } else { - groups = uploadComponentInstanceInfoMap.getGroups(); - } - handleGroupsProperties(preparedResource, groups); - preparedResource = updateGroupsOnResource(preparedResource, groups); - NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, - nodeTypesArtifactsToHandle); - - Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE, createdArtifacts, yamlFileName, - csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock); - if (updateArtifactsEither.isRight()) { - log.debug("failed to update artifacts {}", updateArtifactsEither.right().value()); - throw new ByResponseFormatComponentException(updateArtifactsEither.right().value()); - } - preparedResource = getResourceWithGroups(updateArtifactsEither.left().value().getUniqueId()); + updateGroupsName(oldResource, preparedResource, isTopologyChanged.left().value()); + updateResourceInstancesNames(oldResource, csarInfo, preparedResource, isTopologyChanged.left().value()); - ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldRresource, preparedResource); - if (mergingPropsAndInputsStatus != ActionStatus.OK) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus, - preparedResource); - throw new ByResponseFormatComponentException(responseFormat); - } - compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId()); - return preparedResource; - } + preparedResource = getResourceWithGroups(preparedResource.getUniqueId()); - private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts, - String yamlFileName, CsarInfo csarInfo, Resource preparedResource, - NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) { - - String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName(); - Resource resource = preparedResource; - - Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts - .getNodeTypesArtifactsToHandle(); - if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) { - if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) { - Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = - handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true); - if (handleNodeTypeArtifactsRes.isRight()) { - return Either.right(handleNodeTypeArtifactsRes.right().value()); - } - } - } else { - Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts, - artifactsBusinessLogic.new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction); - log.trace("************* Finished to add artifacts from yaml {}", yamlFileName); - if (createdCsarArtifactsEither.isRight()) { - return createdCsarArtifactsEither; + updateVolumeGroup(preparedResource); - } - resource = createdCsarArtifactsEither.left().value(); - } - return Either.left(resource); - } + ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldResource, preparedResource); + if (mergingPropsAndInputsStatus != ActionStatus.OK) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus, + preparedResource); + throw new ByResponseFormatComponentException(responseFormat); + } + compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier() + .getUserId()); + return preparedResource; + } - private Resource handleResourceGenericType(Resource resource) { - Resource genericResource = fetchAndSetDerivedFromGenericType(resource); - if (resource.shouldGenerateInputs()) { - generateAndAddInputsFromGenericTypeProperties(resource, genericResource); - } - return genericResource; - } + protected void updateVolumeGroup(Resource preparedResource) { + List<GroupDefinition> groups = preparedResource.safeGetGroups(); + for (GroupDefinition group : groups) { + Map<String, ArtifactDefinition> createdNewArtifacts = preparedResource.getDeploymentArtifacts(); + if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) { + List<PropertyDataDefinition> volumePropList = group.getProperties().stream().filter(p -> "volume_group".equals(p.getName())).collect(Collectors.toList()); + if (!volumePropList.isEmpty()) { + PropertyDataDefinition volumeProp = volumePropList.get(0); + if (volumeProp != null) { + boolean isVolumeGroup = isVolumeGroup(group.getArtifacts(), new ArrayList<>(createdNewArtifacts.values())); + + if (!volumePropList.get(0).getValue().equals(String.valueOf(isVolumeGroup))) { + volumeProp.setValue(String.valueOf(isVolumeGroup)); + volumeProp.setDefaultValue(String.valueOf(isVolumeGroup)); + } + } + } + } + } + } - private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle( - Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Resource oldResource) { + private void updateGroupsName(Resource oldResource, Resource preparedResource, boolean isTopologyChanged) { + if (CollectionUtils.isNotEmpty(oldResource.getGroups()) + && CollectionUtils.isNotEmpty(preparedResource.getGroups())) { + Map<String, String> oldGroups = oldResource.getGroups() + .stream() + .collect(toMap(GroupDataDefinition::getInvariantName, GroupDataDefinition::getName)); + + List<GroupDefinition> updatedGroups = preparedResource.getGroups() + .stream() + .filter(group -> oldGroups.containsKey(group.getInvariantName()) && !group.getName() + .equals(oldGroups.get(group.getInvariantName()))) + .collect(toList()); + + if (CollectionUtils.isNotEmpty(updatedGroups)) { + if (isTopologyChanged) { + updatedGroups.stream().filter(group -> !group.isVspOriginated()) + .forEach(group -> group.setName(oldGroups.get(group.getInvariantName()))); + } else { + updatedGroups.forEach(group -> group.setName(oldGroups.get(group.getInvariantName()))); + } + groupBusinessLogic.updateGroups(preparedResource, updatedGroups, false); + } + } + } - Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>(); - Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes - = Either.left(nodeTypesArtifactsToHandle); + private void updateResourceInstancesNames(Resource oldResource, CsarInfo csarInfo, Resource preparedResource, boolean isTopologyChanged) { + if(CollectionUtils.isNotEmpty(oldResource.getComponentInstances())){ + Map<String, String> oldInstances = oldResource.getComponentInstances() + .stream() + .collect(toMap(ComponentInstance::getInvariantName, ComponentInstance::getName)); + List<ComponentInstance> updatedInstances = preparedResource.getComponentInstances() + .stream() + .filter(i -> oldInstances.containsKey(i.getInvariantName()) && !i.getName() + .equals(oldInstances.get(i.getInvariantName()))) + .collect(toList()); + if (CollectionUtils.isNotEmpty(updatedInstances)) { + if(isTopologyChanged) { + updatedInstances.stream().filter(i -> !i.isCreatedFromCsar()) + .forEach(i -> i.setName(oldInstances.get(i.getInvariantName()))); + } + else{ + updatedInstances.forEach(i -> i.setName(oldInstances.get(i.getInvariantName()))); + } + } - try { - Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar()); - Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = - extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo); - log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", - oldResource.getName(), csarInfo.getCsarUUID()); - extractedVfcToscaNames.forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource, - extractedVfcsArtifacts, - namespace, vfcToscaNames)); - } catch (Exception e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - nodeTypesArtifactsToHandleRes = Either.right(responseFormat); - log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e); - } - return nodeTypesArtifactsToHandleRes; - } + } + componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME, + null, preparedResource.getUniqueId(), csarInfo.getModifier() + .getUserId(), + preparedResource.getComponentInstances(), false); + } - private void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, - Resource resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace, ImmutablePair<String, String> vfcToscaNames){ + private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation, + List<ArtifactDefinition> createdArtifacts, String yamlFileName, CsarInfo csarInfo, + Resource preparedResource, NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, + boolean inTransaction, boolean shouldLock) { + + String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName(); + Resource resource = preparedResource; + + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts + .getNodeTypesArtifactsToHandle(); + if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) { + if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null + && !nodeTypesArtifactsToHandle.get(nodeName) + .isEmpty()) { + Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = handleNodeTypeArtifacts( + preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, + csarInfo.getModifier(), inTransaction, true); + if (handleNodeTypeArtifactsRes.isRight()) { + return Either.right(handleNodeTypeArtifactsRes.right() + .value()); + } + } + } else { + Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, + csarInfo, createdArtifacts, + artifactsBusinessLogic.new ArtifactOperationInfo(false, false, operation), shouldLock, + inTransaction); + log.trace("************* Finished to add artifacts from yaml {}", yamlFileName); + if (createdCsarArtifactsEither.isRight()) { + return createdCsarArtifactsEither; - EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null; - log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft()); - Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), null); - if (!isEmpty(extractedVfcsArtifacts)) { - List<ArtifactDefinition> currArtifacts = new ArrayList<>(); - if (extractedVfcsArtifacts.containsKey(namespace)) { - handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace)); - } - curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts); - } else if (curNodeType != null) { - // delete all artifacts if have not received artifacts from - // csar - curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); - List<ArtifactDefinition> artifactsToDelete = new ArrayList<>(); - // delete all informational artifacts - artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream() - .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL) - .collect(toList())); - // delete all deployment artifacts - artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values()); - if (!artifactsToDelete.isEmpty()) { - curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete); - } - } - if (isNotEmpty(curNodeTypeArtifactsToHandle)) { - nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle); - } - } + } + resource = createdCsarArtifactsEither.left() + .value(); + } + return Either.left(resource); + } - private Resource findVfcResource(CsarInfo csarInfo, Resource resource, String currVfcToscaName, String previousVfcToscaName, StorageOperationStatus status) { - if (status != null && status != StorageOperationStatus.NOT_FOUND) { - log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, status); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID()); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.CREATE_RESOURCE); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID()); - } else if (StringUtils.isNotEmpty(currVfcToscaName)) { - return (Resource)toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName) - .left() - .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st)); - } - return null; - } + private Resource handleResourceGenericType(Resource resource) { + Resource genericResource = fetchAndSetDerivedFromGenericType(resource); + if (resource.shouldGenerateInputs()) { + generateAndAddInputsFromGenericTypeProperties(resource, genericResource); + } + return genericResource; + } - private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle( - Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) { + private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle( + Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Resource oldResource) { + + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>(); + Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes = Either + .left(nodeTypesArtifactsToHandle); + + try { + Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils + .extractVfcsArtifactsFromCsar(csarInfo.getCsar()); + Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, + oldResource.getName(), csarInfo); + log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", + oldResource.getName(), csarInfo.getCsarUUID()); + extractedVfcToscaNames.forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, + nodeTypesArtifactsToHandle, oldResource, extractedVfcsArtifacts, namespace, vfcToscaNames)); + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + nodeTypesArtifactsToHandleRes = Either.right(responseFormat); + log.debug("Exception occurred when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e); + } + return nodeTypesArtifactsToHandleRes; + } - EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null; - try { - List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts); - List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>(); - List<ArtifactDefinition> artifactsToDelete = new ArrayList<>(); - processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, artifactsToDelete, - collectExistingArtifacts(curNodeType)); - nodeTypeArtifactsToHandle = putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete); - } catch (Exception e) { - log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e); - throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); - } - return nodeTypeArtifactsToHandle; - } + private void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo, + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, + Resource resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace, + ImmutablePair<String, String> vfcToscaNames) { + + EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null; + log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft()); + Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), + null); + if (!isEmpty(extractedVfcsArtifacts)) { + List<ArtifactDefinition> currArtifacts = new ArrayList<>(); + if (extractedVfcsArtifacts.containsKey(namespace)) { + handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace)); + } + curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts); + } else if (curNodeType != null) { + // delete all artifacts if have not received artifacts from + // csar + curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); + List<ArtifactDefinition> artifactsToDelete = new ArrayList<>(); + // delete all informational artifacts + artifactsToDelete.addAll(curNodeType.getArtifacts() + .values() + .stream() + .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL) + .collect(toList())); + // delete all deployment artifacts + artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts() + .values()); + if (!artifactsToDelete.isEmpty()) { + curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete); + } + } + if (isNotEmpty(curNodeTypeArtifactsToHandle)) { + nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle); + } + } - private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete) { - EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null; - if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) { - nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); - if (!artifactsToUpload.isEmpty()) { - nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload); - } - if (!artifactsToUpdate.isEmpty()) { - nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate); - } - if (!artifactsToDelete.isEmpty()) { - nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete); - } - } - return nodeTypeArtifactsToHandle; - } + private Resource findVfcResource(CsarInfo csarInfo, Resource resource, String currVfcToscaName, + String previousVfcToscaName, StorageOperationStatus status) { + if (status != null && status != StorageOperationStatus.NOT_FOUND) { + log.debug("Error occurred during fetching node type with tosca name {}, error: {}", currVfcToscaName, + status); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID()); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, + AuditingActionEnum.CREATE_RESOURCE); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID()); + } else if (StringUtils.isNotEmpty(currVfcToscaName)) { + return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName) + .left() + .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st)); + } + return null; + } - private void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts, List<ArtifactDefinition> artifactsToUpload, - List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete, - Map<String, ArtifactDefinition> existingArtifacts) { - if (!existingArtifacts.isEmpty()) { - extractedArtifacts.stream().forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a)); - artifactsToDelete.addAll(existingArtifacts.values()); - } - } + private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(Resource curNodeType, + List<ArtifactDefinition> extractedArtifacts) { + + EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null; + try { + List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts); + List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>(); + List<ArtifactDefinition> artifactsToDelete = new ArrayList<>(); + processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, + artifactsToDelete, collectExistingArtifacts(curNodeType)); + nodeTypeArtifactsToHandle = putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete); + } catch (Exception e) { + log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e); + throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); + } + return nodeTypeArtifactsToHandle; + } - private void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, Map<String, ArtifactDefinition> existingArtifacts, ArtifactDefinition currNewArtifact) { - Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values() - .stream() - .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())) - .findFirst(); - if (foundArtifact.isPresent()) { - if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) { - updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get()); - existingArtifacts.remove(foundArtifact.get().getArtifactLabel()); - artifactsToUpload.remove(currNewArtifact); - } else { - log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName()); - throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, - currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), - foundArtifact.get().getArtifactType()); - } - } - } + private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts( + List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, + List<ArtifactDefinition> artifactsToDelete) { + EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null; + if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) { + nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); + if (!artifactsToUpload.isEmpty()) { + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload); + } + if (!artifactsToUpdate.isEmpty()) { + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate); + } + if (!artifactsToDelete.isEmpty()) { + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete); + } + } + return nodeTypeArtifactsToHandle; + } - private void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact, ArtifactDefinition foundArtifact) { - if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) { - foundArtifact.setPayload(currNewArtifact.getPayloadData()); - foundArtifact.setPayloadData( - Base64.encodeBase64String(currNewArtifact.getPayloadData())); - foundArtifact.setArtifactChecksum(GeneralUtility - .calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData())); - artifactsToUpdate.add(foundArtifact); - } - } + private void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts, + List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, + List<ArtifactDefinition> artifactsToDelete, Map<String, ArtifactDefinition> existingArtifacts) { + if (!existingArtifacts.isEmpty()) { + extractedArtifacts.stream() + .forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a)); + artifactsToDelete.addAll(existingArtifacts.values()); + } + } - private Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) { - Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>(); - if (curNodeType == null) { - return existingArtifacts; - } - if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) { - existingArtifacts.putAll(curNodeType.getDeploymentArtifacts()); - } - if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) { - existingArtifacts - .putAll(curNodeType.getArtifacts().entrySet() - .stream() - .filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL) - .collect(toMap(Map.Entry::getKey, Map.Entry::getValue))); - } - return existingArtifacts; - } + private void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload, + List<ArtifactDefinition> artifactsToUpdate, Map<String, ArtifactDefinition> existingArtifacts, + ArtifactDefinition currNewArtifact) { + Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values() + .stream() + .filter(a -> a.getArtifactName() + .equals(currNewArtifact.getArtifactName())) + .findFirst(); + if (foundArtifact.isPresent()) { + if (foundArtifact.get() + .getArtifactType() + .equals(currNewArtifact.getArtifactType())) { + updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get()); + existingArtifacts.remove(foundArtifact.get() + .getArtifactLabel()); + artifactsToUpload.remove(currNewArtifact); + } else { + log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName()); + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, + currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), foundArtifact.get() + .getArtifactType()); + } + } + } - /** - * Changes resource life cycle state to checked out - * - * @param resource - * @param user - * @param inTransaction - * @return - */ - private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) { - Either<Resource, ResponseFormat> checkoutResourceRes; - try { - if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState() - .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - log.debug( - "************* Going to change life cycle state of resource {} to not certified checked out. ", - resource.getName()); - Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState( - resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, - new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT, - LifecycleChanceActionEnum.CREATE_FROM_CSAR), - inTransaction, true); - if (checkoutRes.isRight()) { - log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", - resource.getComponentType().getNodeType(), resource.getUniqueId(), - checkoutRes.right().value().getStatus()); - checkoutResourceRes = Either.right(checkoutRes.right().value()); - } else { - checkoutResourceRes = Either.left((Resource) checkoutRes.left().value()); - } - } else { - checkoutResourceRes = Either.left(resource); - } - } catch (Exception e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - checkoutResourceRes = Either.right(responseFormat); - log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), - e); - } - return checkoutResourceRes; - } + private void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact, + ArtifactDefinition foundArtifact) { + if (!foundArtifact.getArtifactChecksum() + .equals(currNewArtifact.getArtifactChecksum())) { + foundArtifact.setPayload(currNewArtifact.getPayloadData()); + foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData())); + foundArtifact.setArtifactChecksum( + GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData())); + artifactsToUpdate.add(foundArtifact); + } + } - /** - * Handles Artifacts of NodeType - * - * @param nodeTypeResource - * @param nodeTypeArtifactsToHandle - * @param user - * @param inTransaction - * @return - */ - public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource, - Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, - List<ArtifactDefinition> createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) { - Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRequestRes; - Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null; - Either<Resource, ResponseFormat> changeStateResponse; - try { - changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction); - if (changeStateResponse.isRight()) { - return Either.right(changeStateResponse.right().value()); - } - nodeTypeResource = changeStateResponse.left().value(); - - List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>(); - log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName()); - for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle - .entrySet()) { - ArtifactOperationEnum curOperation = curOperationEntry.getKey(); - List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue(); - if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) { - log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), - nodeTypeResource.getName()); - handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic - .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, - createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false, - ignoreLifecycleState, curOperation), - false, inTransaction); - if (handleNodeTypeArtifactsRequestRes.isRight()) { - handleNodeTypeArtifactsRes = Either.right(handleNodeTypeArtifactsRequestRes.right().value()); - break; - } - if (ArtifactOperationEnum.isCreateOrLink(curOperation)) { - createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value()); - } - handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value()); - } - } - if (handleNodeTypeArtifactsRes == null) { - handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts); - } - } catch (Exception e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleNodeTypeArtifactsRes = Either.right(responseFormat); - log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e); - } - return handleNodeTypeArtifactsRes; - } + private Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) { + Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>(); + if (curNodeType == null) { + return existingArtifacts; + } + if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) { + existingArtifacts.putAll(curNodeType.getDeploymentArtifacts()); + } + if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) { + existingArtifacts.putAll(curNodeType.getArtifacts() + .entrySet() + .stream() + .filter(e -> e.getValue() + .getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL) + .collect(toMap(Map.Entry::getKey, Map.Entry::getValue))); + } + return existingArtifacts; + } - private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo, - String vfResourceName, CsarInfo csarInfo) { - Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>(); - - Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo); - if (!nodes.isEmpty()) { - Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator(); - while (nodesNameEntry.hasNext()) { - Entry<String, Object> nodeType = nodesNameEntry.next(); - ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName( - ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey()); - vfcToscaNames.put(nodeType.getKey(), toscaResourceName); - } - } - for (NodeTypeInfo cvfc : nodeTypesInfo.values()) { - vfcToscaNames.put(cvfc.getType(), - buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), vfResourceName, cvfc.getType())); - } - return vfcToscaNames; - } + /** + * Changes resource life cycle state to checked out + * + * @param resource + * @param user + * @param inTransaction + * @return + */ + private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) { + Either<Resource, ResponseFormat> checkoutResourceRes; + try { + if (!resource.getComponentMetadataDefinition() + .getMetadataDataDefinition() + .getState() + .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + log.debug( + "************* Going to change life cycle state of resource {} to not certified checked out. ", + resource.getName()); + Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState( + resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, + new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT, + LifecycleChanceActionEnum.CREATE_FROM_CSAR), + inTransaction, true); + if (checkoutRes.isRight()) { + log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", + resource.getComponentType() + .getNodeType(), + resource.getUniqueId(), checkoutRes.right() + .value() + .getStatus()); + checkoutResourceRes = Either.right(checkoutRes.right() + .value()); + } else { + checkoutResourceRes = Either.left((Resource) checkoutRes.left() + .value()); + } + } else { + checkoutResourceRes = Either.left(resource); + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + checkoutResourceRes = Either.right(responseFormat); + log.debug("Exception occurred when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), + e); + } + return checkoutResourceRes; + } - private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) { - Map<String, Object> nodes = new HashMap<>(); - for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) { - extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate()); - } - extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate()); - return nodes; - } + /** + * Handles Artifacts of NodeType + * + * @param nodeTypeResource + * @param nodeTypeArtifactsToHandle + * @param user + * @param inTransaction + * @return + */ + public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource, + Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, + List<ArtifactDefinition> createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) { + List<ArtifactDefinition> handleNodeTypeArtifactsRequestRes; + Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null; + Either<Resource, ResponseFormat> changeStateResponse; + try { + changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction); + if (changeStateResponse.isRight()) { + return Either.right(changeStateResponse.right() + .value()); + } + nodeTypeResource = changeStateResponse.left() + .value(); + + List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>(); + log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName()); + for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle + .entrySet()) { + ArtifactOperationEnum curOperation = curOperationEntry.getKey(); + List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue(); + if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) { + log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), + nodeTypeResource.getName()); + handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic + .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, + createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false, + ignoreLifecycleState, curOperation), + false, inTransaction); + if (ArtifactOperationEnum.isCreateOrLink(curOperation)) { + createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes); + } + handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes); + } + } + if (handleNodeTypeArtifactsRes == null) { + handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts); + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleNodeTypeArtifactsRes = Either.right(responseFormat); + log.debug("Exception occurred when handleVfcArtifacts, error is:{}", e.getMessage(), e); + } + return handleNodeTypeArtifactsRes; + } - private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) { - Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils - .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES); - if (eitherNodeTypes.isLeft()) { - nodes.putAll(eitherNodeTypes.left().value()); - } - } + private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo, + String vfResourceName, CsarInfo csarInfo) { + Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>(); + + Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo); + if (!nodes.isEmpty()) { + Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet() + .iterator(); + while (nodesNameEntry.hasNext()) { + Entry<String, Object> nodeType = nodesNameEntry.next(); + ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName( + ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey()); + vfcToscaNames.put(nodeType.getKey(), toscaResourceName); + } + } + for (NodeTypeInfo cvfc : nodeTypesInfo.values()) { + vfcToscaNames.put(cvfc.getType(), + buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), vfResourceName, cvfc.getType())); + } + return vfcToscaNames; + } - public Resource createResourceFromCsar(Resource resource, User user, - Map<String, byte[]> csarUIPayload, String csarUUID) { - log.trace("************* created successfully from YAML, resource TOSCA "); + private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) { + Map<String, Object> nodes = new HashMap<>(); + for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) { + extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate()); + } + extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate()); + return nodes; + } - CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID); + private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) { + Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils + .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES); + if (eitherNodeTypes.isLeft()) { + nodes.putAll(eitherNodeTypes.left() + .value()); + } + } - Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo(); - Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle( - nodeTypesInfo, csarInfo, resource); - if (findNodeTypesArtifactsToHandleRes.isRight()) { - log.debug("failed to find node types for update with artifacts during import csar {}. ", - csarInfo.getCsarUUID()); - throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value()); - } - Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(), - nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false, - null); - log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}", - vfResource.getToscaResourceName()); - return vfResource; - } + public Resource createResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload, + String csarUUID) { + log.trace("************* created successfully from YAML, resource TOSCA "); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,StatusCode.STARTED,"Starting to create Resource From Csar by user {}", user.getUserId() ); + CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID); + Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo(); + Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle( + nodeTypesInfo, csarInfo, resource); + if (findNodeTypesArtifactsToHandleRes.isRight()) { + log.debug("failed to find node types for update with artifacts during import csar {}. ", + csarInfo.getCsarUUID()); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(), + StatusCode.ERROR,"error: {}",findNodeTypesArtifactsToHandleRes.right().value()); + throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value()); + } + Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(), + csarInfo.getMainTemplateName(), nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left() + .value(), + true, false, null); + log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}", + vfResource.getToscaResourceName()); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,StatusCode.COMPLETE,"Ended create Resource From Csar by user {}", user.getUserId() ); + return vfResource; + } - private Resource validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) { - log.trace("validating resource before create"); - user.copyData(validateUser(user, CREATE_RESOURCE, resource, AuditingActionEnum.CREATE_RESOURCE, false)); - // validate user role - validateUserRole(user, resource, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null); - // VF / PNF "derivedFrom" should be null (or ignored) - if (ModelConverter.isAtomicComponent(resource)) { - validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE); - } - return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null); + private Resource validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) { + log.trace("validating resource before create"); + user.copyData(validateUser(user, CREATE_RESOURCE, resource, AuditingActionEnum.CREATE_RESOURCE, false)); + // validate user role + validateUserRole(user, resource, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null); + // VF / PNF "derivedFrom" should be null (or ignored) + if (ModelConverter.isAtomicComponent(resource)) { + validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE); + } + return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null); - } + } - // resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo, - // nodeTypesArtifactsToCreate, true, false, null - private Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, - String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, - Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate, - boolean shouldLock, boolean inTransaction, String nodeName) { + // resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo, + // nodeTypesArtifactsToCreate, true, false, null + private Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName, + Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate, + boolean shouldLock, boolean inTransaction, String nodeName) { - List<ArtifactDefinition> createdArtifacts = new ArrayList<>(); - Resource createdResource; - try{ + List<ArtifactDefinition> createdArtifacts = new ArrayList<>(); + Resource createdResource; + try { ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName); if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances()) && resource.getResourceType() != ResourceTypeEnum.PNF) { throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); } - log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName()); - createdResource = createResourceAndRIsFromYaml(yamlName, resource, - parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml, - nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName); - log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName()); - } catch (ByActionStatusComponentException e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); - throw e; - } catch (ByResponseFormatComponentException e) { - ResponseFormat responseFormat = e.getResponseFormat(); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); - throw e; - } catch (StorageException e){ - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus())); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); - throw e; - } - return createdResource; - - } + log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName()); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(), + StatusCode.STARTED,""); + createdResource = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo, + AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml, nodeTypesInfo, + csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName); + log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName()); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(), + StatusCode.COMPLETE,"The resource has been created: {}",resource.getName()); + } catch (ComponentException e) { + ResponseFormat responseFormat = e.getResponseFormat() == null + ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat(); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, + AuditingActionEnum.IMPORT_RESOURCE); + throw e; + } catch (StorageException e) { + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus())); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, + AuditingActionEnum.IMPORT_RESOURCE); + throw e; + } + return createdResource; - public Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map<String, Object> mappedToscaTemplate, boolean needLock, - Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, - List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, - CsarInfo csarInfo) { + } - Either<String, ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate, - TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION); - if (toscaVersion.isRight()) { - throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE); - } - Map<String, Object> mapToConvert = new HashMap<>(); - mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value()); - Map<String, Object> nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate); - createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, mapToConvert, nodeTypes); - return csarInfo.getCreatedNodes(); - } + public Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, + Map<String, Object> mappedToscaTemplate, boolean needLock, + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, + List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, + CsarInfo csarInfo) { - private Map<String,Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) { - return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES) - .left().orValue(HashMap::new); - } + Either<String, ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate, + TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION); + if (toscaVersion.isRight()) { + throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE); + } + Map<String, Object> mapToConvert = new HashMap<>(); + mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left() + .value()); + Map<String, Object> nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate); + createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, + nodeTypesInfo, csarInfo, mapToConvert, nodeTypes); + return csarInfo.getCreatedNodes(); + } - private void createNodeTypes(String yamlName, Resource resource, boolean needLock, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) { - Iterator<Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet().iterator(); - Resource vfcCreated = null; - while (nodesNameValueIter.hasNext()) { - Entry<String, Object> nodeType = nodesNameValueIter.next(); - Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null - || nodeTypesArtifactsToHandle.isEmpty() ? null - : nodeTypesArtifactsToHandle.get(nodeType.getKey()); - - if (nodeTypesInfo.containsKey(nodeType.getKey())) { - log.trace("************* Going to handle nested vfc {}", nodeType.getKey()); - vfcCreated = handleNestedVfc(resource, - nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, - nodeType.getKey()); - log.trace("************* Finished to handle nested vfc {}", nodeType.getKey()); - } else if (csarInfo.getCreatedNodesToscaResourceNames() != null - && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) { - log.trace("************* Going to create node {}", nodeType.getKey()); - ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, - resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, - csarInfo, true); - log.debug("************* Finished to create node {}", nodeType.getKey()); - - vfcCreated = resourceCreated.getLeft(); - csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(), - vfcCreated.getToscaResourceName()); - } - if (vfcCreated != null) { - csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated); - } - mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName()); - } - } + private Map<String, Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) { + return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES) + .left() + .orValue(HashMap::new); + } - private Resource handleNestedVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle, - List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, - String nodeName) { + private void createNodeTypes(String yamlName, Resource resource, boolean needLock, + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, + List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, + CsarInfo csarInfo, Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) { + Iterator<Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet() + .iterator(); + Resource vfcCreated = null; + while (nodesNameValueIter.hasNext()) { + Entry<String, Object> nodeType = nodesNameValueIter.next(); + Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null + || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey()); + + if (nodeTypesInfo.containsKey(nodeType.getKey())) { + log.trace("************* Going to handle nested vfc {}", nodeType.getKey()); + vfcCreated = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, + nodeTypesInfo, csarInfo, nodeType.getKey()); + log.trace("************* Finished to handle nested vfc {}", nodeType.getKey()); + } else if (csarInfo.getCreatedNodesToscaResourceNames() != null + && !csarInfo.getCreatedNodesToscaResourceNames() + .containsKey(nodeType.getKey())) { + log.trace("************* Going to create node {}", nodeType.getKey()); + ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName, + nodeType, csarInfo.getModifier(), mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, + nodeTypesNewCreatedArtifacts, true, csarInfo, true); + log.debug("************* Finished to create node {}", nodeType.getKey()); + + vfcCreated = resourceCreated.getLeft(); + csarInfo.getCreatedNodesToscaResourceNames() + .put(nodeType.getKey(), vfcCreated.getToscaResourceName()); + } + if (vfcCreated != null) { + csarInfo.getCreatedNodes() + .put(nodeType.getKey(), vfcCreated); + } + mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName()); + } + } - String yamlName = nodesInfo.get(nodeName).getTemplateFileName(); - Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate(); + private Resource handleNestedVfc(Resource resource, + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle, + List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, + String nodeName) { + + String yamlName = nodesInfo.get(nodeName) + .getTemplateFileName(); + Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName) + .getMappedToscaTemplate(); + + log.debug("************* Going to create node types from yaml {}", yamlName); + createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle, + createdArtifacts, nodesInfo, csarInfo); + log.debug("************* Finished to create node types from yaml {}", yamlName); + + if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) { + log.debug("************* Going to handle complex VFC from yaml {}", yamlName); + resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, + nodeName, yamlName); + } + return resource; + } - log.debug("************* Going to create node types from yaml {}", yamlName); - createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, - nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo); - log.debug("************* Finished to create node types from yaml {}", yamlName); + private Resource handleComplexVfc(Resource resource, + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle, + List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, + String nodeName, String yamlName) { + + Resource oldComplexVfc = null; + Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo); + Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade + .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName()); + if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right() + .value() == StorageOperationStatus.NOT_FOUND) { + oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName( + buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName) + .getRight()); + } + if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right() + .value() != StorageOperationStatus.NOT_FOUND) { + log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", + newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right() + .value()); + throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); + } else if (oldComplexVfcRes.isLeft()) { + log.debug(VALIDATE_DERIVED_BEFORE_UPDATE); + Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate( + oldComplexVfcRes.left() + .value(), + newComplexVfc, ValidationUtils.hasBeenCertified(oldComplexVfcRes.left() + .value() + .getVersion())); + if (eitherValidation.isLeft()) { + oldComplexVfc = oldComplexVfcRes.left() + .value(); + } + } + newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, + yamlName, oldComplexVfc, newComplexVfc); + csarInfo.getCreatedNodesToscaResourceNames() + .put(nodeName, newComplexVfc.getToscaResourceName()); + LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT, + LifecycleChanceActionEnum.CREATE_FROM_CSAR); + log.debug("Going to certify cvfc {}. ", newComplexVfc.getName()); + Resource result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, + lifecycleChangeInfo, true, false, true); + csarInfo.getCreatedNodes() + .put(nodeName, result); + csarInfo.removeNodeFromQueue(); + return result; + } - if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) { - log.debug("************* Going to handle complex VFC from yaml {}", yamlName); - resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, - csarInfo, nodeName, yamlName); - } - return resource; - } + private Resource handleComplexVfc( + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle, + List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, + String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) { + + Resource handleComplexVfcRes; + Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName) + .getMappedToscaTemplate(); + String yamlContent = new String(csarInfo.getCsar() + .get(yamlName)); + Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet() + .stream() + .collect(toMap(Entry::getKey, e -> e.getValue() + .getUnmarkedCopy())); + CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo); + if (oldComplexVfc == null) { + handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, + csarInfo, nodesArtifactsToHandle, false, true, nodeName); + } else { + handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, + AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo, + newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true); + } + return handleComplexVfcRes; + } - private Resource handleComplexVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle, - List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, - String nodeName, String yamlName) { - - Resource oldComplexVfc = null; - Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo); - Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade - .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName()); - if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) { - oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName( - buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), - nodeName).getRight()); - } - if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) { - log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", - newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value()); - throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); - } else if (oldComplexVfcRes.isLeft()) { - log.debug(VALIDATE_DERIVED_BEFORE_UPDATE); - Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate( - oldComplexVfcRes.left().value(), newComplexVfc, - ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion())); - if (eitherValidation.isLeft()) { - oldComplexVfc = oldComplexVfcRes.left().value(); - } - } - newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, - oldComplexVfc, newComplexVfc); - csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName()); - LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction( - CERTIFICATION_ON_IMPORT, LifecycleChanceActionEnum.CREATE_FROM_CSAR); - log.debug("Going to certify cvfc {}. ", newComplexVfc.getName()); - Either<Resource, ResponseFormat> result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, - true); - if (result.isRight()) { - log.debug("Failed to certify complex VFC resource {}. ", newComplexVfc.getName()); - } - csarInfo.getCreatedNodes().put(nodeName, result.left().value()); - csarInfo.removeNodeFromQueue(); - return result.left().value(); - } + private Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, + Map<String, NodeTypeInfo> nodesInfo) { - private Resource handleComplexVfc(Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle, - List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, - String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) { - - Resource handleComplexVfcRes; - Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate(); - String yamlContent = new String(csarInfo.getCsar().get(yamlName)); - Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream() - .collect(toMap(Entry::getKey, e -> e.getValue().getUnmarkedCopy())); - CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo); - if (oldComplexVfc == null) { - handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, - csarInfo, nodesArtifactsToHandle, false, true, nodeName); - } else { - handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, - AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo, - newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true); - } - return handleComplexVfcRes; - } + Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo); + log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName()); + csarInfo.addNodeToQueue(nodeName); + return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, + true, csarInfo); + } - private Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, - Map<String, NodeTypeInfo> nodesInfo) { + private String getNodeTypeActualName(String fullName) { + String nameWithouNamespacePrefix = fullName + .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); + String[] findTypes = nameWithouNamespacePrefix.split("\\."); + String resourceType = findTypes[0]; + return nameWithouNamespacePrefix.substring(resourceType.length()); + } - Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo); - log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName()); - csarInfo.addNodeToQueue(nodeName); - return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), - AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo); - } + private ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(String yamlName, + Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert, Resource resourceVf, + boolean needLock, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, + List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, + boolean isNested) { - private String getNodeTypeActualName(String fullName) { - String nameWithouNamespacePrefix = fullName - .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); - String[] findTypes = nameWithouNamespacePrefix.split("\\."); - String resourceType = findTypes[0]; - return nameWithouNamespacePrefix.substring(resourceType.length()); - } + UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user); - private ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml( - String yamlName, Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert, - Resource resourceVf, boolean needLock, - Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, - List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, - boolean isNested) { - - UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user); - - String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, - resourceMetaData.getResourceType(), csarInfo); - user = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true); - return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, - nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, - nodeNameValue.getKey(), isNested); - } + String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), + csarInfo); + user = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true); + return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, + nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, + nodeNameValue.getKey(), isNested); + } - private String buildNodeTypeYaml(Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert, - String nodeResourceType, CsarInfo csarInfo) { - // We need to create a Yaml from each node_types in order to create - // resource from each node type using import normative flow. - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); + private String buildNodeTypeYaml(Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert, + String nodeResourceType, CsarInfo csarInfo) { + // We need to create a Yaml from each node_types in order to create + // resource from each node type using import normative flow. + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + Yaml yaml = new Yaml(options); - Map<String, Object> node = new HashMap<>(); - node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey()) - .getLeft(), nodeNameValue.getValue()); - mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node); + Map<String, Object> node = new HashMap<>(); + node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey()) + .getLeft(), nodeNameValue.getValue()); + mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node); - return yaml.dumpAsMap(mapToConvert); - } + return yaml.dumpAsMap(mapToConvert); + } - public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) { - validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE); - return Either.left(true); - } + public Boolean validateResourceCreationFromNodeType(Resource resource, User creator) { + validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE); + return true; + } - public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock, - Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, - List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, - String nodeName, boolean isNested) { - - LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT, - LifecycleChanceActionEnum.CREATE_FROM_CSAR); - Function<Resource, Either<Boolean, ResponseFormat>> validator = resource -> validateResourceCreationFromNodeType(resource, creator); - return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, - lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle, - nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested) - .left().on(this::failOnCertification); - } + public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml, + UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock, + Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, + List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, + String nodeName, boolean isNested) { + + LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT, + LifecycleChanceActionEnum.CREATE_FROM_CSAR); + Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType( + resource, creator); + return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, + lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle, + nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested); + } - private ImmutablePair<Resource,ActionStatus> failOnCertification(ResponseFormat error) { - throw new ByResponseFormatComponentException(error); - } + /*private ImmutablePair<Resource, ActionStatus> failOnCertification(ResponseFormat error) { + throw new ByResponseFormatComponentException(); + }*/ - private UploadResourceInfo fillResourceMetadata(String yamlName, Resource resourceVf, - String nodeName, User user) { - UploadResourceInfo resourceMetaData = new UploadResourceInfo(); + private UploadResourceInfo fillResourceMetadata(String yamlName, Resource resourceVf, String nodeName, User user) { + UploadResourceInfo resourceMetaData = new UploadResourceInfo(); - // validate nodetype name prefix - if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) { - log.debug("invalid nodeName:{} does not start with {}.", nodeName, - Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX); - throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, - yamlName, resourceMetaData.getName(), nodeName); - } + // validate nodetype name prefix + if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) { + log.debug("invalid nodeName:{} does not start with {}.", nodeName, + Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX); + throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), + nodeName); + } - String actualName = this.getNodeTypeActualName(nodeName); - String namePrefix = nodeName.replace(actualName, ""); - String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); + String actualName = this.getNodeTypeActualName(nodeName); + String namePrefix = nodeName.replace(actualName, ""); + String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); - // if we import from csar, the node_type name can be - // org.openecomp.resource.abstract.node_name - in this case we always - // create a vfc - if (resourceType.equals(Constants.ABSTRACT)) { - resourceType = ResourceTypeEnum.VFC.name().toLowerCase(); - } - // validating type - if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) { - log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), - ResourceTypeEnum.values()); - throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, - yamlName, resourceMetaData.getName(), nodeName); - } + // if we import from csar, the node_type name can be + // org.openecomp.resource.abstract.node_name - in this case we always + // create a vfc + if (resourceType.equals(Constants.ABSTRACT)) { + resourceType = ResourceTypeEnum.VFC.name() + .toLowerCase(); + } + // validating type + if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) { + log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), + ResourceTypeEnum.values()); + throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), + nodeName); + } - // Setting name - resourceMetaData.setName(resourceVf.getSystemName() + actualName); - - // Setting type from name - String type = resourceType.toUpperCase(); - resourceMetaData.setResourceType(type); - - resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION); - resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON); - resourceMetaData.setContactId(user.getUserId()); - resourceMetaData.setVendorName(resourceVf.getVendorName()); - resourceMetaData.setVendorRelease(resourceVf.getVendorRelease()); - - // Setting tag - List<String> tags = new ArrayList<>(); - tags.add(resourceMetaData.getName()); - resourceMetaData.setTags(tags); - - // Setting category - CategoryDefinition category = new CategoryDefinition(); - category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME); - SubCategoryDefinition subCategory = new SubCategoryDefinition(); - subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY); - category.addSubCategory(subCategory); - List<CategoryDefinition> categories = new ArrayList<>(); - categories.add(category); - resourceMetaData.setCategories(categories); - - return resourceMetaData; - } + // Setting name + resourceMetaData.setName(resourceVf.getSystemName() + actualName); + + // Setting type from name + String type = resourceType.toUpperCase(); + resourceMetaData.setResourceType(type); + + resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION); + resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON); + resourceMetaData.setContactId(user.getUserId()); + resourceMetaData.setVendorName(resourceVf.getVendorName()); + resourceMetaData.setVendorRelease(resourceVf.getVendorRelease()); + + // Setting tag + List<String> tags = new ArrayList<>(); + tags.add(resourceMetaData.getName()); + resourceMetaData.setTags(tags); + + // Setting category + CategoryDefinition category = new CategoryDefinition(); + category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME); + SubCategoryDefinition subCategory = new SubCategoryDefinition(); + subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY); + category.addSubCategory(subCategory); + List<CategoryDefinition> categories = new ArrayList<>(); + categories.add(category); + resourceMetaData.setCategories(categories); + + return resourceMetaData; + } - private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName, - Map<String, NodeTypeInfo> nodesInfo) { - Resource cvfc = new Resource(); - NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName); - cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName)); - cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName())); - cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName())); - cvfc.setResourceType(ResourceTypeEnum.CVFC); - cvfc.setAbstract(true); - cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom()); - cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION); - cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON); - cvfc.setContactId(csarInfo.getModifier().getUserId()); - cvfc.setCreatorUserId(csarInfo.getModifier().getUserId()); - cvfc.setVendorName(resourceVf.getVendorName()); - cvfc.setVendorRelease(resourceVf.getVendorRelease()); - cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber()); - cvfc.setToscaResourceName( - buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName) - .getLeft()); - cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID()); - - List<String> tags = new ArrayList<>(); - tags.add(cvfc.getName()); - cvfc.setTags(tags); - - CategoryDefinition category = new CategoryDefinition(); - category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME); - SubCategoryDefinition subCategory = new SubCategoryDefinition(); - subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY); - category.addSubCategory(subCategory); - List<CategoryDefinition> categories = new ArrayList<>(); - categories.add(category); - cvfc.setCategories(categories); - - cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION); - cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT); - cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION); - - return cvfc; - } + private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName, + Map<String, NodeTypeInfo> nodesInfo) { + Resource cvfc = new Resource(); + NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName); + cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName)); + cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName())); + cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName())); + cvfc.setResourceType(ResourceTypeEnum.CVFC); + cvfc.setAbstract(true); + cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom()); + cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION); + cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON); + cvfc.setContactId(csarInfo.getModifier() + .getUserId()); + cvfc.setCreatorUserId(csarInfo.getModifier() + .getUserId()); + cvfc.setVendorName(resourceVf.getVendorName()); + cvfc.setVendorRelease(resourceVf.getVendorRelease()); + cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber()); + cvfc.setToscaResourceName( + buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName) + .getLeft()); + cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID()); + + List<String> tags = new ArrayList<>(); + tags.add(cvfc.getName()); + cvfc.setTags(tags); + + CategoryDefinition category = new CategoryDefinition(); + category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME); + SubCategoryDefinition subCategory = new SubCategoryDefinition(); + subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY); + category.addSubCategory(subCategory); + List<CategoryDefinition> categories = new ArrayList<>(); + categories.add(category); + cvfc.setCategories(categories); + + cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION); + cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT); + cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION); + + return cvfc; + } - private String buildCvfcName(String resourceVfName, String nodeName) { - String nameWithouNamespacePrefix = nodeName - .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); - String[] findTypes = nameWithouNamespacePrefix.split("\\."); - String resourceType = findTypes[0]; - String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1); - return addCvfcSuffixToResourceName(resourceName); - } + private String buildCvfcName(String resourceVfName, String nodeName) { + String nameWithouNamespacePrefix = nodeName + .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); + String[] findTypes = nameWithouNamespacePrefix.split("\\."); + String resourceType = findTypes[0]; + String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1); + return addCvfcSuffixToResourceName(resourceName); + } - private Resource createResourceAndRIsFromYaml(String yamlName, Resource resource, - ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative, - List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml, - Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, - Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate, - boolean shouldLock, boolean inTransaction, String nodeName) { + private Resource createResourceAndRIsFromYaml(String yamlName, Resource resource, + ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative, + List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml, + Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate, + boolean shouldLock, boolean inTransaction, String nodeName) { - List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>(); + List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>(); if (shouldLock) { Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, @@ -1355,16 +1581,20 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } try { log.trace("************* createResourceFromYaml before full create resource {}", yamlName); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Starting to add inputs from yaml: {}",yamlName); final Resource genericResource = fetchAndSetDerivedFromGenericType(resource); - resource = createResourceTransaction(resource, csarInfo.getModifier(), isNormative); + resource = createResourceTransaction(resource, + csarInfo.getModifier(), isNormative); log.trace("************* createResourceFromYaml after full create resource {}", yamlName); log.trace("************* Going to add inputs from yaml {}", yamlName); - if (resource.shouldGenerateInputs()) { + if (resource.shouldGenerateInputs()) generateAndAddInputsFromGenericTypeProperties(resource, genericResource); - } + final Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs(); resource = createInputsOnResource(resource, inputs); log.trace("************* Finish to add inputs from yaml {}", yamlName); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(), + StatusCode.COMPLETE,"Finish to add inputs from yaml: {}",yamlName); if (resource.getResourceType() == ResourceTypeEnum.PNF) { log.trace("************* Adding generic properties to PNF"); resource = (Resource) propertyBusinessLogic.copyPropertyToComponent(resource, genericResource.getProperties()); @@ -1372,20 +1602,21 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { softwareInformationBusinessLogic.setSoftwareInformation(resource, csarInfo); log.trace("************* Removing non-mano software information file from PNF"); if (csarInfo.getSoftwareInformationPath().isPresent() && - !softwareInformationBusinessLogic.removeSoftwareInformationFile(csarInfo)) { + !softwareInformationBusinessLogic.removeSoftwareInformationFile(csarInfo)) { log.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR , ResourceBusinessLogic.class.getName(), - "catalog-be", "Could not remove the software information file."); + "catalog-be", "Could not remove the software information file."); } } Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo .getInstances(); - log.trace("************* Going to create nodes, Resource Instances and Relations from yaml {}", yamlName); + log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Start create nodes, RI and Relations from yaml: {}",yamlName); resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName); - - log.trace("************* Finished to create nodes, Resource Instances and Relations from yaml {}", yamlName); + log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,"Finished to create nodes, RI and Relation from yaml: {}",yamlName); // validate update vf module group names Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName()); @@ -1393,1739 +1624,1979 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right().value()); } - // add groups to resource Map<String, GroupDefinition> groups; log.trace("************* Going to add groups from yaml {}", yamlName); - + loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,resource.getComponentMetadataForSupportLog(), + StatusCode.STARTED,"Start to add groups from yaml: {}",yamlName); if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) { groups = validateUpdateVfGroupNamesRes.left().value(); } else { groups = parsedToscaYamlInfo.getGroups(); } - Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, - groups); - if (createGroupsOnResource.isRight()) { - rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); - throw new ByResponseFormatComponentException(createGroupsOnResource.right().value()); - } - resource = createGroupsOnResource.left().value(); - log.trace("************* Finished to add groups from yaml {}", yamlName); - - log.trace("************* Going to add artifacts from yaml {}", yamlName); - - NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, - nodeTypesArtifactsToCreate); - - Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.CREATE, createdArtifacts, yamlName, - csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock); - if (createArtifactsEither.isRight()) { - rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); - throw new ByResponseFormatComponentException(createArtifactsEither.right().value()); - } - - resource = getResourceWithGroups(createArtifactsEither.left().value().getUniqueId()); - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum); - ASDCKpiApi.countCreatedResourcesKPI(); - return resource; + Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, groups); + if (createGroupsOnResource.isRight()) { + rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,resource.getComponentMetadataForSupportLog(), + StatusCode.ERROR,"ERROR while adding groups from yaml: {}",yamlName); + throw new ByResponseFormatComponentException(createGroupsOnResource.right() + .value()); + } + resource = createGroupsOnResource.left() + .value(); + log.trace("************* Finished to add groups from yaml {}", yamlName); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,resource.getComponentMetadataForSupportLog(), + StatusCode.COMPLETE,"Finished to add groups from yaml: {}",yamlName); + + log.trace("************* Going to add artifacts from yaml {}", yamlName); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,resource.getComponentMetadataForSupportLog(), + StatusCode.STARTED,"Started to add artifacts from yaml: {}",yamlName); + + NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, + nodeTypesArtifactsToCreate); + + Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts( + ArtifactOperationEnum.CREATE, createdArtifacts, yamlName, csarInfo, resource, + nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock); + if (createArtifactsEither.isRight()) { + rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,resource.getComponentMetadataForSupportLog(), + StatusCode.ERROR,"error happened {}",createArtifactsEither.right() + .value()); + throw new ByResponseFormatComponentException(createArtifactsEither.right() + .value()); + } + loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,resource.getComponentMetadataForSupportLog(), + StatusCode.COMPLETE,"Finished to add artifacts from yaml: "+resource.getToscaResourceName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum); + ASDCKpiApi.countCreatedResourcesKPI(); + return resource; } catch (final ComponentException | StorageException e) { rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); throw e; } catch (final ToscaOperationException e) { - LOGGER.error("An error has occurred during resource and resource instance creation", e); + log.error("An error has occurred during resource and resource instance creation", e); rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR , ResourceBusinessLogic.class.getName(), "catalog-be", e.getMessage()); throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } catch (final BusinessLogicException e) { - LOGGER.error("An error has occurred during resource and resource instance creation", e); + log.error("An error has occurred during resource and resource instance creation", e); rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); throw new ByResponseFormatComponentException(e.getResponseFormat()); } finally { if (!inTransaction) { janusGraphDao.commit(); - } - if (shouldLock) { - graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), - NodeTypeEnum.Resource); - } - } - } + } + if (shouldLock) { + graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), + NodeTypeEnum.Resource); + } + } + } - private void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) { - if(!inTransaction) { + private void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts, + List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) { + if (!inTransaction) { janusGraphDao.rollback(); - } - if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) { - createdArtifacts.addAll(nodeTypesNewCreatedArtifacts); - log.debug("Found {} newly created artifacts to deleted, the component name: {}",createdArtifacts.size(), resource.getName()); - } - } - - private Resource getResourceWithGroups(String resourceId) { - - ComponentParametersView filter = new ComponentParametersView(); - filter.setIgnoreGroups(false); - Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter); - if (updatedResource.isRight()) { - rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId); - } - return updatedResource.left().value(); - } - - private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, - Map<String, GroupDefinition> groups) { - if (groups != null && !groups.isEmpty()) { - List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource( - groups, resource); - handleGroupsProperties(resource, groups); - fillGroupsFinalFields(groupsAsList); - Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, - groupsAsList, true); - if (createGroups.isRight()) { - return Either.right(createGroups.right().value()); - } - } else { - return Either.left(resource); - } - Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade - .getToscaElement(resource.getUniqueId()); - if (updatedResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource); - return Either.right(responseFormat); - } - return Either.left(updatedResource.left().value()); - } - - private void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) { - List<InputDefinition> inputs = resource.getInputs(); - if (MapUtils.isNotEmpty(groups)) { - groups.values() - .stream() - .filter(g -> isNotEmpty(g.getProperties())) - .flatMap(g -> g.getProperties().stream()) - .forEach(p -> handleGetInputs(p, inputs)); - } - } - - private void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) { - if (isNotEmpty(property.getGetInputValues())) { - if (inputs == null || inputs.isEmpty()) { - log.debug("Failed to add property {} to group. Inputs list is empty ", property); - rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues() - .stream() - .map(GetInputValueDataDefinition::getInputName) - .collect(toList()).toString()); - } - ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues().listIterator(); - while (getInputValuesIter.hasNext()) { - GetInputValueDataDefinition getInput = getInputValuesIter.next(); - InputDefinition input = findInputByName(inputs, getInput); - getInput.setInputId(input.getUniqueId()); - if (getInput.getGetInputIndex() != null) { - GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); - input = findInputByName(inputs, getInputIndex); - getInputIndex.setInputId(input.getUniqueId()); - getInputValuesIter.add(getInputIndex); - } - } - } - } - - private InputDefinition findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) { - Optional<InputDefinition> inputOpt = inputs.stream() - .filter(p -> p.getName().equals(getInput.getInputName())) - .findFirst(); - if (!inputOpt.isPresent()) { - log.debug("#findInputByName - Failed to find the input {} ", getInput.getInputName()); - rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, getInput.getInputName()); - } - return inputOpt.get(); - } - - private void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) { - groupsAsList.forEach(groupDefinition -> { - groupDefinition.setInvariantName(groupDefinition.getName()); - groupDefinition.setCreatedFrom(CreatedFrom.CSAR); - }); - } - - private Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) { - if (isEmpty(groups)) { - return resource; - } else { - updateOrCreateGroups(resource, groups); - } - Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade - .getToscaElement(resource.getUniqueId()); - if (updatedResource.isRight()) { - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource)); - } - return updatedResource.left().value(); - } + } + if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) { + createdArtifacts.addAll(nodeTypesNewCreatedArtifacts); + log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(), + resource.getName()); + } + } - private void updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) { - List<GroupDefinition> groupsFromResource = resource.getGroups(); - List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource); - List<GroupDefinition> groupsToUpdate = new ArrayList<>(); - List<GroupDefinition> groupsToDelete = new ArrayList<>(); - List<GroupDefinition> groupsToCreate = new ArrayList<>(); - if (isNotEmpty(groupsFromResource)) { - addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate); - addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete); - } else { - groupsToCreate.addAll(groupsAsList); - } - if (isNotEmpty(groupsToCreate)) { - fillGroupsFinalFields(groupsToCreate); - if (isNotEmpty(groupsFromResource)) { - groupBusinessLogic.addGroups(resource, - groupsToCreate, true) - .left() - .on(this::throwComponentException); - } else { - groupBusinessLogic.createGroups(resource, - groupsToCreate, true) - .left() - .on(this::throwComponentException); - } - } - if (isNotEmpty(groupsToDelete)) { - groupBusinessLogic.deleteGroups(resource, groupsToDelete) - .left() - .on(this::throwComponentException); - } - if (isNotEmpty(groupsToUpdate)) { - groupBusinessLogic.updateGroups(resource, groupsToUpdate, true) - .left() - .on(this::throwComponentException); - } - } + private Resource getResourceWithGroups(String resourceId) { - private void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, List<GroupDefinition> groupsToDelete) { - for (GroupDefinition group : groupsFromResource) { - Optional<GroupDefinition> op = groupsAsList.stream() - .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny(); - if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) { - groupsToDelete.add(group); - } - } - } + ComponentParametersView filter = new ComponentParametersView(); + filter.setIgnoreGroups(false); + Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, + filter); + if (updatedResource.isRight()) { + rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right() + .value()), resourceId); + } + return updatedResource.left() + .value(); + } - private void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) { - for (GroupDefinition group : groupsAsList) { - Optional<GroupDefinition> op = groupsFromResource.stream() - .filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName())).findAny(); - if (op.isPresent()) { - GroupDefinition groupToUpdate = op.get(); - groupToUpdate.setMembers(group.getMembers()); - groupToUpdate.setCapabilities(group.getCapabilities()); - groupToUpdate.setProperties(group.getProperties()); - groupsToUpdate.add(groupToUpdate); - } else { - groupsToCreate.add(group); - } - } - } + private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, + Map<String, GroupDefinition> groups) { + if (groups != null && !groups.isEmpty()) { + List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource); + handleGroupsProperties(resource, groups); + fillGroupsFinalFields(groupsAsList); + Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, + groupsAsList, true); + if (createGroups.isRight()) { + return Either.right(createGroups.right() + .value()); + } + } + return Either.left(resource); + } - private Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) { - List<InputDefinition> resourceProperties = resource.getInputs(); - if (MapUtils.isNotEmpty(inputs)|| isNotEmpty(resourceProperties)) { + private void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) { + List<InputDefinition> inputs = resource.getInputs(); + if (MapUtils.isNotEmpty(groups)) { + groups.values() + .stream() + .filter(g -> isNotEmpty(g.getProperties())) + .flatMap(g -> g.getProperties() + .stream()) + .forEach(p -> handleGetInputs(p, inputs)); + } + } - Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, - resource); - if (createInputs.isRight()) { - throw new ByResponseFormatComponentException(createInputs.right().value()); - } - } else { - return resource; - } - Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade - .getToscaElement(resource.getUniqueId()); - if (updatedResource.isRight()) { - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource)); - } - return updatedResource.left().value(); - } + private void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) { + if (isNotEmpty(property.getGetInputValues())) { + if (inputs == null || inputs.isEmpty()) { + log.debug("Failed to add property {} to group. Inputs list is empty ", property); + rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues() + .stream() + .map(GetInputValueDataDefinition::getInputName) + .collect(toList()) + .toString()); + } + ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues() + .listIterator(); + while (getInputValuesIter.hasNext()) { + GetInputValueDataDefinition getInput = getInputValuesIter.next(); + InputDefinition input = findInputByName(inputs, getInput); + getInput.setInputId(input.getUniqueId()); + if (getInput.getGetInputIndex() != null) { + GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); + input = findInputByName(inputs, getInputIndex); + getInputIndex.setInputId(input.getUniqueId()); + getInputValuesIter.add(getInputIndex); + } + } + } + } - private List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) { + private InputDefinition findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) { + Optional<InputDefinition> inputOpt = inputs.stream() + .filter(p -> p.getName() + .equals(getInput.getInputName())) + .findFirst(); + if (!inputOpt.isPresent()) { + log.debug("#findInputByName - Failed to find the input {} ", getInput.getInputName()); + rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, getInput.getInputName()); + } + return inputOpt.get(); + } - List<GroupDefinition> result = new ArrayList<>(); - List<ComponentInstance> componentInstances = component.getComponentInstances(); + private void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) { + groupsAsList.forEach(groupDefinition -> { + groupDefinition.setInvariantName(groupDefinition.getName()); + groupDefinition.setCreatedFrom(CreatedFrom.CSAR); + }); + } - if (groups != null) { - Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups); - if (validateCyclicGroupsDependencies.isRight()) { - throw new ByResponseFormatComponentException(validateCyclicGroupsDependencies.right().value()); - } - for (Entry<String, GroupDefinition> entry : groups.entrySet()) { - String groupName = entry.getKey(); - GroupDefinition groupDefinition = entry.getValue(); - GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition); - updatedGroupDefinition.setMembers(null); - Map<String, String> members = groupDefinition.getMembers(); - if (members != null) { - updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members); - } - result.add(updatedGroupDefinition); - } - } - return result; - } + private Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) { + if (isEmpty(groups)) { + return resource; + } + return updateOrCreateGroups(resource, groups); + } - private void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Resource component, List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) { - Set<String> compInstancesNames = members.keySet(); + private Resource updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) { + List<GroupDefinition> groupsFromResource = resource.getGroups(); + List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource); + List<GroupDefinition> groupsToUpdate = new ArrayList<>(); + List<GroupDefinition> groupsToDelete = new ArrayList<>(); + List<GroupDefinition> groupsToCreate = new ArrayList<>(); + if (isNotEmpty(groupsFromResource)) { + addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate); + addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete); + } else { + groupsToCreate.addAll(groupsAsList); + } + if (isNotEmpty(groupsToCreate)) { + fillGroupsFinalFields(groupsToCreate); + if (isNotEmpty(groupsFromResource)) { + groupBusinessLogic.addGroups(resource, groupsToCreate, true) + .left() + .on(this::throwComponentException); + } else { + groupBusinessLogic.createGroups(resource, groupsToCreate, true) + .left() + .on(this::throwComponentException); + } + } + if (isNotEmpty(groupsToDelete)) { + groupBusinessLogic.deleteGroups(resource, groupsToDelete) + .left() + .on(this::throwComponentException); + } + if (isNotEmpty(groupsToUpdate)) { + groupBusinessLogic.updateGroups(resource, groupsToUpdate, true) + .left() + .on(this::throwComponentException); + } + return resource; - if (CollectionUtils.isEmpty(componentInstances)) { - String membersAstString = compInstancesNames.stream().collect(joining(",")); - log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", - membersAstString, groupName, component.getNormalizedName()); - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat( - ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, - component.getNormalizedName(), getComponentTypeForResponse(component))); - } - // Find all component instances with the member names - Map<String, String> memberNames = componentInstances.stream() - .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId)); - memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> ""))); - Map<String, String> relevantInstances = memberNames.entrySet().stream() - .filter(n -> compInstancesNames.contains(n.getKey())) - .collect(toMap(Entry::getKey, Entry::getValue)); - - if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) { - - List<String> foundMembers = new ArrayList<>(); - if (relevantInstances != null) { - foundMembers = relevantInstances.keySet().stream().collect(toList()); - } - compInstancesNames.removeAll(foundMembers); - String membersAstString = compInstancesNames.stream().collect(joining(",")); - log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, - groupName, component.getNormalizedName()); - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat( - ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, - component.getNormalizedName(), getComponentTypeForResponse(component))); - } - updatedGroupDefinition.setMembers(relevantInstances); - } + } - /** - * This Method validates that there is no cyclic group dependencies. meaning - * group A as member in group B which is member in group A - * - * @param allGroups - * @return - */ - private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) { + private void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, + List<GroupDefinition> groupsToDelete) { + for (GroupDefinition group : groupsFromResource) { + Optional<GroupDefinition> op = groupsAsList.stream() + .filter(p -> p.getInvariantName() + .equalsIgnoreCase(group.getInvariantName())) + .findAny(); + if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts() + .isEmpty())) { + groupsToDelete.add(group); + } + } + } - Either<Boolean, ResponseFormat> result = Either.left(true); - try { - Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator(); - while (allGroupsItr.hasNext() && result.isLeft()) { - Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next(); - // Fetches a group member A - String groupAName = groupAEntry.getKey(); - // Finds all group members in group A - Set<String> allGroupAMembersNames = new HashSet<>(); - fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames); - // If A is a group member of itself found cyclic dependency - if (allGroupAMembersNames.contains(groupAName)) { - ResponseFormat responseFormat = componentsUtils - .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName); - result = Either.right(responseFormat); - } - } - } catch (Exception e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - result = Either.right(responseFormat); - log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e); - } - return result; - } + private void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, + List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) { + for (GroupDefinition group : groupsAsList) { + Optional<GroupDefinition> op = groupsFromResource.stream() + .filter(p -> p.getInvariantName() + .equalsIgnoreCase(group.getInvariantName())) + .findAny(); + if (op.isPresent()) { + GroupDefinition groupToUpdate = op.get(); + groupToUpdate.setMembers(group.getMembers()); + groupToUpdate.setCapabilities(group.getCapabilities()); + groupToUpdate.setProperties(group.getProperties()); + groupsToUpdate.add(groupToUpdate); + } else { + groupsToCreate.add(group); + } + } + } - /** - * This Method fills recursively the set groupMembers with all the members - * of the given group which are also of type group. - * - * @param groupName - * @param allGroups - * @param allGroupMembers - * @return - */ - private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups, - Set<String> allGroupMembers) { - - // Found Cyclic dependency - if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) { - return; - } - GroupDefinition groupDefinition = allGroups.get(groupName); - // All Members Of Current Group Resource Instances & Other Groups - Set<String> currGroupMembers = groupDefinition.getMembers().keySet(); - // Filtered Members Of Current Group containing only members which - // are groups - List<String> currGroupFilteredMembers = currGroupMembers.stream(). - // Keep Only Elements of type group and not Resource Instances - filter(allGroups::containsKey). - // Add Filtered Elements to main Set - peek(allGroupMembers::add). - // Collect results - collect(toList()); - - // Recursively call the method for all the filtered group members - for (String innerGroupName : currGroupFilteredMembers) { - fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers); - } + private Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) { + List<InputDefinition> resourceProperties = resource.getInputs(); + if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) { + + Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, + resource); + if (createInputs.isRight()) { + loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(), + StatusCode.ERROR,"failed to add inputs from yaml: {}",createInputs.right() + .value()); + throw new ByResponseFormatComponentException(createInputs.right() + .value()); + } + resource.setInputs(createInputs.left().value()); + } + return resource; + } - } + private List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, + Resource component) { - private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups, - Set<String> allGroupMembers) { + List<GroupDefinition> result = new ArrayList<>(); + List<ComponentInstance> componentInstances = component.getComponentInstances(); - boolean stop = false; - // In Case Not Group Stop - if (!allGroups.containsKey(groupName)) { - stop = true; - } - // In Case Group Has no members stop - if (!stop) { - GroupDefinition groupDefinition = allGroups.get(groupName); - stop = isEmpty(groupDefinition.getMembers()); + if (groups != null) { + Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups); + if (validateCyclicGroupsDependencies.isRight()) { + throw new ByResponseFormatComponentException(validateCyclicGroupsDependencies.right().value()); + } + for (Entry<String, GroupDefinition> entry : groups.entrySet()) { + String groupName = entry.getKey(); + GroupDefinition groupDefinition = entry.getValue(); + GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition); + updatedGroupDefinition.setMembers(null); + Map<String, String> members = groupDefinition.getMembers(); + if (members != null) { + updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, + members); + } + result.add(updatedGroupDefinition); + } + } + return result; + } - } - // In Case all group members already contained stop - if (!stop) { - final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet(); - Set<String> membersOfTypeGroup = allMembers.stream(). - // Filter In Only Group members - filter(allGroups::containsKey). - // Collect - collect(toSet()); - stop = allGroupMembers.containsAll(membersOfTypeGroup); - } - return stop; - } + private void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, + Resource component, List<ComponentInstance> componentInstances, String groupName, + Map<String, String> members) { + Set<String> compInstancesNames = members.keySet(); + + if (CollectionUtils.isEmpty(componentInstances)) { + String membersAstString = compInstancesNames.stream() + .collect(joining(",")); + log.debug( + "The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", + membersAstString, groupName, component.getNormalizedName()); + throw new ByActionStatusComponentException( + ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, + groupName, component.getNormalizedName(), getComponentTypeForResponse(component)); + } + // Find all component instances with the member names + Map<String, String> memberNames = componentInstances.stream() + .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId)); + memberNames.putAll(groups.keySet() + .stream() + .collect(toMap(g -> g, g -> ""))); + Map<String, String> relevantInstances = memberNames.entrySet() + .stream() + .filter(n -> compInstancesNames.contains(n.getKey())) + .collect(toMap(Entry::getKey, Entry::getValue)); + + if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) { + + List<String> foundMembers = new ArrayList<>(); + if (relevantInstances != null) { + foundMembers = relevantInstances.keySet() + .stream() + .collect(toList()); + } + compInstancesNames.removeAll(foundMembers); + String membersAstString = compInstancesNames.stream() + .collect(joining(",")); + log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, + component.getNormalizedName()); + throw new ByActionStatusComponentException( + ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, + groupName, component.getNormalizedName(), getComponentTypeForResponse(component)); + } + updatedGroupDefinition.setMembers(relevantInstances); + } - private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource, - Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, - String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, - Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, - Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate, - String nodeName) { - - log.debug("************* Going to create all nodes {}", yamlName); - handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, - nodeTypesInfo, csarInfo, nodeName); - log.debug("************* Finished to create all nodes {}", yamlName); - log.debug("************* Going to create all resource instances {}", yamlName); - resource = createResourceInstances(yamlName, resource, - uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes()); - log.debug("************* Finished to create all resource instances {}", yamlName); - log.debug("************* Going to create all relations {}", yamlName); - resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap); - log.debug("************* Finished to create all relations {}", yamlName); - log.debug("************* Going to create positions {}", yamlName); - compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId()); - log.debug("************* Finished to set positions {}", yamlName); - return resource; - } + /** + * This Method validates that there is no cyclic group dependencies. meaning + * group A as member in group B which is member in group A + * + * @param allGroups + * @return + */ + private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) { + + Either<Boolean, ResponseFormat> result = Either.left(true); + try { + Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet() + .iterator(); + while (allGroupsItr.hasNext() && result.isLeft()) { + Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next(); + // Fetches a group member A + String groupAName = groupAEntry.getKey(); + // Finds all group members in group A + Set<String> allGroupAMembersNames = new HashSet<>(); + fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames); + // If A is a group member of itself found cyclic dependency + if (allGroupAMembersNames.contains(groupAName)) { + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName); + result = Either.right(responseFormat); + } + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + result = Either.right(responseFormat); + log.debug("Exception occurred when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e); + } + return result; + } - private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts, - List<ArtifactDefinition> artifactsToAdd) { - List<String> vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName) - .collect(toList()); - artifactsToAdd.stream().forEach(a -> { - if (!vfcArtifactNames.contains(a.getArtifactName())) { - vfcArtifacts.add(a); - } else { - log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName()); - } - }); + /** + * This Method fills recursively the set groupMembers with all the members + * of the given group which are also of type group. + * + * @param groupName + * @param allGroups + * @param allGroupMembers + * @return + */ + private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups, + Set<String> allGroupMembers) { + + // Found Cyclic dependency + if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) { + return; + } + GroupDefinition groupDefinition = allGroups.get(groupName); + // All Members Of Current Group Resource Instances & Other Groups + Set<String> currGroupMembers = groupDefinition.getMembers() + .keySet(); + // Filtered Members Of Current Group containing only members which + // are groups + List<String> currGroupFilteredMembers = currGroupMembers.stream() + . + // Keep Only Elements of type group and not Resource Instances + filter(allGroups::containsKey) + . + // Add Filtered Elements to main Set + peek(allGroupMembers::add) + . + // Collect results + collect(toList()); + + // Recursively call the method for all the filtered group members + for (String innerGroupName : currGroupFilteredMembers) { + fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers); + } - } + } - @SuppressWarnings("unchecked") - private void handleNodeTypes(String yamlName, Resource resource, - String topologyTemplateYaml, boolean needLock, - Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, - List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, - CsarInfo csarInfo, String nodeName) { - try{ - for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) { - if (nodeTypeEntry.getValue().isNested()) { - - handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, - nodeTypesInfo, csarInfo, nodeTypeEntry.getKey()); - log.trace("************* finished to create node {}", nodeTypeEntry.getKey()); - } - } - Map<String, Object> mappedToscaTemplate = null; - if (StringUtils.isNotEmpty(nodeName) && isNotEmpty(nodeTypesInfo) - && nodeTypesInfo.containsKey(nodeName)) { - mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate(); - } - if (isEmpty(mappedToscaTemplate)) { - mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml); - } - createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle, - nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo); - } catch(ByActionStatusComponentException e){ - ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); - throw e; - } catch(ByResponseFormatComponentException e){ - ResponseFormat responseFormat = e.getResponseFormat(); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); - throw e; - } catch (StorageException e){ - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus())); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); - throw e; - } - } + private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups, + Set<String> allGroupMembers) { - private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo, - List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock, - boolean inTransaction) { - - if (csarInfo.getCsar() != null) { - String vendorLicenseModelId = null; - String vfLicenseModelId = null; - - if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) { - Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts(); - if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) { - for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) { - if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) { - vendorLicenseModelId = artifactEntry.getValue().getUniqueId(); - } - if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) { - vfLicenseModelId = artifactEntry.getValue().getUniqueId(); - } - } - } + boolean stop = false; + // In Case Not Group Stop + if (!allGroups.containsKey(groupName)) { + stop = true; + } + // In Case Group Has no members stop + if (!stop) { + GroupDefinition groupDefinition = allGroups.get(groupName); + stop = isEmpty(groupDefinition.getMembers()); - } - // Specific Behavior for license artifacts - createOrUpdateSingleNonMetaArtifact(resource, csarInfo, - CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL, - ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, - Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, - Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true, shouldLock, - inTransaction); - createOrUpdateSingleNonMetaArtifact(resource, csarInfo, - CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL, - ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL, - Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, - artifactOperation, null, true, shouldLock, inTransaction); - - Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, - createdArtifacts, shouldLock, inTransaction, artifactOperation); - if (eitherCreateResult.isRight()) { - return Either.right(eitherCreateResult.right().value()); - } - Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade - .getToscaElement(resource.getUniqueId()); - if (eitherGerResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); + } + // In Case all group members already contained stop + if (!stop) { + final Set<String> allMembers = allGroups.get(groupName) + .getMembers() + .keySet(); + Set<String> membersOfTypeGroup = allMembers.stream() + . + // Filter In Only Group members + filter(allGroups::containsKey) + . + // Collect + collect(toSet()); + stop = allGroupMembers.containsAll(membersOfTypeGroup); + } + return stop; + } - return Either.right(responseFormat); + private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource, + Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, String topologyTemplateYaml, + List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, + CsarInfo csarInfo, + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate, + String nodeName) { + + log.debug("************* Going to create all nodes {}", yamlName); + handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, + nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeName); + log.debug("************* Finished to create all nodes {}", yamlName); + log.debug("************* Going to create all resource instances {}", yamlName); + Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>(); + resource = createResourceInstances(yamlName, resource, null, uploadComponentInstanceInfoMap, + csarInfo.getCreatedNodes(), existingNodeTypesByResourceNames); + log.debug("************* Finished to create all resource instances {}", yamlName); + log.debug("************* Going to create all relations {}", yamlName); + resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, null, uploadComponentInstanceInfoMap, existingNodeTypesByResourceNames); + log.debug("************* Finished to create all relations {}", yamlName); + log.debug("************* Going to create positions {}", yamlName); + compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier() + .getUserId()); + log.debug("************* Finished to set positions {}", yamlName); + return resource; + } - } - resource = eitherGerResource.left().value(); - - Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils); - - if (artifacsMetaCsarStatus.isLeft()) { - String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey(); - String artifactsContents = artifacsMetaCsarStatus.left().value().getValue(); - Either<Resource, ResponseFormat> createArtifactsFromCsar; - if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) { - createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction); - } else { - createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction); - } + private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts, + List<ArtifactDefinition> artifactsToAdd) { + List<String> vfcArtifactNames = vfcArtifacts.stream() + .map(ArtifactDataDefinition::getArtifactName) + .collect(toList()); + artifactsToAdd.stream() + .forEach(a -> { + if (!vfcArtifactNames.contains(a.getArtifactName())) { + vfcArtifacts.add(a); + } else { + log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName()); + } + }); - if (createArtifactsFromCsar.isRight()) { - log.debug("Couldn't create artifacts from artifacts.meta"); - return Either.right(createArtifactsFromCsar.right().value()); - } + } - return Either.left(createArtifactsFromCsar.left().value()); - } else { + @SuppressWarnings("unchecked") + private void handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock, + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, + List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, + CsarInfo csarInfo, String nodeName) { + try { + for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) { + if (nodeTypeEntry.getValue() + .isNested()) { + + handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, + csarInfo, nodeTypeEntry.getKey()); + log.trace("************* finished to create node {}", nodeTypeEntry.getKey()); + } + } + Map<String, Object> mappedToscaTemplate = null; + if (StringUtils.isNotEmpty(nodeName) && isNotEmpty(nodeTypesInfo) && nodeTypesInfo.containsKey(nodeName)) { + mappedToscaTemplate = nodeTypesInfo.get(nodeName) + .getMappedToscaTemplate(); + } + if (isEmpty(mappedToscaTemplate)) { + mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml); + } + createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, + nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo); + } catch (ComponentException e) { + ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat() + : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, + AuditingActionEnum.IMPORT_RESOURCE); + throw e; + } catch (StorageException e) { + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus())); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, + AuditingActionEnum.IMPORT_RESOURCE); + throw e; + } + } - return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock, inTransaction); + private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo, + List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock, + boolean inTransaction) { + + if (csarInfo.getCsar() != null) { + String vendorLicenseModelId = null; + String vfLicenseModelId = null; + + if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) { + Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts(); + if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) { + for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) { + if (artifactEntry.getValue() + .getArtifactName() + .equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) { + vendorLicenseModelId = artifactEntry.getValue() + .getUniqueId(); + } + if (artifactEntry.getValue() + .getArtifactName() + .equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) { + vfLicenseModelId = artifactEntry.getValue() + .getUniqueId(); + } + } + } - } - } - return Either.left(resource); - } + } + // Specific Behavior for license artifacts + createOrUpdateSingleNonMetaArtifact(resource, csarInfo, + CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL, + ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, + Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, + Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true, + shouldLock, inTransaction); + createOrUpdateSingleNonMetaArtifact(resource, csarInfo, + CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL, + ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL, + Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, + artifactOperation, null, true, shouldLock, inTransaction); + + Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, + createdArtifacts, shouldLock, inTransaction, artifactOperation); + if (eitherCreateResult.isRight()) { + return Either.right(eitherCreateResult.right() + .value()); + } + Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils + .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils); + + if (artifacsMetaCsarStatus.isLeft()) { + String artifactsFileName = artifacsMetaCsarStatus.left() + .value() + .getKey(); + String artifactsContents = artifacsMetaCsarStatus.left() + .value() + .getValue(); + Either<Resource, ResponseFormat> createArtifactsFromCsar; + if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) { + createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar( + csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts); + } else { + createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar( + csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, + inTransaction); + } + + if (createArtifactsFromCsar.isRight()) { + log.debug("Couldn't create artifacts from artifacts.meta"); + return Either.right(createArtifactsFromCsar.right() + .value()); + } + + return Either.left(createArtifactsFromCsar.left() + .value()); + } else { + + return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock, + inTransaction); - private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo, - String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, - String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId, - ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean isFromCsar, boolean shouldLock, - boolean inTransaction) { - byte[] artifactFileBytes = null; + } + } + return Either.left(resource); + } - if (csarInfo.getCsar().containsKey(artifactPath)) { - artifactFileBytes = csarInfo.getCsar().get(artifactPath); - } - Either<Boolean, ResponseFormat> result = Either.left(true); - if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE) { - if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) { - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, - shouldLock, inTransaction); - if (handleDelete.isRight()) { - result = Either.right(handleDelete.right().value()); - } - return result; - } + private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo, + String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, + String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId, + ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean isFromCsar, + boolean shouldLock, boolean inTransaction) { + byte[] artifactFileBytes = null; + + if (csarInfo.getCsar() + .containsKey(artifactPath)) { + artifactFileBytes = csarInfo.getCsar() + .get(artifactPath); + } + Either<Boolean, ResponseFormat> result = Either.left(true); + if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE + || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE) { + if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) { + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic + .handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), + AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, shouldLock, + inTransaction); + if (handleDelete.isRight()) { + result = Either.right(handleDelete.right() + .value()); + } else { + Either<ArtifactDefinition, Operation> value = handleDelete.left().value(); + if (value.isLeft()) { + String updatedArtifactId = value.left().value().getUniqueId(); + if (artifactGroupType == ArtifactGroupTypeEnum.DEPLOYMENT) { + resource.getDeploymentArtifacts().remove(updatedArtifactId); + } else { + resource.getArtifacts().remove(updatedArtifactId); + } + } + } + return result; + } + if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) { + operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false, + ArtifactOperationEnum.CREATE); + } - if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) { - operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false, - ArtifactOperationEnum.CREATE); - } + } + if (artifactFileBytes != null) { + Map<String, Object> vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId, + artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName, + artifactDescription, artifactFileBytes, null, isFromCsar); + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic + .createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), vendorLicenseModelJson, + operation); + addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts); + if (eitherNonMetaArtifacts.isRight()) { + BeEcompErrorManager.getInstance() + .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: " + + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(), + ErrorSeverity.WARNING); + return Either.right(eitherNonMetaArtifacts.right() + .value()); + } + ArtifactDefinition artifactDefinition = eitherNonMetaArtifacts.left().value().left().value(); + createOrUpdateResourceWithUpdatedArtifact(artifactDefinition,resource, artifactGroupType); + } - } - if (artifactFileBytes != null) { - Map<String, Object> vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId, artifactFileName, - artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription, - artifactFileBytes, null, isFromCsar); - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic.createOrUpdateCsarArtifactFromJson( - resource, csarInfo.getModifier(), vendorLicenseModelJson, operation); - addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts); - if (eitherNonMetaArtifacts.isRight()) { - BeEcompErrorManager.getInstance() - .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: " - + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(), - ErrorSeverity.WARNING); - return Either.right(eitherNonMetaArtifacts.right().value()); - } - } - return result; - } + return result; + } - private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) { - return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar; - } + private void createOrUpdateResourceWithUpdatedArtifact(ArtifactDefinition artifact, Resource resource, ArtifactGroupTypeEnum groupTypeEnum) { + if (groupTypeEnum == ArtifactGroupTypeEnum.DEPLOYMENT) { + resource.getDeploymentArtifacts().put(artifact.getArtifactLabel(), artifact); + } else { + resource.getArtifacts().put(artifact.getArtifactLabel(), artifact); + } + } + private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) { + return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar; + } - private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, - List<ArtifactDefinition> createdArtifacts, - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) { - if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null - && eitherNonMetaArtifacts.isLeft()) { - Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value(); - if (eitherResult.isLeft()) { - createdArtifacts.add(eitherResult.left().value()); - } - } - } + private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, + List<ArtifactDefinition> createdArtifacts, + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) { + if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null + && eitherNonMetaArtifacts.isLeft()) { + Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left() + .value(); + if (eitherResult.isLeft()) { + createdArtifacts.add(eitherResult.left() + .value()); + } + } + } + private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource, + List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction, + ArtifactOperationInfo artifactOperation) { - private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource, - List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction, - ArtifactOperationInfo artifactOperation) { + Either<Resource, ResponseFormat> resStatus = null; + Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); - Either<Resource, ResponseFormat> resStatus = null; - Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); + try { + Either<List<NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, + collectedWarningMessages); + if (artifactPathAndNameList.isRight()) { + return Either.right(getComponentsUtils().getResponseFormatByArtifactId( + ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right() + .value())); + } + EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null; + + if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) { + vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); + vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left() + .value()); + } else { + Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle( + resource, artifactPathAndNameList.left() + .value(), + csarInfo.getModifier()); + + if (findVfCsarArtifactsToHandleRes.isRight()) { + resStatus = Either.right(findVfCsarArtifactsToHandleRes.right() + .value()); + } + if (resStatus == null) { + vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left() + .value(); + } + } + if (resStatus == null && vfCsarArtifactsToHandle != null) { + resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, + resStatus, vfCsarArtifactsToHandle); + } + if (resStatus == null) { + resStatus = Either.left(resource); + } + } catch (Exception e) { + resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + log.debug("Exception occurred in createNonMetaArtifacts, message:{}", e.getMessage(), e); + } finally { + CsarUtils.handleWarningMessages(collectedWarningMessages); + } + return resStatus; + } - try { - Either<List<NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages); - if (artifactPathAndNameList.isRight()) { - return Either.right(getComponentsUtils().getResponseFormatByArtifactId( - ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value())); - } - EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null; + private Either<Resource, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Resource resource, + List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction, + Either<Resource, ResponseFormat> resStatus, + EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle) { + for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle + .entrySet()) { + + Optional<ResponseFormat> optionalCreateInDBError = + // Stream of artifacts to be created + currArtifactOperationPair.getValue() + .stream() + // create each artifact + .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(), + e.getArtifactName(), e.getArtifactType() + .getType(), + e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), + CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(), + artifactsBusinessLogic.new ArtifactOperationInfo(false, false, + currArtifactOperationPair.getKey()), + createdArtifacts, e.isFromCsar(), shouldLock, inTransaction)) + // filter in only error + .filter(Either::isRight) + . + // Convert the error from either to + // ResponseFormat + map(e -> e.right() + .value()) + . + // Check if an error occurred + findAny(); + // Error found on artifact Creation + if (optionalCreateInDBError.isPresent()) { + resStatus = Either.right(optionalCreateInDBError.get()); + break; + } + } + return resStatus; + } - if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) { - vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); - vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value()); - } else { - Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle( - resource, artifactPathAndNameList.left().value(), csarInfo.getModifier()); + private Either<List<NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo, + Map<String, Set<List<String>>> collectedWarningMessages) { + List<NonMetaArtifactInfo> artifactPathAndNameList = + // Stream of file paths contained in csar + csarInfo.getCsar() + .entrySet() + .stream() + // Filter in only VF artifact path location + .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN) + .matcher(e.getKey()) + .matches()) + // Validate and add warnings + .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages)) + // Filter in Non Warnings + .filter(Either::isLeft) + // Convert from Either to NonMetaArtifactInfo + .map(e -> e.left() + .value()) + // collect to List + .collect(toList()); + Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME); + for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) { + if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()) + .matches()) { + return Either.right(nonMetaArtifactInfo.getArtifactName()); + } + } + return Either.left(artifactPathAndNameList); + } - if (findVfCsarArtifactsToHandleRes.isRight()) { - resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value()); - } - if (resStatus == null) { - vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value(); - } - } - if (resStatus == null && vfCsarArtifactsToHandle != null) { - resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, resStatus, vfCsarArtifactsToHandle); - } - if (resStatus == null) { - resStatus = Either.left(resource); - } - } catch (Exception e) { - resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e); - } finally { - CsarUtils.handleWarningMessages(collectedWarningMessages); - } - return resStatus; - } + private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle( + Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) { - private Either<Resource, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Resource resource, List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction, Either<Resource, ResponseFormat> resStatus, EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle) { - for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle - .entrySet()) { - - Optional<ResponseFormat> optionalCreateInDBError = - // Stream of artifacts to be created - currArtifactOperationPair.getValue().stream() - // create each artifact - .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(), - e.getArtifactName(), e.getArtifactType().getType(), - e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), - CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(), - artifactsBusinessLogic.new ArtifactOperationInfo(false, false, - currArtifactOperationPair.getKey()), - createdArtifacts, e.isFromCsar(), shouldLock, inTransaction)) - // filter in only error - .filter(Either::isRight). - // Convert the error from either to - // ResponseFormat - map(e -> e.right().value()). - // Check if an error occurred - findAny(); - // Error found on artifact Creation - if (optionalCreateInDBError.isPresent()) { - resStatus = Either.right(optionalCreateInDBError.get()); - break; - } - } - return resStatus; - } + List<ArtifactDefinition> existingArtifacts = new ArrayList<>(); + // collect all Deployment and Informational artifacts of VF + if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts() + .isEmpty()) { + existingArtifacts.addAll(resource.getDeploymentArtifacts() + .values()); + } + if (resource.getArtifacts() != null && !resource.getArtifacts() + .isEmpty()) { + existingArtifacts.addAll(resource.getArtifacts() + .values()); + } + existingArtifacts = existingArtifacts.stream() + // filter MANDATORY artifacts, LICENSE artifacts and artifacts + // was created from HEAT.meta + .filter(this::isNonMetaArtifact) + .collect(toList()); + + List<String> artifactsToIgnore = new ArrayList<>(); + // collect IDs of Artifacts of VF which belongs to any group + if (resource.getGroups() != null) { + resource.getGroups() + .stream() + .forEach(g -> { + if (g.getArtifacts() != null && !g.getArtifacts() + .isEmpty()) { + artifactsToIgnore.addAll(g.getArtifacts()); + } + }); + } + existingArtifacts = existingArtifacts.stream() + // filter artifacts which belongs to any group + .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())) + .collect(toList()); + return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user); + } - private Either<List<NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo, Map<String, Set<List<String>>> collectedWarningMessages) { - List<NonMetaArtifactInfo> artifactPathAndNameList = - // Stream of file paths contained in csar - csarInfo.getCsar().entrySet().stream() - // Filter in only VF artifact path location - .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()) - .matches()) - // Validate and add warnings - .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), - collectedWarningMessages)) - // Filter in Non Warnings - .filter(Either::isLeft) - // Convert from Either to NonMetaArtifactInfo - .map(e -> e.left().value()) - // collect to List - .collect(toList()); - Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME); - for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) { - if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) { - return Either.right(nonMetaArtifactInfo.getArtifactName()); - } - } - return Either.left(artifactPathAndNameList); - } + private boolean isNonMetaArtifact(ArtifactDefinition artifact) { + boolean result = true; + if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) { + result = false; + } + return result; + } - private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle( - Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) { + private boolean isValidArtifactType(ArtifactDefinition artifact) { + boolean result = true; + if (artifact.getArtifactType() == null + || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE + || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) { + result = false; + } + return result; + } - List<ArtifactDefinition> existingArtifacts = new ArrayList<>(); - // collect all Deployment and Informational artifacts of VF - if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) { - existingArtifacts.addAll(resource.getDeploymentArtifacts().values()); - } - if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) { - existingArtifacts.addAll(resource.getArtifacts().values()); - } - existingArtifacts = existingArtifacts.stream() - // filter MANDATORY artifacts, LICENSE artifacts and artifacts - // was created from HEAT.meta - .filter(this::isNonMetaArtifact).collect(toList()); - - List<String> artifactsToIgnore = new ArrayList<>(); - // collect IDs of Artifacts of VF which belongs to any group - if (resource.getGroups() != null) { - resource.getGroups().stream().forEach(g -> { - if (g.getArtifacts() != null && !g.getArtifacts().isEmpty()) { - artifactsToIgnore.addAll(g.getArtifacts()); - } - }); - } - existingArtifacts = existingArtifacts.stream() - // filter artifacts which belongs to any group - .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList()); - return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user); - } + private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource, Resource oldResource, + Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, Map<String, Resource> existingNodeTypesByResourceNames) { + log.debug("#createResourceInstancesRelations - Going to create relations "); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Start to create relations"); + List<ComponentInstance> componentInstancesList = resource.getComponentInstances(); + if (isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList) && + resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances { + log.debug( + "#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", + resource.getUniqueId(), yamlName); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"No instances found in the resource: {}, is empty, yaml template file name: {}",resource.getName(),yamlName); + BeEcompErrorManager.getInstance() + .logInternalDataError("createResourceInstancesRelations", + "No instances found in a resource or nn yaml template. ", ErrorSeverity.ERROR); + throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + } + Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>(); + Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>(); + Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>(); + Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>(); + Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>(); + Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>(); + List<RequirementCapabilityRelDef> relations = new ArrayList<>(); + Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>(); + + log.debug("#createResourceInstancesRelations - Before get all datatypes. "); + Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + JanusGraphOperationStatus status = allDataTypes.right() + .value(); + BeEcompErrorManager.getInstance() + .logInternalFlowError("UpdatePropertyValueOnComponentInstance", + "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), + StatusCode.ERROR,"ERROR while update property value on instance. Status is: "+status); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse( + DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName); - private boolean isNonMetaArtifact(ArtifactDefinition artifact) { - boolean result = true; - if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) { - result = false; - } - return result; - } + } + Resource finalResource = resource; + uploadResInstancesMap.values() + .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes, + instProperties, instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts, + instAttributes, existingNodeTypesByResourceNames, instInputs, i)); + resource.getComponentInstances() + .stream() + .filter(i -> !i.isCreatedFromCsar()) + .forEach(i->processUiComponentInstance(oldResource, i, instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts, instProperties, instInputs, instAttributes)); + + associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties); + associateComponentInstanceInputsToComponent(yamlName, resource, instInputs); + associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts); + associateArtifactsToInstances(yamlName, resource, instArtifacts); + associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements); + associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes); + addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations); + associateResourceInstances(yamlName, resource, relations); + handleSubstitutionMappings(resource, uploadResInstancesMap); + log.debug("************* in create relations, getResource start"); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,"create relations"); + Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade + .getToscaFullElement(resource.getUniqueId()); + log.debug("************* in create relations, getResource end"); + if (eitherGetResource.isRight()) { + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), + StatusCode.ERROR,"ERROR while create relations"); + throw new ByResponseFormatComponentException(componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right() + .value()), resource)); + } + return eitherGetResource.left() + .value(); + } - private boolean isValidArtifactType(ArtifactDefinition artifact) { - boolean result = true; - if (artifact.getArtifactType() == null - || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE - || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) { - result = false; - } - return result; - } + private void processUiComponentInstance(Resource oldResource, ComponentInstance instance, + Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities, + Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements, + Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, + Map<String, Map<String, ArtifactDefinition>> instArtifacts, Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, List<ComponentInstanceInput>> instInputs, Map<String, List<PropertyDefinition>> instAttributes) { + Optional<ComponentInstance> foundInstance = findInstance(oldResource, instance); + if(foundInstance.isPresent()){ + if(MapUtils.isNotEmpty(foundInstance.get().getCapabilities())){ + instCapabilities.put(instance, foundInstance.get().getCapabilities()); + } + if(MapUtils.isNotEmpty(foundInstance.get().getRequirements())){ + instRequirements.put(instance, foundInstance.get().getRequirements()); + } + if(MapUtils.isNotEmpty(foundInstance.get().getDeploymentArtifacts())){ + instDeploymentArtifacts.put(instance.getUniqueId(), foundInstance.get().getDeploymentArtifacts()); + } + if(MapUtils.isNotEmpty(foundInstance.get().getArtifacts())){ + instArtifacts.put(instance.getUniqueId(), foundInstance.get().getArtifacts()); + } + if(MapUtils.isNotEmpty(oldResource.getComponentInstancesProperties()) && + CollectionUtils.isNotEmpty(oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()))){ + instProperties.put(instance.getUniqueId(), oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId())); + } + if(MapUtils.isNotEmpty(oldResource.getComponentInstancesInputs()) && + CollectionUtils.isNotEmpty(oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()))){ + instInputs.put(instance.getUniqueId(), oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId())); + } + if(MapUtils.isNotEmpty(oldResource.getComponentInstancesAttributes()) && + CollectionUtils.isNotEmpty(oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()))){ + instAttributes.put(instance.getUniqueId(), oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()).stream().map(PropertyDefinition::new).collect(toList())); + } + } + } - private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource, - Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) { - log.debug("#createResourceInstancesRelations - Going to create relations "); - List<ComponentInstance> componentInstancesList = resource.getComponentInstances(); - if (((isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) && - resource.getResourceType() != ResourceTypeEnum.PNF)) { // PNF can have no resource instances - log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", resource.getUniqueId(), yamlName); - BeEcompErrorManager.getInstance().logInternalDataError("createResourceInstancesRelations", "No instances found in a resource or nn yaml template. ", ErrorSeverity.ERROR); - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName)); - } - Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>(); - Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>(); - Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>(); - Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>(); - Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>(); - Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>(); - Map<String, Resource> originCompMap = new HashMap<>(); - List<RequirementCapabilityRelDef> relations = new ArrayList<>(); - Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>(); - - log.debug("#createResourceInstancesRelations - Before get all datatypes. "); - Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll(); - if (allDataTypes.isRight()) { - JanusGraphOperationStatus status = allDataTypes.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", - "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( - DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName)); + private Optional<ComponentInstance> findInstance(Resource oldResource, ComponentInstance instance) { + if(oldResource != null && CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) { + return oldResource.getComponentInstances().stream().filter(i -> i.getName().equals(instance.getName())).findFirst(); + } + return Optional.empty(); + } - } - Resource finalResource = resource; - uploadResInstancesMap - .values() - .forEach(i ->processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes, - instProperties, instCapabilities, instRequirements, instDeploymentArtifacts, - instArtifacts, instAttributes, originCompMap, instInputs, i)); - - associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties); - associateComponentInstanceInputsToComponent(yamlName, resource, instInputs); - associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts); - associateArtifactsToInstances(yamlName, resource, instArtifacts); - associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements); - associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes); - - resource = getResourceAfterCreateRelations(resource); - - addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations); - associateResourceInstances(yamlName, resource, relations); - handleSubstitutionMappings(resource, uploadResInstancesMap); - log.debug("************* in create relations, getResource start"); - Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); - log.debug("************* in create relations, getResource end"); - if (eitherGetResource.isRight()) { - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource)); - } - return eitherGetResource.left().value(); - } + private void associateResourceInstances(String yamlName, Resource resource, + List<RequirementCapabilityRelDef> relations) { + Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade.associateResourceInstances(resource, resource.getUniqueId(), relations); + + if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) { + StorageOperationStatus status = relationsEither.right().value(); + log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), + status); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), yamlName); + } else { + setResourceInstanceRelationsOnComponent(resource, relationsEither.left().value()); + } + } - private Resource getResourceAfterCreateRelations(Resource resource) { - ComponentParametersView parametersView = getComponentFilterAfterCreateRelations(); - Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade - .getToscaElement(resource.getUniqueId(), parametersView); + private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource, + Map<String, List<PropertyDefinition>> instAttributes) { + StorageOperationStatus addArtToInst; + addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, + resource); + if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { + log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), + addArtToInst); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + } + } - if (eitherGetResource.isRight()) { - throwComponentExceptionByResource(eitherGetResource.right().value(),resource); - } - return eitherGetResource.left().value(); - } + private void associateOrAddCalculatedCapReq(String yamlName, Resource resource, + Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities, + Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) { + StorageOperationStatus addArtToInst; + addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, + resource); + if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { + log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), + addArtToInst); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + } + } - private void associateResourceInstances(String yamlName, Resource resource, List<RequirementCapabilityRelDef> relations) { - StorageOperationStatus addArtToInst; - addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations); - if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), - addArtToInst); - throw new ByResponseFormatComponentException(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); - } - } + private void associateArtifactsToInstances(String yamlName, Resource resource, + Map<String, Map<String, ArtifactDefinition>> instArtifacts) { + StorageOperationStatus addArtToInst; - private ComponentParametersView getComponentFilterAfterCreateRelations() { - ComponentParametersView parametersView = new ComponentParametersView(); - parametersView.disableAll(); - parametersView.setIgnoreComponentInstances(false); - parametersView.setIgnoreComponentInstancesProperties(false); - parametersView.setIgnoreCapabilities(false); - parametersView.setIgnoreRequirements(false); - parametersView.setIgnoreGroups(false); - return parametersView; - } + addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource); + if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { + log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + } + } - private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource, Map<String, List<PropertyDefinition>> instAttributes) { - StorageOperationStatus addArtToInst; - addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, - resource.getUniqueId()); - if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), - addArtToInst); - throw new ByResponseFormatComponentException(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); - } - } + private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource, + Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) { + StorageOperationStatus addArtToInst = toscaOperationFacade + .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user); + if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { + log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + } + } - private void associateOrAddCalculatedCapReq(String yamlName, Resource resource, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) { - StorageOperationStatus addArtToInst; - addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, - resource.getUniqueId()); - if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), - addArtToInst); - throw new ByResponseFormatComponentException(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); - } - } + private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource, + Map<String, List<ComponentInstanceInput>> instInputs) { + if (MapUtils.isNotEmpty(instInputs)) { + Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade + .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId()); + if (addInputToInst.isRight()) { + + StorageOperationStatus addInputToInstError = addInputToInst.right().value(); + log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), + addInputToInstError); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addInputToInstError), yamlName); + } + setComponentInstanceInputsOnComponent(resource, instInputs); + } + } - private void associateArtifactsToInstances(String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) { - StorageOperationStatus addArtToInst; + private void setComponentInstanceInputsOnComponent(Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) { + Map<String, List<ComponentInstanceInput>> componentInstancesInputs = resource.getComponentInstancesInputs(); + if (componentInstancesInputs == null) + componentInstancesInputs = new HashMap<>(); + componentInstancesInputs.putAll(instInputs); + resource.setComponentInstancesInputs(componentInstancesInputs); + } - addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource.getUniqueId()); - if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst); - throw new ByResponseFormatComponentException(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); - } - } + private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource, + Map<String, List<ComponentInstanceProperty>> instProperties) { + Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade + .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId()); + if (addPropToInst.isRight()) { + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), + StatusCode.ERROR,"ERROR while associate compnent insatnce properties of resource: {} status is: {}",resource.getName(),addPropToInst.right().value()); + StorageOperationStatus storageOperationStatus = addPropToInst.right().value(); + log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), + storageOperationStatus); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), yamlName); + } + setComponentInstancePropertiesOnComponent(resource, instProperties); + } - private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) { - StorageOperationStatus addArtToInst = toscaOperationFacade - .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource.getUniqueId(), user); - if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst); - throw new ByResponseFormatComponentException(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); - } - } + private void setComponentInstancePropertiesOnComponent(Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) { + Map<String, List<ComponentInstanceProperty>> componentInstanceProps = resource.getComponentInstancesProperties(); + if (componentInstanceProps == null ) + componentInstanceProps = new HashMap<>(); + componentInstanceProps.putAll(instProperties); + resource.setComponentInstancesProperties(componentInstanceProps); + } - private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) { - if (MapUtils.isNotEmpty(instInputs)) { - Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade - .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId()); - if (addInputToInst.isRight()) { - log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), - addInputToInst.right().value()); - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName)); - } - } - } + private void handleSubstitutionMappings(Resource resource, + Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) { + if (resource.getResourceType() == ResourceTypeEnum.CVFC) { + Either<Resource, StorageOperationStatus> getResourceRes = + updateCalculatedCapReqWithSubstitutionMappings(resource, uploadResInstancesMap); + if (getResourceRes.isRight()) { + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right() + .value()), resource); + throw new ByResponseFormatComponentException(responseFormat); + } + } + } - private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) { - Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade - .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId()); - if (addPropToInst.isRight()) { - log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), - addPropToInst.right().value()); - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName)); - } - } + private void addRelationsToRI(String yamlName, Resource resource, + Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, + List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) { + for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) { + UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue(); + ComponentInstance currentCompInstance = null; + for (ComponentInstance compInstance : componentInstancesList) { - private void handleSubstitutionMappings(Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) { - if (resource.getResourceType() == ResourceTypeEnum.CVFC) { - Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaFullElement(resource.getUniqueId()); - if (getResourceRes.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource); - throw new ByResponseFormatComponentException(responseFormat); - } - getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(), - uploadResInstancesMap); - if (getResourceRes.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource); - throw new ByResponseFormatComponentException(responseFormat); - } - } - } + if (compInstance.getName() + .equals(uploadComponentInstanceInfo.getName())) { + currentCompInstance = compInstance; + break; + } - private void addRelationsToRI(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) { - for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) { - UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue(); - ComponentInstance currentCompInstance = null; - for (ComponentInstance compInstance : componentInstancesList) { + } + if (currentCompInstance == null) { + log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), + resource.getUniqueId()); + BeEcompErrorManager.getInstance() + .logInternalDataError( + COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, + resource.getUniqueId(), ErrorSeverity.ERROR); + throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + } - if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) { - currentCompInstance = compInstance; - break; - } + ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations); + if (addRelationToRiRes.getStatus() != 200) { + throw new ByResponseFormatComponentException(addRelationToRiRes); + } + } - } - if (currentCompInstance == null) { - log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), - resource.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError( - COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, - resource.getUniqueId(), ErrorSeverity.ERROR); - ResponseFormat responseFormat = componentsUtils - .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - throw new ByResponseFormatComponentException(responseFormat); - } + } - ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations); - if (addRelationToRiRes.getStatus() != 200) { - throw new ByResponseFormatComponentException(addRelationToRiRes); - } - } - } + private void setResourceInstanceRelationsOnComponent(Resource resource, List<RequirementCapabilityRelDef> relations) { + if (resource.getComponentInstancesRelations() != null) { + /*Map<String, RequirementCapabilityRelDef> relationsMapByUid = resource.getComponentInstancesRelations().stream().collect(Collectors.toMap(r -> r.getUid(), r -> r)); + Map<String, RequirementCapabilityRelDef> updatedRelationsByUid = relations.stream().collect(Collectors.toMap(r -> r.getUid(), r -> r)); + relationsMapByUid.putAll(updatedRelationsByUid); + resource.setComponentInstancesRelations(new ArrayList<>(relationsMapByUid.values()));*/ + resource.getComponentInstancesRelations().addAll(relations); + } else { + resource.setComponentInstancesRelations(relations); + } + } - private void processComponentInstance(String yamlName, Resource resource, List<ComponentInstance> componentInstancesList, Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes, Map<String, List<ComponentInstanceProperty>> instProperties, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements, Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, Map<String, Map<String, ArtifactDefinition>> instArtifacts, Map<String, List<PropertyDefinition>> instAttributes, Map<String, Resource> originCompMap, Map<String, List<ComponentInstanceInput>> instInputs, UploadComponentInstanceInfo uploadComponentInstanceInfo) { - Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream() - .filter(i->i.getName().equals(uploadComponentInstanceInfo.getName())) - .findFirst(); - if (!currentCompInstanceOpt.isPresent()) { - log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), - resource.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError( - COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, - resource.getUniqueId(), ErrorSeverity.ERROR); - ResponseFormat responseFormat = componentsUtils - .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - throw new ByResponseFormatComponentException(responseFormat); - } - ComponentInstance currentCompInstance = currentCompInstanceOpt.get(); - String resourceInstanceId = currentCompInstance.getUniqueId(); - Resource originResource = getOriginResource(yamlName, originCompMap, currentCompInstance); - if (isNotEmpty(originResource.getRequirements())) { - instRequirements.put(currentCompInstance, originResource.getRequirements()); - } - if (isNotEmpty(originResource.getCapabilities())) { - processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo, - currentCompInstance, originResource); - } - if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) { - instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts()); - } - if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) { - instArtifacts.put(resourceInstanceId, originResource.getArtifacts()); - } - if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) { - instAttributes.put(resourceInstanceId, originResource.getAttributes()); - } - if (originResource.getResourceType() != ResourceTypeEnum.CVFC) { - ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, - originResource, currentCompInstance, instProperties, allDataTypes.left().value()); - if (addPropertiesValueToRiRes.getStatus() != 200) { - throw new ByResponseFormatComponentException(addPropertiesValueToRiRes); - } - } else { - addInputsValuesToRi(uploadComponentInstanceInfo, resource, - originResource, currentCompInstance, instInputs, allDataTypes.left().value()); - } - } + private void processComponentInstance(String yamlName, Resource resource, + List<ComponentInstance> componentInstancesList, + Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes, + Map<String, List<ComponentInstanceProperty>> instProperties, + Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, + Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements, + Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, + Map<String, Map<String, ArtifactDefinition>> instArtifacts, + Map<String, List<PropertyDefinition>> instAttributes, Map<String, Resource> originCompMap, + Map<String, List<ComponentInstanceInput>> instInputs, + UploadComponentInstanceInfo uploadComponentInstanceInfo) { + Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream() + .filter(i -> i.getName() + .equals(uploadComponentInstanceInfo.getName())) + .findFirst(); + if (!currentCompInstanceOpt.isPresent()) { + log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), + resource.getUniqueId()); + BeEcompErrorManager.getInstance() + .logInternalDataError( + COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, + resource.getUniqueId(), ErrorSeverity.ERROR); + throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + } + ComponentInstance currentCompInstance = currentCompInstanceOpt.get(); + String resourceInstanceId = currentCompInstance.getUniqueId(); + Resource originResource = getOriginResource(originCompMap, currentCompInstance); + if (isNotEmpty(originResource.getRequirements())) { + instRequirements.put(currentCompInstance, originResource.getRequirements()); + } + if (isNotEmpty(originResource.getCapabilities())) { + processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo, + currentCompInstance, originResource); + } + if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts() + .isEmpty()) { + instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts()); + } + if (originResource.getArtifacts() != null && !originResource.getArtifacts() + .isEmpty()) { + instArtifacts.put(resourceInstanceId, originResource.getArtifacts()); + } + if (originResource.getAttributes() != null && !originResource.getAttributes() + .isEmpty()) { + instAttributes.put(resourceInstanceId, originResource.getAttributes()); + } + if (originResource.getResourceType() != ResourceTypeEnum.CVFC) { + ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, + originResource, currentCompInstance, instProperties, allDataTypes.left() + .value()); + if (addPropertiesValueToRiRes.getStatus() != 200) { + throw new ByResponseFormatComponentException(addPropertiesValueToRiRes); + } + } else { + addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, instInputs, + allDataTypes.left() + .value()); + } + } - private Resource getOriginResource(String yamlName, Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) { - Resource originResource; - if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) { - Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade - .getToscaFullElement(currentCompInstance.getComponentUid()); - if (getOriginResourceRes.isRight()) { - log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}", - currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(), - getOriginResourceRes); - ResponseFormat responseFormat = componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName); - throw new ByResponseFormatComponentException(responseFormat); - } - originResource = getOriginResourceRes.left().value(); - originCompMap.put(originResource.getUniqueId(), originResource); - } else { - originResource = originCompMap.get(currentCompInstance.getComponentUid()); - } - return originResource; - } + private Resource getOriginResource(Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) { + Resource originResource; + if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) { + Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade + .getToscaFullElement(currentCompInstance.getComponentUid()); + if (getOriginResourceRes.isRight()) { + log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}", + currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(), + getOriginResourceRes); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right() + .value()), currentCompInstance.getComponentUid()); + } + originResource = getOriginResourceRes.left() + .value(); + originCompMap.put(originResource.getUniqueId(), originResource); + } else { + originResource = originCompMap.get(currentCompInstance.getComponentUid()); + } + return originResource; + } - private void processComponentInstanceCapabilities(Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, Resource originResource) { - Map<String, List<CapabilityDefinition>> originCapabilities; - if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) { - originCapabilities = new HashMap<>(); - Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>(); - originResource.getCapabilities().forEach((k,v) -> addCapabilities(originCapabilities, k, v)); - uploadComponentInstanceInfo.getCapabilities().values().forEach(l-> addCapabilitiesProperties(newPropertiesMap, l)); - updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap); - } else { - originCapabilities = originResource.getCapabilities(); - } - instCapabilties.put(currentCompInstance, originCapabilities); - } + private void processComponentInstanceCapabilities( + Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes, + Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, + UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, + Resource originResource) { + Map<String, List<CapabilityDefinition>> originCapabilities; + if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) { + originCapabilities = new HashMap<>(); + Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>(); + originResource.getCapabilities() + .forEach((k, v) -> addCapabilities(originCapabilities, k, v)); + uploadComponentInstanceInfo.getCapabilities() + .values() + .forEach(l -> addCapabilitiesProperties(newPropertiesMap, l)); + updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap); + } else { + originCapabilities = originResource.getCapabilities(); + } + instCapabilties.put(currentCompInstance, originCapabilities); + } - private void updateCapabilityPropertiesValues(Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes, Map<String, List<CapabilityDefinition>> originCapabilities, Map<String, Map<String, UploadPropInfo>> newPropertiesMap) { - originCapabilities.values().stream() - .flatMap(Collection::stream) - .filter(c -> newPropertiesMap.containsKey(c.getName())) - .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes.left().value())); - } + private void updateCapabilityPropertiesValues( + Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes, + Map<String, List<CapabilityDefinition>> originCapabilities, + Map<String, Map<String, UploadPropInfo>> newPropertiesMap) { + originCapabilities.values() + .stream() + .flatMap(Collection::stream) + .filter(c -> newPropertiesMap.containsKey(c.getName())) + .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), + allDataTypes.left() + .value())); + } - private void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap, List<UploadCapInfo> capabilities) { - for (UploadCapInfo capability : capabilities) { - if (isNotEmpty(capability.getProperties())) { - newPropertiesMap.put(capability.getName(), capability.getProperties().stream() - .collect(toMap(UploadInfo::getName, p -> p))); - } - } - } + private void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap, + List<UploadCapInfo> capabilities) { + for (UploadCapInfo capability : capabilities) { + if (isNotEmpty(capability.getProperties())) { + newPropertiesMap.put(capability.getName(), capability.getProperties() + .stream() + .collect(toMap(UploadInfo::getName, p -> p))); + } + } + } - private void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type, List<CapabilityDefinition> capabilities) { - List<CapabilityDefinition> list = capabilities.stream().map(CapabilityDefinition::new) - .collect(toList()); - originCapabilities.put(type, list); - } + private void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type, + List<CapabilityDefinition> capabilities) { + List<CapabilityDefinition> list = capabilities.stream() + .map(CapabilityDefinition::new) + .collect(toList()); + originCapabilities.put(type, list); + } - private void updatePropertyValues(List<ComponentInstanceProperty> properties, Map<String, UploadPropInfo> newProperties, - Map<String, DataTypeDefinition> allDataTypes) { - properties.forEach(p->updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes)); - } + private void updatePropertyValues(List<ComponentInstanceProperty> properties, + Map<String, UploadPropInfo> newProperties, Map<String, DataTypeDefinition> allDataTypes) { + properties.forEach(p -> updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes)); + } - private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo, - Map<String, DataTypeDefinition> allDataTypes) { - String value = null; - List<GetInputValueDataDefinition> getInputs = null; - boolean isValidate = true; - if (null != propertyInfo && propertyInfo.getValue() != null) { - getInputs = propertyInfo.getGet_input(); - isValidate = getInputs == null || getInputs.isEmpty(); - if (isValidate) { - value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType()); - } else { - value = getPropertyJsonStringValue(propertyInfo.getValue(), - TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); - } - } - property.setValue(value); + private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo, + Map<String, DataTypeDefinition> allDataTypes) { + String value = null; + List<GetInputValueDataDefinition> getInputs = null; + boolean isValidate = true; + if (null != propertyInfo && propertyInfo.getValue() != null) { + getInputs = propertyInfo.getGet_input(); + isValidate = getInputs == null || getInputs.isEmpty(); + if (isValidate) { + value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType()); + } else { + value = getPropertyJsonStringValue(propertyInfo.getValue(), + TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); + } + } + property.setValue(value); return validatePropValueBeforeCreate(property, value, isValidate, allDataTypes); - } + } - private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource, - Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) { - Either<Resource, StorageOperationStatus> updateRes = null; - Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>(); - Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>(); - StorageOperationStatus status = toscaOperationFacade - .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId()); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - log.debug( - "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}", - resource.getUniqueId(), status); - updateRes = Either.right(status); - } - if (updateRes == null) { - fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap, - updatedInstCapabilities, updatedInstRequirements); - status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, - resource.getUniqueId()); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - log.debug( - "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}", - resource.getUniqueId(), status); - updateRes = Either.right(status); - } - } - if (updateRes == null) { - updateRes = Either.left(resource); - } - return updateRes; - } + private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource, + Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) { + Either<Resource, StorageOperationStatus> updateRes = null; + Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>(); + Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>(); + StorageOperationStatus status = toscaOperationFacade + .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId()); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + log.debug( + "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}", + resource.getUniqueId(), status); + updateRes = Either.right(status); + } + if (updateRes == null) { + fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap, + updatedInstCapabilities, updatedInstRequirements); + status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, + updatedInstRequirements, resource); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + log.debug( + "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}", + resource.getUniqueId(), status); + updateRes = Either.right(status); + } + } + if (updateRes == null) { + updateRes = Either.left(resource); + } + return updateRes; + } - private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances, - Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, - Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities, - Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) { - - componentInstances.stream().forEach(i -> { - fillUpdatedInstCapabilities(updatedInstCapabilities, i, - uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate()); - fillUpdatedInstRequirements(updatedInstRequirements, i, - uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate()); - }); - } + private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances, + Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, + Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities, + Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) { + + componentInstances.stream() + .forEach(i -> { + fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName()) + .getCapabilitiesNamesToUpdate()); + fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName()) + .getRequirementsNamesToUpdate()); + }); + } - private void fillUpdatedInstRequirements( - Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements, - ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) { - Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>(); - Set<String> updatedReqNames = new HashSet<>(); - if (isNotEmpty(requirementsNamesToUpdate)) { - for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) { - updatedRequirements.put(requirements.getKey(), - requirements.getValue().stream() - .filter(r -> requirementsNamesToUpdate.containsKey(r.getName()) - && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName()))) - .map(r -> { - r.setParentName(r.getName()); - r.setName(requirementsNamesToUpdate.get(r.getName())); - updatedReqNames.add(r.getName()); - return r; - }).collect(toList())); - } - } - if (isNotEmpty(updatedRequirements)) { - updatedInstRequirements.put(instance, updatedRequirements); - } - } + private void fillUpdatedInstRequirements( + Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements, + ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) { + Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>(); + Set<String> updatedReqNames = new HashSet<>(); + if (isNotEmpty(requirementsNamesToUpdate)) { + for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements() + .entrySet()) { + updatedRequirements.put(requirements.getKey(), requirements.getValue() + .stream() + .filter(r -> requirementsNamesToUpdate.containsKey(r.getName()) + && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName()))) + .map(r -> { + r.setParentName(r.getName()); + r.setName(requirementsNamesToUpdate.get(r.getName())); + updatedReqNames.add(r.getName()); + return r; + }) + .collect(toList())); + } + } + if (isNotEmpty(updatedRequirements)) { + updatedInstRequirements.put(instance, updatedRequirements); + } + } - private void fillUpdatedInstCapabilities( - Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties, - ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) { - Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>(); - Set<String> updatedCapNames = new HashSet<>(); - if (isNotEmpty(capabilitiesNamesToUpdate)) { - for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) { - updatedCapabilities.put(requirements.getKey(), - requirements.getValue().stream() - .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName()) - && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName()))) - .map(c -> { - c.setParentName(c.getName()); - c.setName(capabilitiesNamesToUpdate.get(c.getName())); - updatedCapNames.add(c.getName()); - return c; - }).collect(toList())); - } - } - if (isNotEmpty(updatedCapabilities)) { - updatedInstCapabilties.put(instance, updatedCapabilities); - } - } + private void fillUpdatedInstCapabilities( + Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties, + ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) { + Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>(); + Set<String> updatedCapNames = new HashSet<>(); + if (isNotEmpty(capabilitiesNamesToUpdate)) { + for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities() + .entrySet()) { + updatedCapabilities.put(requirements.getKey(), requirements.getValue() + .stream() + .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName()) + && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName()))) + .map(c -> { + c.setParentName(c.getName()); + c.setName(capabilitiesNamesToUpdate.get(c.getName())); + updatedCapNames.add(c.getName()); + return c; + }) + .collect(toList())); + } + } + if (isNotEmpty(updatedCapabilities)) { + updatedInstCapabilties.put(instance, updatedCapabilities); + } + } - private ResponseFormat addRelationToRI(String yamlName, Resource resource, - UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) { - List<ComponentInstance> componentInstancesList = resource.getComponentInstances(); + private ResponseFormat addRelationToRI(String yamlName, Resource resource, + UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) { + List<ComponentInstance> componentInstancesList = resource.getComponentInstances(); - ComponentInstance currentCompInstance = null; + ComponentInstance currentCompInstance = null; - for (ComponentInstance compInstance : componentInstancesList) { + for (ComponentInstance compInstance : componentInstancesList) { - if (compInstance.getName().equals(nodesInfoValue.getName())) { - currentCompInstance = compInstance; - break; - } + if (compInstance.getName() + .equals(nodesInfoValue.getName())) { + currentCompInstance = compInstance; + break; + } - } + } - if (currentCompInstance == null) { - log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), - resource.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError( - COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, - resource.getUniqueId(), ErrorSeverity.ERROR); - return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, - yamlName); - } - String resourceInstanceId = currentCompInstance.getUniqueId(); - - Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements(); - - if (regMap != null) { - Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator(); - - while (nodesRegValue.hasNext()) { - Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next(); - - List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue(); - for (UploadReqInfo uploadRegInfo : uploadRegInfoList) { - log.debug("Going to create relation {}", uploadRegInfo.getName()); - String regName = uploadRegInfo.getName(); - RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef(); - regCapRelDef.setFromNode(resourceInstanceId); - log.debug("try to find available requirement {} ", regName); - Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, - yamlName, nodesInfoValue, currentCompInstance, - uploadRegInfo.getCapabilityName()); - if (eitherReqStatus.isRight()) { - log.debug("failed to find available requirement {} status is {}", regName, - eitherReqStatus.right().value()); - return eitherReqStatus.right().value(); - } - - RequirementDefinition validReq = eitherReqStatus.left().value(); - List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef - .getRelationships(); - if (reqAndRelationshipPairList == null) { - reqAndRelationshipPairList = new ArrayList<>(); - } - RelationshipInfo reqAndRelationshipPair = new RelationshipInfo(); - reqAndRelationshipPair.setRequirement(regName); - reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId()); - reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId()); - RelationshipImpl relationship = new RelationshipImpl(); - relationship.setType(validReq.getCapability()); - reqAndRelationshipPair.setRelationships(relationship); - - ComponentInstance currentCapCompInstance = null; - for (ComponentInstance compInstance : componentInstancesList) { - if (compInstance.getName().equals(uploadRegInfo.getNode())) { - currentCapCompInstance = compInstance; - break; - } - } - - if (currentCapCompInstance == null) { - log.debug("The component instance with name {} not found on resource {} ", - uploadRegInfo.getNode(), resource.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError( - COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, - resource.getUniqueId(), ErrorSeverity.ERROR); - return componentsUtils - .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - } - regCapRelDef.setToNode(currentCapCompInstance.getUniqueId()); - log.debug("try to find aviable Capability req name is {} ", validReq.getName()); - CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, - currentCapCompInstance, uploadRegInfo); - reqAndRelationshipPair.setCapability(aviableCapForRel.getName()); - reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId()); - reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId()); - if (aviableCapForRel == null) { - log.debug("aviable capability was not found. req name is {} component instance is {}", - validReq.getName(), currentCapCompInstance.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError( - "aviable capability was not found. req name is " + validReq.getName() - + " component instance is " + currentCapCompInstance.getUniqueId(), - resource.getUniqueId(), ErrorSeverity.ERROR); - return componentsUtils - .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - } - CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship(); - capReqRel.setRelation(reqAndRelationshipPair); - reqAndRelationshipPairList.add(capReqRel); - regCapRelDef.setRelationships(reqAndRelationshipPairList); - relations.add(regCapRelDef); - } - } - } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) { - return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName); - } - return componentsUtils.getResponseFormat(ActionStatus.OK); - } + if (currentCompInstance == null) { + log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId()); + BeEcompErrorManager.getInstance() + .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, + resource.getUniqueId(), ErrorSeverity.ERROR); + return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + } + String resourceInstanceId = currentCompInstance.getUniqueId(); + + Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements(); + + if (regMap != null) { + Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet() + .iterator(); + + while (nodesRegValue.hasNext()) { + Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next(); + + List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue(); + for (UploadReqInfo uploadRegInfo : uploadRegInfoList) { + log.debug("Going to create relation {}", uploadRegInfo.getName()); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Started to create relations on instance: {}",uploadRegInfo.getName()); + String regName = uploadRegInfo.getName(); + RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef(); + regCapRelDef.setFromNode(resourceInstanceId); + log.debug("try to find available requirement {} ", regName); + Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, + yamlName, nodesInfoValue, currentCompInstance, uploadRegInfo.getCapabilityName()); + if (eitherReqStatus.isRight()) { + log.debug("failed to find available requirement {} status is {}", regName, + eitherReqStatus.right() + .value()); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR while search available requirement {} status is: {}",regName,eitherReqStatus.right().value()); + return eitherReqStatus.right() + .value(); + } + + RequirementDefinition validReq = eitherReqStatus.left() + .value(); + List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef + .getRelationships(); + if (reqAndRelationshipPairList == null) { + reqAndRelationshipPairList = new ArrayList<>(); + } + RelationshipInfo reqAndRelationshipPair = new RelationshipInfo(); + reqAndRelationshipPair.setRequirement(regName); + reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId()); + reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId()); + RelationshipImpl relationship = new RelationshipImpl(); + relationship.setType(validReq.getCapability()); + reqAndRelationshipPair.setRelationships(relationship); + + ComponentInstance currentCapCompInstance = null; + for (ComponentInstance compInstance : componentInstancesList) { + if (compInstance.getName() + .equals(uploadRegInfo.getNode())) { + currentCapCompInstance = compInstance; + break; + } + } + + if (currentCapCompInstance == null) { + log.debug("The component instance with name {} not found on resource {} ", + uploadRegInfo.getNode(), resource.getUniqueId()); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR component instance with name: {} not found on resource: {}",uploadRegInfo.getNode(),resource.getUniqueId()); + BeEcompErrorManager.getInstance() + .logInternalDataError( + COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, + resource.getUniqueId(), ErrorSeverity.ERROR); + return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + } + regCapRelDef.setToNode(currentCapCompInstance.getUniqueId()); + log.debug("try to find aviable Capability req name is {} ", validReq.getName()); + CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, + currentCapCompInstance, uploadRegInfo); + reqAndRelationshipPair.setCapability(aviableCapForRel.getName()); + reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId()); + reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId()); + if (aviableCapForRel == null) { + log.debug("aviable capability was not found. req name is {} component instance is {}", + validReq.getName(), currentCapCompInstance.getUniqueId()); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR available capability was not found. req name is: {} component instance is: {}",validReq.getName(),currentCapCompInstance.getUniqueId()); + BeEcompErrorManager.getInstance() + .logInternalDataError( + "aviable capability was not found. req name is " + validReq.getName() + + " component instance is " + currentCapCompInstance.getUniqueId(), + resource.getUniqueId(), ErrorSeverity.ERROR); + return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + } + CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship(); + capReqRel.setRelation(reqAndRelationshipPair); + reqAndRelationshipPairList.add(capReqRel); + regCapRelDef.setRelationships(reqAndRelationshipPairList); + relations.add(regCapRelDef); + } + } + } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) { + return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName); + } + return componentsUtils.getResponseFormat(ActionStatus.OK); + } - private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, - Resource resource, Resource originResource, ComponentInstance currentCompInstance, - Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) { - Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties(); - if (MapUtils.isNotEmpty(propMap)) { - Map<String, InputDefinition> currPropertiesMap = new HashMap<>(); - List<ComponentInstanceInput> instPropList = new ArrayList<>(); - - if (CollectionUtils.isEmpty( originResource.getInputs())) { - log.debug("failed to find properties "); - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND)); - } - originResource.getInputs().forEach(p->addInput(currPropertiesMap, p)); - for (List<UploadPropInfo> propertyList : propMap.values()) { - processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList, propertyList); - } - currPropertiesMap.values().forEach(p->instPropList.add(new ComponentInstanceInput(p))); - instInputs.put(currentCompInstance.getUniqueId(), instPropList); - } - } + private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, + Resource originResource, ComponentInstance currentCompInstance, + Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) { + Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties(); + if (MapUtils.isNotEmpty(propMap)) { + Map<String, InputDefinition> currPropertiesMap = new HashMap<>(); + List<ComponentInstanceInput> instPropList = new ArrayList<>(); + + if (CollectionUtils.isEmpty(originResource.getInputs())) { + log.debug("failed to find properties "); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(),StatusCode.ERROR,"ERROR while try to find properties"); + throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND); + } + originResource.getInputs() + .forEach(p -> addInput(currPropertiesMap, p)); + for (List<UploadPropInfo> propertyList : propMap.values()) { + processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList, + propertyList); + } + currPropertiesMap.values() + .forEach(p -> instPropList.add(new ComponentInstanceInput(p))); + instInputs.put(currentCompInstance.getUniqueId(), instPropList); + } + } - private void processProperty(Resource resource, ComponentInstance currentCompInstance, Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap, List<ComponentInstanceInput> instPropList, List<UploadPropInfo> propertyList) { - UploadPropInfo propertyInfo = propertyList.get(0); - String propName = propertyInfo.getName(); - if (!currPropertiesMap.containsKey(propName)) { - log.debug("failed to find property {} ", propName); - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, - propName)); - } - InputDefinition curPropertyDef = currPropertiesMap.get(propName); - ComponentInstanceInput property = null; - - String value = null; - List<GetInputValueDataDefinition> getInputs = null; - boolean isValidate = true; - if (propertyInfo.getValue() != null) { - getInputs = propertyInfo.getGet_input(); - isValidate = getInputs == null || getInputs.isEmpty(); - if (isValidate) { - value = getPropertyJsonStringValue(propertyInfo.getValue(), - curPropertyDef.getType()); - } else { - value = getPropertyJsonStringValue(propertyInfo.getValue(), - TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); - } - } - String innerType = null; - property = new ComponentInstanceInput(curPropertyDef, value, null); + private void processProperty(Resource resource, ComponentInstance currentCompInstance, + Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap, + List<ComponentInstanceInput> instPropList, List<UploadPropInfo> propertyList) { + UploadPropInfo propertyInfo = propertyList.get(0); + String propName = propertyInfo.getName(); + if (!currPropertiesMap.containsKey(propName)) { + loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), + StatusCode.ERROR,"ERROR failed to find property: {}",propName); + log.debug("failed to find property {} ", propName); + throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, propName); + } + InputDefinition curPropertyDef = currPropertiesMap.get(propName); + ComponentInstanceInput property = null; + + String value = null; + List<GetInputValueDataDefinition> getInputs = null; + boolean isValidate = true; + if (propertyInfo.getValue() != null) { + getInputs = propertyInfo.getGet_input(); + isValidate = getInputs == null || getInputs.isEmpty(); + if (isValidate) { + value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType()); + } else { + value = getPropertyJsonStringValue(propertyInfo.getValue(), + TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); + } + } + String innerType = null; + property = new ComponentInstanceInput(curPropertyDef, value, null); String validPropertyVAlue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes); - property.setValue(validPropertyVAlue); - - if (isNotEmpty(getInputs)) { - List<GetInputValueDataDefinition> getInputValues = new ArrayList<>(); - for (GetInputValueDataDefinition getInput : getInputs) { - List<InputDefinition> inputs = resource.getInputs(); - if (CollectionUtils.isEmpty(inputs)) { - log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", - property, currentCompInstance.getUniqueId()); - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - Optional<InputDefinition> optional = inputs.stream() - .filter(p -> p.getName().equals(getInput.getInputName())).findAny(); - if (!optional.isPresent()) { - log.debug("Failed to find input {} ", getInput.getInputName()); - // @@TODO error message - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - InputDefinition input = optional.get(); - getInput.setInputId(input.getUniqueId()); - getInputValues.add(getInput); - - GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); - processGetInput(getInputValues, inputs, getInputIndex); - } - property.setGetInputValues(getInputValues); - } - instPropList.add(property); - // delete overriden property - currPropertiesMap.remove(property.getName()); - } + property.setValue(validPropertyVAlue); + + if (isNotEmpty(getInputs)) { + List<GetInputValueDataDefinition> getInputValues = new ArrayList<>(); + for (GetInputValueDataDefinition getInput : getInputs) { + List<InputDefinition> inputs = resource.getInputs(); + if (CollectionUtils.isEmpty(inputs)) { + loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), + StatusCode.ERROR,"ERROR Failed to add property: "+propName+" to resource instance: {}. Inputs list is empty ",currentCompInstance.getUniqueId()); + log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, + currentCompInstance.getUniqueId()); + throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); + } + + Optional<InputDefinition> optional = inputs.stream() + .filter(p -> p.getName() + .equals(getInput.getInputName())) + .findAny(); + if (!optional.isPresent()) { + loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), + StatusCode.ERROR,"ERROR Failed to find input: "+getInput.getInputName()); + log.debug("Failed to find input {} ", getInput.getInputName()); + // @@TODO error message + throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); + } + InputDefinition input = optional.get(); + getInput.setInputId(input.getUniqueId()); + getInputValues.add(getInput); + + GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); + processGetInput(getInputValues, inputs, getInputIndex); + } + property.setGetInputValues(getInputValues); + } + instPropList.add(property); + // delete overriden property + currPropertiesMap.remove(property.getName()); + } - private void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs, GetInputValueDataDefinition getInputIndex) { - Optional<InputDefinition> optional; - if (getInputIndex != null) { - optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())) - .findAny(); - if (!optional.isPresent()) { - log.debug("Failed to find input {} ", getInputIndex.getInputName()); - // @@TODO error message - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - InputDefinition inputIndex = optional.get(); - getInputIndex.setInputId(inputIndex.getUniqueId()); - getInputValues.add(getInputIndex); - } - } + private void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs, + GetInputValueDataDefinition getInputIndex) { + Optional<InputDefinition> optional; + if (getInputIndex != null) { + optional = inputs.stream() + .filter(p -> p.getName() + .equals(getInputIndex.getInputName())) + .findAny(); + if (!optional.isPresent()) { + log.debug("Failed to find input {} ", getInputIndex.getInputName()); + // @@TODO error message + throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); + } + InputDefinition inputIndex = optional.get(); + getInputIndex.setInputId(inputIndex.getUniqueId()); + getInputValues.add(getInputIndex); + } + } - private void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) { - String propName = prop.getName(); - if (!currPropertiesMap.containsKey(propName)) { - currPropertiesMap.put(propName, prop); - } - } + private void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) { + String propName = prop.getName(); + if (!currPropertiesMap.containsKey(propName)) { + currPropertiesMap.put(propName, prop); + } + } - private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, - Resource resource, Resource originResource, ComponentInstance currentCompInstance, - Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) { + private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, + Resource resource, Resource originResource, ComponentInstance currentCompInstance, + Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) { - Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties(); - Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>(); + Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties(); + Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>(); - List<PropertyDefinition> listFromMap = originResource.getProperties(); - if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) { - log.debug("failed to find properties "); - return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND); - } - if (listFromMap == null || listFromMap.isEmpty()) { - return componentsUtils.getResponseFormat(ActionStatus.OK); - } - for (PropertyDefinition prop : listFromMap) { - String propName = prop.getName(); - if (!currPropertiesMap.containsKey(propName)) { - currPropertiesMap.put(propName, prop); - } - } - List<ComponentInstanceProperty> instPropList = new ArrayList<>(); - if (propMap != null && propMap.size() > 0) { - for (List<UploadPropInfo> propertyList : propMap.values()) { - - UploadPropInfo propertyInfo = propertyList.get(0); - String propName = propertyInfo.getName(); - if (!currPropertiesMap.containsKey(propName)) { - log.debug("failed to find property {} ", propName); - return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, - propName); - } - PropertyDefinition curPropertyDef = currPropertiesMap.get(propName); - ComponentInstanceProperty property = null; - - String value = null; - List<GetInputValueDataDefinition> getInputs = null; - boolean isValidate = true; - if (propertyInfo.getValue() != null) { - getInputs = propertyInfo.getGet_input(); - isValidate = getInputs == null || getInputs.isEmpty(); - if (isValidate) { - value = getPropertyJsonStringValue(propertyInfo.getValue(), - curPropertyDef.getType()); - } else { - value = getPropertyJsonStringValue(propertyInfo.getValue(), - TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); - } - } - String innerType = null; - property = new ComponentInstanceProperty(curPropertyDef, value, null); + List<PropertyDefinition> listFromMap = originResource.getProperties(); + if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) { + loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), + StatusCode.ERROR,"ERROR Failed to find properties"); + log.debug("failed to find properties"); + return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND); + } + if (listFromMap == null || listFromMap.isEmpty()) { + return componentsUtils.getResponseFormat(ActionStatus.OK); + } + for (PropertyDefinition prop : listFromMap) { + String propName = prop.getName(); + if (!currPropertiesMap.containsKey(propName)) { + currPropertiesMap.put(propName, prop); + } + } + List<ComponentInstanceProperty> instPropList = new ArrayList<>(); + if (propMap != null && propMap.size() > 0) { + for (List<UploadPropInfo> propertyList : propMap.values()) { + + UploadPropInfo propertyInfo = propertyList.get(0); + String propName = propertyInfo.getName(); + if (!currPropertiesMap.containsKey(propName)) { + log.debug("failed to find property {} ", propName); + loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR Failed to find property: {}",propName); + return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName); + } + PropertyDefinition curPropertyDef = currPropertiesMap.get(propName); + ComponentInstanceProperty property = null; + + String value = null; + List<GetInputValueDataDefinition> getInputs = null; + boolean isValidate = true; + if (propertyInfo.getValue() != null) { + getInputs = propertyInfo.getGet_input(); + isValidate = getInputs == null || getInputs.isEmpty(); + if (isValidate) { + value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType()); + } else { + value = getPropertyJsonStringValue(propertyInfo.getValue(), + TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); + } + } + String innerType = null; + property = new ComponentInstanceProperty(curPropertyDef, value, null); String validatePropValue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes); - property.setValue(validatePropValue); - - if (getInputs != null && !getInputs.isEmpty()) { - List<GetInputValueDataDefinition> getInputValues = new ArrayList<>(); - for (GetInputValueDataDefinition getInput : getInputs) { - List<InputDefinition> inputs = resource.getInputs(); - if (inputs == null || inputs.isEmpty()) { - log.debug("Failed to add property {} to instance. Inputs list is empty ", property); - rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues() - .stream() - .map(GetInputValueDataDefinition::getInputName) - .collect(toList()).toString()); - } - InputDefinition input = findInputByName(inputs, getInput); - getInput.setInputId(input.getUniqueId()); - getInputValues.add(getInput); - - GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); - if (getInputIndex != null) { - input = findInputByName(inputs, getInputIndex); - getInputIndex.setInputId(input.getUniqueId()); - getInputValues.add(getInputIndex); - - } - - } - property.setGetInputValues(getInputValues); - } - instPropList.add(property); - // delete overriden property - currPropertiesMap.remove(property.getName()); - } - } - // add rest of properties - if (!currPropertiesMap.isEmpty()) { - for (PropertyDefinition value : currPropertiesMap.values()) { - instPropList.add(new ComponentInstanceProperty(value)); - } - } - instProperties.put(currentCompInstance.getUniqueId(), instPropList); - return componentsUtils.getResponseFormat(ActionStatus.OK); - } + property.setValue(validatePropValue); + + if (getInputs != null && !getInputs.isEmpty()) { + List<GetInputValueDataDefinition> getInputValues = new ArrayList<>(); + for (GetInputValueDataDefinition getInput : getInputs) { + List<InputDefinition> inputs = resource.getInputs(); + if (inputs == null || inputs.isEmpty()) { + log.debug("Failed to add property {} to instance. Inputs list is empty ", property); + loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"Failed to add property: {} to instance. Inputs list is empty",propName); + rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues() + .stream() + .map(GetInputValueDataDefinition::getInputName) + .collect(toList()) + .toString()); + } + InputDefinition input = findInputByName(inputs, getInput); + getInput.setInputId(input.getUniqueId()); + getInputValues.add(getInput); + + GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); + if (getInputIndex != null) { + input = findInputByName(inputs, getInputIndex); + getInputIndex.setInputId(input.getUniqueId()); + getInputValues.add(getInputIndex); + + } + + } + property.setGetInputValues(getInputValues); + } + instPropList.add(property); + // delete overriden property + currPropertiesMap.remove(property.getName()); + } + } + // add rest of properties + if (!currPropertiesMap.isEmpty()) { + for (PropertyDefinition value : currPropertiesMap.values()) { + instPropList.add(new ComponentInstanceProperty(value)); + } + } + instProperties.put(currentCompInstance.getUniqueId(), instPropList); + return componentsUtils.getResponseFormat(ActionStatus.OK); + } - // US740820 Relate RIs according to capability name - private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, - ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) { - if (null == uploadReqInfo.getCapabilityName() - || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {// get - // by - // capability - // type - return findAvailableCapability(validReq, currentCapCompInstance); - } - return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo); - } + // US740820 Relate RIs according to capability name + private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, + ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) { + if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability() + .equals(uploadReqInfo.getCapabilityName())) {// get + // by + // capability + // type + return findAvailableCapability(validReq, currentCapCompInstance); + } + return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo); + } - private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, - ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) { - CapabilityDefinition cap = null; - Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities(); - if (!capMap.containsKey(validReq.getCapability())) { - return null; - } - Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream() - .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny(); - if (!capByName.isPresent()) { - return null; - } - cap = capByName.get(); + private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, + ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) { + CapabilityDefinition cap = null; + Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities(); + if (!capMap.containsKey(validReq.getCapability())) { + return null; + } + Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()) + .stream() + .filter(p -> p.getName() + .equals(uploadReqInfo.getCapabilityName())) + .findAny(); + if (!capByName.isPresent()) { + return null; + } + cap = capByName.get(); - if (isBoundedByOccurrences(cap)) { - String leftOccurrences = cap.getLeftOccurrences(); - int left = Integer.parseInt(leftOccurrences); - if (left > 0) { - --left; - cap.setLeftOccurrences(String.valueOf(left)); + if (isBoundedByOccurrences(cap)) { + String leftOccurrences = cap.getLeftOccurrences(); + int left = Integer.parseInt(leftOccurrences); + if (left > 0) { + --left; + cap.setLeftOccurrences(String.valueOf(left)); - } + } - } - return cap; - } + } + return cap; + } - private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) { - Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities(); - if (capMap.containsKey(validReq.getCapability())) { - List<CapabilityDefinition> capList = capMap.get(validReq.getCapability()); - - for (CapabilityDefinition cap : capList) { - if (isBoundedByOccurrences(cap)) { - String leftOccurrences = cap.getLeftOccurrences() != null ? - cap.getLeftOccurrences() : cap.getMaxOccurrences(); - int left = Integer.parseInt(leftOccurrences); - if (left > 0) { - --left; - cap.setLeftOccurrences(String.valueOf(left)); - return cap; - } - } else { - return cap; - } - } - } - return null; - } + private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) { + Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities(); + if (capMap.containsKey(validReq.getCapability())) { + List<CapabilityDefinition> capList = capMap.get(validReq.getCapability()); + + for (CapabilityDefinition cap : capList) { + if (isBoundedByOccurrences(cap)) { + String leftOccurrences = cap.getLeftOccurrences() != null ? cap.getLeftOccurrences() + : cap.getMaxOccurrences(); + int left = Integer.parseInt(leftOccurrences); + if (left > 0) { + --left; + cap.setLeftOccurrences(String.valueOf(left)); + return cap; + } + } else { + return cap; + } + } + } + return null; + } - private boolean isBoundedByOccurrences(CapabilityDefinition cap) { - return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES); - } + private boolean isBoundedByOccurrences(CapabilityDefinition cap) { + return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences() + .equals(CapabilityDataDefinition.MAX_OCCURRENCES); + } - private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName, - UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, - String capName) { - Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements(); - List<RequirementDefinition> list = comInstRegDefMap.get(capName); - RequirementDefinition validRegDef = null; - if (list == null) { - for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) { - for (RequirementDefinition reqDef : entry.getValue()) { - if (reqDef.getName().equals(regName)) { - if (reqDef.getMaxOccurrences() != null - && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { - String leftOccurrences = reqDef.getLeftOccurrences(); - if (leftOccurrences == null) { - leftOccurrences = reqDef.getMaxOccurrences(); - } - int left = Integer.parseInt(leftOccurrences); - if (left > 0) { - --left; - reqDef.setLeftOccurrences(String.valueOf(left)); - validRegDef = reqDef; - break; - } else { - continue; - } - } else { - validRegDef = reqDef; - break; - } - - } - } - if (validRegDef != null) { - break; - } - } - } else { - for (RequirementDefinition reqDef : list) { - if (reqDef.getName().equals(regName)) { - if (reqDef.getMaxOccurrences() != null - && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { - String leftOccurrences = reqDef.getLeftOccurrences(); - if (leftOccurrences == null) { - leftOccurrences = reqDef.getMaxOccurrences(); - } - int left = Integer.parseInt(leftOccurrences); - if (left > 0) { - --left; - reqDef.setLeftOccurrences(String.valueOf(left)); - validRegDef = reqDef; - break; - } else { - continue; - } - } else { - validRegDef = reqDef; - break; - } - } - } - } - if (validRegDef == null) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, - yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - return Either.right(responseFormat); - } - return Either.left(validRegDef); - } + private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName, + UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, + String capName) { + Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements(); + List<RequirementDefinition> list = comInstRegDefMap.get(capName); + RequirementDefinition validRegDef = null; + if (list == null) { + for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) { + for (RequirementDefinition reqDef : entry.getValue()) { + if (reqDef.getName() + .equals(regName)) { + if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences() + .equals(RequirementDataDefinition.MAX_OCCURRENCES)) { + String leftOccurrences = reqDef.getLeftOccurrences(); + if (leftOccurrences == null) { + leftOccurrences = reqDef.getMaxOccurrences(); + } + int left = Integer.parseInt(leftOccurrences); + if (left > 0) { + --left; + reqDef.setLeftOccurrences(String.valueOf(left)); + validRegDef = reqDef; + break; + } else { + continue; + } + } else { + validRegDef = reqDef; + break; + } + + } + } + if (validRegDef != null) { + break; + } + } + } else { + for (RequirementDefinition reqDef : list) { + if (reqDef.getName() + .equals(regName)) { + if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences() + .equals(RequirementDataDefinition.MAX_OCCURRENCES)) { + String leftOccurrences = reqDef.getLeftOccurrences(); + if (leftOccurrences == null) { + leftOccurrences = reqDef.getMaxOccurrences(); + } + int left = Integer.parseInt(leftOccurrences); + if (left > 0) { + --left; + reqDef.setLeftOccurrences(String.valueOf(left)); + validRegDef = reqDef; + break; + } else { + continue; + } + } else { + validRegDef = reqDef; + break; + } + } + } + } + if (validRegDef == null) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, + yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + return Either.right(responseFormat); + } + return Either.left(validRegDef); + } - private Resource createResourceInstances(String yamlName, Resource resource, - Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, - Map<String, Resource> nodeNamespaceMap) { + private Resource createResourceInstances(String yamlName, Resource resource, Resource oldResource, + Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingNodeTypesByResourceNames) { - Either<Resource, ResponseFormat> eitherResource = null; - log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName); + Either<Resource, ResponseFormat> eitherResource; + log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName); if (isEmpty(uploadResInstancesMap) && resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE); throw new ByResponseFormatComponentException(responseFormat); - } - Map<String, Resource> existingNodeTypeMap = new HashMap<>(); - if (MapUtils.isNotEmpty(nodeNamespaceMap)) { - nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v)); - } - Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>(); - uploadResInstancesMap - .values() - .forEach(i->createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap)); - - if (isNotEmpty(resourcesInstancesMap)) { - StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource, - resourcesInstancesMap, false); - if (status != null && status != StorageOperationStatus.OK) { - log.debug("Failed to add component instances to container component {}", resource.getName()); - ResponseFormat responseFormat = componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(status)); - eitherResource = Either.right(responseFormat); - throw new ByResponseFormatComponentException(eitherResource.right().value()); - } - } - log.debug("*************Going to get resource {}", resource.getUniqueId()); - Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade - .getToscaElement(resource.getUniqueId(), getComponentWithInstancesFilter()); - log.debug("*************finished to get resource {}", resource.getUniqueId()); - if (eitherGetResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); - throw new ByResponseFormatComponentException(responseFormat); - } - if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances()) && - resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances - log.debug("Error when create resource instance from csar. ComponentInstances list empty"); - BeEcompErrorManager.getInstance().logBeDaoSystemError( - "Error when create resource instance from csar. ComponentInstances list empty"); - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE)); - } - return eitherGetResource.left().value(); - } + } + if (MapUtils.isNotEmpty(nodeNamespaceMap)) { + nodeNamespaceMap.forEach((k, v) -> existingNodeTypesByResourceNames.put(v.getToscaResourceName(), v)); + } + Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>(); + uploadResInstancesMap.values() + .forEach(i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, + existingNodeTypesByResourceNames, resourcesInstancesMap)); + if (oldResource != null && oldResource.getResourceType() != ResourceTypeEnum.CVFC && oldResource.getComponentInstances() != null) { + Map<String, Resource> existingNodeTypesByUids = existingNodeTypesByResourceNames.values() + .stream() + .collect(toMap(Resource::getUniqueId, r -> r)); + oldResource.getComponentInstances() + .stream() + .filter(i -> !i.isCreatedFromCsar()) + .forEach(uiInst -> resourcesInstancesMap.put(uiInst, + getOriginResource(existingNodeTypesByUids, uiInst))); + } - private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName, - Resource resource, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap, Map<ComponentInstance, Resource> resourcesInstancesMap) { - Either<Resource, ResponseFormat> eitherResource; - log.debug("*************Going to create resource instances {}", yamlName); - // updating type if the type is node type name - we need to take the - // updated name - log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName()); - if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) { - uploadComponentInstanceInfo - .setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName()); - } - Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, - existingnodeTypeMap); + if (isNotEmpty(resourcesInstancesMap)) { + try { + toscaOperationFacade.associateComponentInstancesToComponent(resource, + resourcesInstancesMap, false, oldResource != null); + } catch (StorageException exp) { + if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) { + log.debug("Failed to add component instances to container component {}", resource.getName()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus())); + eitherResource = Either.right(responseFormat); + throw new ByResponseFormatComponentException(eitherResource.right().value()); + } + } + } + if (CollectionUtils.isEmpty(resource.getComponentInstances()) && + resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances + log.debug("Error when create resource instance from csar. ComponentInstances list empty"); + BeEcompErrorManager.getInstance() + .logBeDaoSystemError( + "Error when create resource instance from csar. ComponentInstances list empty"); + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE)); + } + return resource; + } - ComponentInstance componentInstance = new ComponentInstance(); - componentInstance.setComponentUid(refResource.getUniqueId()); + private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName, + Resource resource, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap, + Map<ComponentInstance, Resource> resourcesInstancesMap) { + Either<Resource, ResponseFormat> eitherResource; + log.debug("*************Going to create resource instances {}", yamlName); + // updating type if the type is node type name - we need to take the + // updated name + log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName()); + if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) { + uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()) + .getToscaResourceName()); + } + Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, + existingnodeTypeMap); + ComponentInstance componentInstance = new ComponentInstance(); + componentInstance.setComponentUid(refResource.getUniqueId()); Collection<String> directives = uploadComponentInstanceInfo.getDirectives(); if(directives != null && !directives.isEmpty()) { componentInstance.setDirectives(new ArrayList<>(directives)); @@ -3135,18 +3606,16 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { componentInstance.setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo, componentInstance.getUniqueId())); } - ComponentTypeEnum containerComponentType = resource.getComponentType(); - NodeTypeEnum containerNodeType = containerComponentType.getNodeType(); - if (containerNodeType.equals(NodeTypeEnum.Resource) - && isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) - && isNotEmpty(refResource.getCapabilities())) { - setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities()); - Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities( - refResource.getUniqueId(), refResource.getCapabilities(), - uploadComponentInstanceInfo.getCapabilities()); - componentInstance.setCapabilities(validComponentInstanceCapabilities); - } + NodeTypeEnum containerNodeType = containerComponentType.getNodeType(); + if (containerNodeType == NodeTypeEnum.Resource && isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) + && isNotEmpty(refResource.getCapabilities())) { + setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities()); + Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities( + refResource.getUniqueId(), refResource.getCapabilities(), + uploadComponentInstanceInfo.getCapabilities()); + componentInstance.setCapabilities(validComponentInstanceCapabilities); + } if (isNotEmpty(uploadComponentInstanceInfo.getArtifacts())) { Map<String, Map<String, UploadArtifactInfo>> artifacts = uploadComponentInstanceInfo.getArtifacts(); @@ -3164,1588 +3633,1720 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { componentInstance.setToscaArtifacts(toscaArtifacts); } - if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) { - log.debug( - "createResourceInstances - not found lates version for resource instance with name {} and type ", - uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, - yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - throw new ByResponseFormatComponentException(responseFormat); - } - Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType()); - componentInstance.setName(uploadComponentInstanceInfo.getName()); - componentInstance.setIcon(origResource.getIcon()); - resourcesInstancesMap.put(componentInstance, origResource); - } - - private ComponentParametersView getComponentWithInstancesFilter() { - ComponentParametersView parametersView = new ComponentParametersView(); - parametersView.disableAll(); - parametersView.setIgnoreComponentInstances(false); - parametersView.setIgnoreInputs(false); - // inputs are read when creating - // property values on instances - parametersView.setIgnoreUsers(false); - return parametersView; - } - - private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities, - Map<String, List<UploadCapInfo>> uploadedCapabilities) { - for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) { - if (originCapabilities.containsKey(currEntry.getKey())) { - currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey())); - } - } - for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) { - capabilities.getValue().stream().forEach(cap -> { - if (uploadedCapabilities.containsKey(cap.getName())) { - uploadedCapabilities.get(cap.getName()).stream().forEach(c -> { - c.setName(cap.getName()); - c.setType(cap.getType()); - }); - } - }); - } + if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) { + log.debug("createResourceInstances - not found lates version for resource instance with name {} and type ", + uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, + yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + } + Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType()); + componentInstance.setName(uploadComponentInstanceInfo.getName()); + componentInstance.setIcon(origResource.getIcon()); + componentInstance.setCreatedFrom(CreatedFrom.CSAR); + resourcesInstancesMap.put(componentInstance, origResource); + } - } + private ComponentParametersView getComponentWithInstancesFilter() { + ComponentParametersView parametersView = new ComponentParametersView(); + parametersView.disableAll(); + parametersView.setIgnoreComponentInstances(false); + parametersView.setIgnoreInputs(false); + // inputs are read when creating + // property values on instances + parametersView.setIgnoreUsers(false); + return parametersView; + } - private Resource validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, - Map<String, Resource> nodeNamespaceMap) { - - log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create", - uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - Resource refResource; - if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) { - refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()); - } else { - Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade - .getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType()); - if (findResourceEither.isRight()) { - log.debug( - "validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type ", - uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(findResourceEither.right().value())); - throw new ByResponseFormatComponentException(responseFormat); - } - refResource = findResourceEither.left().value(); - nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource); - } - String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState(); - if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - log.debug( - "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.", - refResource.getName(), componentState); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, - refResource.getComponentType().getValue(), refResource.getName(), componentState); - throw new ByResponseFormatComponentException(responseFormat); - } + private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities, + Map<String, List<UploadCapInfo>> uploadedCapabilities) { + for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) { + if (originCapabilities.containsKey(currEntry.getKey())) { + currEntry.getValue() + .stream() + .forEach(cap -> cap.setType(currEntry.getKey())); + } + } + for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) { + capabilities.getValue() + .stream() + .forEach(cap -> { + if (uploadedCapabilities.containsKey(cap.getName())) { + uploadedCapabilities.get(cap.getName()) + .stream() + .forEach(c -> { + c.setName(cap.getName()); + c.setType(cap.getType()); + }); + } + }); + } + } - if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) { - log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, - yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - throw new ByResponseFormatComponentException(responseFormat); - } - return refResource; - } + private Resource validateResourceInstanceBeforeCreate(String yamlName, + UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeNamespaceMap) { + + log.debug( + "validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type {} before create", + uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + Resource refResource; + if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) { + refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()); + } else { + Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade + .getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType()); + if (findResourceEither.isRight()) { + log.debug( + "validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type {}", + uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(findResourceEither.right().value())); + } + refResource = findResourceEither.left().value(); + nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource); + } + String componentState = refResource.getComponentMetadataDefinition() + .getMetadataDataDefinition() + .getState(); + if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + log.debug( + "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.", + refResource.getName(), componentState); + throw new ByActionStatusComponentException(ActionStatus.ILLEGAL_COMPONENT_STATE, + refResource.getComponentType().getValue(),refResource.getName(), componentState); + } + if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) { + log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType()); + throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, + yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + } + return refResource; + } - public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource, - LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock, - boolean forceCertificationAllowed) { + public Resource propagateStateToCertified(User user, Resource resource, + LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock, + boolean forceCertificationAllowed) { - Either<Resource, ResponseFormat> result = null; - try { - if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed - && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) { - result = nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock); - if (result.isRight()) { - return result; - } - resource = result.left().value(); - } - if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) { - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts( - resource, user, false, inTransaction, needLock); - result = eitherPopulated.isLeft() ? Either.left(resource) - : Either.right(eitherPopulated.right().value()); - return result; - } - return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock); - } catch (Exception e) { - log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } finally { - if (result == null || result.isRight()) { - BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify"); - if (!inTransaction) { + boolean failed = false; + try { + if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed + && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) { + nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock); + } + if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) { + Either<ArtifactDefinition, Operation> eitherPopulated = populateToscaArtifacts( + resource, user, false, inTransaction, needLock, false); + return resource; + } + return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock); + } catch (ComponentException e) { + failed = true; + log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e); + throw e; + } finally { + if (failed) { + BeEcompErrorManager.getInstance() + .logBeSystemError("Change LifecycleState - Certify"); + if (!inTransaction) { janusGraphDao.rollback(); - } - } else if (!inTransaction) { + } + } else if (!inTransaction) { janusGraphDao.commit(); - } - } - } + } + } + } - private Either<Resource, ResponseFormat> nodeFullCertification(String uniqueId, User user, - LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) { - return lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, - lifecycleChangeInfo, inTransaction, needLock); - } + private Resource nodeFullCertification(String uniqueId, User user, + LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) { + Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, + inTransaction, needLock); + if(resourceResponse.isRight()){ + throw new ByResponseFormatComponentException(resourceResponse.right().value()); + } + return resourceResponse.left().value(); + } - private Either<Resource, ResponseFormat> nodeForceCertification(Resource resource, User user, - LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) { - return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, - needLock); - } + private Resource nodeForceCertification(Resource resource, User user, + LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) { + return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, + needLock); + } - public ImmutablePair<Resource, ActionStatus> createOrUpdateResourceByImport( - Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock, - CsarInfo csarInfo, String nodeName, boolean isNested) { - - ImmutablePair<Resource, ActionStatus> result = null; - // check if resource already exists (search by tosca name = type) - boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName); - Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade - .getLatestByToscaResourceName(resource.getToscaResourceName()); - - if (latestByToscaName.isLeft()) { - Resource foundResource = latestByToscaName.left().value(); - // we don't allow updating names of top level types - if (!isNestedResource && - !StringUtils.equals(resource.getName(), foundResource.getName())) { - BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import", - ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); - log.debug("resource already exist new name={} old name={} same type={}", resource.getName(), - foundResource.getName(), resource.getToscaResourceName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS); - componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE); - throwComponentException(responseFormat); - } - result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested); - } else if (isNotFound(latestByToscaName)) { - if (isNestedResource) { - result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo, isNested, nodeName); - } else { - result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo); - } - } else { - StorageOperationStatus status = latestByToscaName.right().value(); - log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(latestByToscaName.right().value()), resource); - componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE); - throwComponentException(responseFormat); - } - return result; - } + public ImmutablePair<Resource, ActionStatus> createOrUpdateResourceByImport(Resource resource, User user, + boolean isNormative, boolean isInTransaction, boolean needLock, CsarInfo csarInfo, String nodeName, + boolean isNested) { + + ImmutablePair<Resource, ActionStatus> result = null; + // check if resource already exists (search by tosca name = type) + boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName); + Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade + .getLatestByToscaResourceName(resource.getToscaResourceName()); + + if (latestByToscaName.isLeft()) { + Resource foundResource = latestByToscaName.left() + .value(); + // we don't allow updating names of top level types + if (!isNestedResource && !StringUtils.equals(resource.getName(), foundResource.getName())) { + BeEcompErrorManager.getInstance() + .logBeComponentMissingError("Create / Update resource by import", + ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); + log.debug("resource already exist new name={} old name={} same type={}", resource.getName(), + foundResource.getName(), resource.getToscaResourceName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS); + componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE); + throwComponentException(responseFormat); + } + result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested); + } else if (isNotFound(latestByToscaName)) { + if (isNestedResource) { + result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo, + isNested, nodeName); + } else { + result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo); + } + } else { + StorageOperationStatus status = latestByToscaName.right() + .value(); + log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status); + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(latestByToscaName.right() + .value()), resource); + componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE); + throwComponentException(responseFormat); + } + return result; + } - private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) { - return csarInfo != null && csarInfo.isUpdate() && nodeName != null; - } + private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) { + return csarInfo != null && csarInfo.isUpdate() && nodeName != null; + } - private ImmutablePair<Resource, ActionStatus> createOrUpdateNestedResource(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock, CsarInfo csarInfo, boolean isNested, String nodeName) { - Either<Component, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(buildNestedToscaResourceName( - resource.getResourceType().name(), csarInfo.getVfResourceName(), nodeName).getRight()); - if (latestByToscaName.isLeft()) { - Resource nestedResource = (Resource) latestByToscaName.left().value(); - log.debug(VALIDATE_DERIVED_BEFORE_UPDATE); - Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource, resource, - ValidationUtils.hasBeenCertified(nestedResource.getVersion())); - if (eitherValidation.isRight()) { - return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo); - } - return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested); - } else { - return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo); - } - } + private ImmutablePair<Resource, ActionStatus> createOrUpdateNestedResource(Resource resource, User user, + boolean isNormative, boolean isInTransaction, boolean needLock, CsarInfo csarInfo, boolean isNested, + String nodeName) { + Either<Component, StorageOperationStatus> latestByToscaName = toscaOperationFacade + .getLatestByToscaResourceName(buildNestedToscaResourceName(resource.getResourceType() + .name(), csarInfo.getVfResourceName(), nodeName).getRight()); + if (latestByToscaName.isLeft()) { + Resource nestedResource = (Resource) latestByToscaName.left() + .value(); + log.debug(VALIDATE_DERIVED_BEFORE_UPDATE); + Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource, + resource, ValidationUtils.hasBeenCertified(nestedResource.getVersion())); + if (eitherValidation.isRight()) { + return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo); + } + return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested); + } else { + return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo); + } + } - private boolean isNotFound(Either<Resource, StorageOperationStatus> getResourceEither) { - return getResourceEither.isRight() && getResourceEither.right().value() == StorageOperationStatus.NOT_FOUND; - } + private boolean isNotFound(Either<Resource, StorageOperationStatus> getResourceEither) { + return getResourceEither.isRight() && getResourceEither.right() + .value() == StorageOperationStatus.NOT_FOUND; + } - private ImmutablePair<Resource, ActionStatus> createResourceByImport(Resource resource, - User user, boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) { - log.debug("resource with name {} does not exist. create new resource", resource.getName()); - validateResourceBeforeCreate(resource, user, - AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo); - Resource createdResource = createResourceByDao(resource, user, - AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction); - ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createdResource, - ActionStatus.CREATED); - ASDCKpiApi.countImportResourcesKPI(); - return resourcePair; - } + private ImmutablePair<Resource, ActionStatus> createResourceByImport(Resource resource, User user, + boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) { + log.debug("resource with name {} does not exist. create new resource", resource.getName()); + validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo); + final Resource createResourceByDao = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, + isInTransaction); + Resource createdResource = updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Resource)r).left().value(); + ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createdResource, ActionStatus.CREATED); + ASDCKpiApi.countImportResourcesKPI(); + return resourcePair; + } - public boolean isResourceExist(String resourceName) { - Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName); - return latestByName.isLeft(); - } + public boolean isResourceExist(String resourceName) { + Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName); + return latestByName.isLeft(); + } - private ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport( - Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock, - boolean isNested) { - String lockedResourceId = oldResource.getUniqueId(); - log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, - oldResource.getVersion(), oldResource.getLifecycleState()); - ImmutablePair<Resource, ActionStatus> resourcePair = null; - try { - lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import"); - oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false); - mergeOldResourceMetadataWithNew(oldResource, newResource); - - validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested); - validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction); - // contact info normalization - newResource.setContactId(newResource.getContactId().toLowerCase()); - // non-updatable fields - newResource.setCreatorUserId(user.getUserId()); - newResource.setCreatorFullName(user.getFullName()); - newResource.setLastUpdaterUserId(user.getUserId()); - newResource.setLastUpdaterFullName(user.getFullName()); - newResource.setUniqueId(oldResource.getUniqueId()); - newResource.setVersion(oldResource.getVersion()); - newResource.setInvariantUUID(oldResource.getInvariantUUID()); - newResource.setLifecycleState(oldResource.getLifecycleState()); - newResource.setUUID(oldResource.getUUID()); - newResource.setNormalizedName(oldResource.getNormalizedName()); - newResource.setSystemName(oldResource.getSystemName()); - if (oldResource.getCsarUUID() != null) { - newResource.setCsarUUID(oldResource.getCsarUUID()); - } - if (oldResource.getImportedToscaChecksum() != null) { - newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum()); - } - newResource.setAbstract(oldResource.isAbstract()); + private ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(Resource newResource, + Resource oldResource, User user, boolean inTransaction, boolean needLock, boolean isNested) { + String lockedResourceId = oldResource.getUniqueId(); + log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, + oldResource.getVersion(), oldResource.getLifecycleState()); + ImmutablePair<Resource, ActionStatus> resourcePair = null; + try { + lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import"); + oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false); + mergeOldResourceMetadataWithNew(oldResource, newResource); + + validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested); + validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, + AuditingActionEnum.IMPORT_RESOURCE, inTransaction); + // contact info normalization + newResource.setContactId(newResource.getContactId() + .toLowerCase()); + PropertyConstraintsUtils.validatePropertiesConstraints(newResource, oldResource); + // non-updatable fields + newResource.setCreatorUserId(user.getUserId()); + newResource.setCreatorFullName(user.getFullName()); + newResource.setLastUpdaterUserId(user.getUserId()); + newResource.setLastUpdaterFullName(user.getFullName()); + newResource.setUniqueId(oldResource.getUniqueId()); + newResource.setVersion(oldResource.getVersion()); + newResource.setInvariantUUID(oldResource.getInvariantUUID()); + newResource.setLifecycleState(oldResource.getLifecycleState()); + newResource.setUUID(oldResource.getUUID()); + newResource.setNormalizedName(oldResource.getNormalizedName()); + newResource.setSystemName(oldResource.getSystemName()); + if (oldResource.getCsarUUID() != null) { + newResource.setCsarUUID(oldResource.getCsarUUID()); + } + if (oldResource.getImportedToscaChecksum() != null) { + newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum()); + } + newResource.setAbstract(oldResource.isAbstract()); - if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom().isEmpty()) { - newResource.setDerivedFrom(oldResource.getDerivedFrom()); - } - if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType().isEmpty()) { - newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType()); - } - if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion().isEmpty()) { - newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion()); - } - // add for new) - // created without tosca artifacts - add the placeholders - if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) { - setToscaArtifactsPlaceHolders(newResource, user); - } + if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom() + .isEmpty()) { + newResource.setDerivedFrom(oldResource.getDerivedFrom()); + } + if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType() + .isEmpty()) { + newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType()); + } + if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion() + .isEmpty()) { + newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion()); + } + // add for new) + // created without tosca artifacts - add the placeholders + if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts() + .isEmpty()) { + setToscaArtifactsPlaceHolders(newResource, user); + } - if (newResource.getInterfaces() == null || newResource.getInterfaces().isEmpty()) { - newResource.setInterfaces(oldResource.getInterfaces()); - } + if (newResource.getInterfaces() == null || newResource.getInterfaces().isEmpty()) { + newResource.setInterfaces(oldResource.getInterfaces()); + } if (CollectionUtils.isEmpty(newResource.getProperties())) { newResource.setProperties(oldResource.getProperties()); } - Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade - .overrideComponent(newResource, oldResource); - - if (overrideResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource); - componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE); + Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade + .overrideComponent(newResource, oldResource); - throwComponentException(responseFormat); - } + if (overrideResource.isRight()) { + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right() + .value()), newResource); + componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE); - log.debug("Resource updated successfully!!!"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE, - ResourceVersionInfo.newBuilder() - .state(oldResource.getLifecycleState() - .name()) - .version(oldResource.getVersion()) - .build()); - - resourcePair = new ImmutablePair<>(overrideResource.left().value(), - ActionStatus.OK); - return resourcePair; - } finally { - if (resourcePair == null) { - BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify"); - janusGraphDao.rollback(); - } else if (!inTransaction) { + throwComponentException(responseFormat); + } + updateCatalog(overrideResource.left() + .value(), ChangeTypeEnum.LIFECYCLE); + + log.debug("Resource updated successfully!!!"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE, + ResourceVersionInfo.newBuilder() + .state(oldResource.getLifecycleState() + .name()) + .version(oldResource.getVersion()) + .build()); + + resourcePair = new ImmutablePair<>(overrideResource.left() + .value(), ActionStatus.OK); + return resourcePair; + } finally { + if (resourcePair == null) { + BeEcompErrorManager.getInstance() + .logBeSystemError("Change LifecycleState - Certify"); + janusGraphDao.rollback(); + } else if (!inTransaction) { janusGraphDao.commit(); - } - if (needLock) { - log.debug("unlock resource {}", lockedResourceId); - graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource); - } - } - - } + } + if (needLock) { + log.debug("unlock resource {}", lockedResourceId); + graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource); + } + } - /** - * Merge old resource with new. Keep old category and vendor name without - * change - * - * @param oldResource - * @param newResource - */ - private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) { - - // keep old category and vendor name without change - // merge the rest of the resource metadata - if (newResource.getTags() == null || newResource.getTags().isEmpty()) { - newResource.setTags(oldResource.getTags()); - } + } - if (newResource.getDescription() == null) { - newResource.setDescription(oldResource.getDescription()); - } + /** + * Merge old resource with new. Keep old category and vendor name without + * change + * + * @param oldResource + * @param newResource + */ + private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) { + + // keep old category and vendor name without change + // merge the rest of the resource metadata + if (newResource.getTags() == null || newResource.getTags().isEmpty()) { + newResource.setTags(oldResource.getTags()); + } - if (newResource.getVendorRelease() == null) { - newResource.setVendorRelease(oldResource.getVendorRelease()); - } + if (newResource.getDescription() == null) { + newResource.setDescription(oldResource.getDescription()); + } - if (newResource.getResourceVendorModelNumber() == null) { - newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber()); - } + if (newResource.getVendorRelease() == null) { + newResource.setVendorRelease(oldResource.getVendorRelease()); + } - if (newResource.getContactId() == null) { - newResource.setContactId(oldResource.getContactId()); - } + if (newResource.getResourceVendorModelNumber() == null) { + newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber()); + } - newResource.setCategories(oldResource.getCategories()); - if (newResource.getVendorName() == null) { - newResource.setVendorName(oldResource.getVendorName()); - } - } + if (newResource.getContactId() == null) { + newResource.setContactId(oldResource.getContactId()); + } - private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user, - boolean inTransaction, boolean needLock) { + newResource.setCategories(oldResource.getCategories()); + if (newResource.getVendorName() == null) { + newResource.setVendorName(oldResource.getVendorName()); + } + List<GroupDefinition>oldForUpdate = oldResource.getGroups(); + if(CollectionUtils.isNotEmpty(oldForUpdate)){ + List<GroupDefinition>groupForUpdate = oldForUpdate.stream().map(group -> new GroupDefinition(group)).collect(Collectors.toList()); - if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) { - // checkout - return lifecycleBusinessLogic.changeState( - oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, - new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock) - .left() - .on(response -> failOnChangeState(response, user, oldResource, newResource)); - } - return oldResource; - } + groupForUpdate.stream().filter(group -> group.isVspOriginated()) + .forEach(group -> group.setName(group.getInvariantName())); - private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) { - log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), - response.getFormattedMessage()); - componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE, - ResourceVersionInfo.newBuilder() - .state(oldResource.getLifecycleState().name()) - .version(oldResource.getVersion()) - .build()); - throw new ByResponseFormatComponentException(response); - } + newResource.setGroups(groupForUpdate); + } - public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) { - - validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction); - validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction); - validateLifecycleTypesCreate(user, resource, actionEnum); - validateResourceType(user, resource, actionEnum); - resource.setCreatorUserId(user.getUserId()); - resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); - resource.setContactId(resource.getContactId().toLowerCase()); - if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) { - String resourceSystemName; - if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) { - resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName()); - } else { - resourceSystemName = resource.getSystemName(); - } - resource.setToscaResourceName(CommonBeUtils - .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName)); - } - // Generate invariant UUID - must be here and not in operation since it - // should stay constant during clone - // TODO - String invariantUUID = UniqueIdBuilder.buildInvariantUUID(); - resource.setInvariantUUID(invariantUUID); + if(newResource.getResourceType().isAtomicType() && !newResource.getName().equals("Root")&& newResource.getResourceType() != ResourceTypeEnum.CVFC) { + ResourceTypeEnum updatedResourceType = newResource.getResourceType(); + Component derivedFromResource = getParentComponent(newResource); + if (derivedFromResource.getComponentType() == ComponentTypeEnum.RESOURCE) { + Resource parentResource = (Resource) derivedFromResource; + if (!(parentResource.isAbstract() && (ResourceTypeEnum.VFC == parentResource.getResourceType() || ResourceTypeEnum.ABSTRACT == parentResource.getResourceType())) && + parentResource.getResourceType() != updatedResourceType) { + BeEcompErrorManager.getInstance() + .logInternalDataError("mergeOldResourceMetadataWithNew", "resource type of the resource does not match to derived from resource type", + ErrorSeverity.ERROR); + log.debug("#mergeOldResourceMetadataWithNew - resource type {} of the resource {} does not match to derived from resource type {}", + newResource.getResourceType(), newResource.getToscaResourceName(), parentResource.getResourceType()); + throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_TYPE); + } + } + } - return resource; - } + } - private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource, - AuditingActionEnum actionEnum) { - Either<Boolean, ResponseFormat> eitherResult = Either.left(true); - if (resource.getResourceType() == null) { - log.debug("Invalid resource type for resource"); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - eitherResult = Either.right(errorResponse); - componentsUtils.auditResource(errorResponse, user, resource, actionEnum); - } - return eitherResult; - } + private Component getParentComponent(Resource newResource) { + String toscaResourceNameDerivedFrom = newResource.getDerivedFrom().get(0); + Either<Component, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(toscaResourceNameDerivedFrom); + if(latestByToscaResourceName.isRight()){ + BeEcompErrorManager.getInstance() + .logInternalDataError("mergeOldResourceMetadataWithNew", "derived from resource not found", ErrorSeverity.ERROR); + log.debug("#mergeOldResourceMetadataWithNew - derived from resource {} not found", toscaResourceNameDerivedFrom); + throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, toscaResourceNameDerivedFrom); + } + return latestByToscaResourceName.left().value(); + } - private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource, - AuditingActionEnum actionEnum) { - Either<Boolean, ResponseFormat> eitherResult = Either.left(true); - if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) { - log.debug("validate interface lifecycle Types Exist"); - Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator(); - while (intItr.hasNext() && eitherResult.isLeft()) { - InterfaceDefinition interfaceDefinition = intItr.next(); - String intType = interfaceDefinition.getUniqueId(); - Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation - .getInterface(intType); - if (eitherCapTypeFound.isRight()) { - if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logBeGraphObjectMissingError( - "Create Resource - validateLifecycleTypesCreate", "Interface", intType); - log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", - intType, resource.getName()); - BeEcompErrorManager.getInstance() - .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate"); - log.debug("request to data model failed with error: {}", - eitherCapTypeFound.right().value().name()); - } - - ResponseFormat errorResponse = componentsUtils - .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType); - eitherResult = Either.right(errorResponse); - componentsUtils.auditResource(errorResponse, user, resource, actionEnum); - } + private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user, + boolean inTransaction, boolean needLock) { - } - } - return eitherResult; - } + if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) { + // checkout + return lifecycleBusinessLogic.changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, + new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock) + .left() + .on(response -> failOnChangeState(response, user, oldResource, newResource)); + } + return oldResource; + } - private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user, - ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, - boolean inTransaction) { + private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) { + log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage()); + componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE, + ResourceVersionInfo.newBuilder() + .state(oldResource.getLifecycleState() + .name()) + .version(oldResource.getVersion()) + .build()); + throw new ByResponseFormatComponentException(response); + } - Either<Boolean, ResponseFormat> eitherResult = Either.left(true); - if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) { - log.debug("validate capability Types Exist - capabilities section"); + public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, + boolean inTransaction, CsarInfo csarInfo) { + + validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction); + validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction); + validateLifecycleTypesCreate(user, resource, actionEnum); + validateResourceType(user, resource, actionEnum); + resource.setCreatorUserId(user.getUserId()); + resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); + resource.setContactId(resource.getContactId() + .toLowerCase()); + if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) { + String resourceSystemName; + if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) { + resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName()); + } else { + resourceSystemName = resource.getSystemName(); + } + resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType() + .name() + .toLowerCase(), resourceSystemName)); + } - for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) { + // Generate invariant UUID - must be here and not in operation since it + // should stay constant during clone + // TODO + String invariantUUID = UniqueIdBuilder.buildInvariantUUID(); + resource.setInvariantUUID(invariantUUID); - eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, - eitherResult, typeEntry, inTransaction); - if (eitherResult.isRight()) { - return Either.right(eitherResult.right().value()); - } - } - } + return resource; + } - if (resource.getRequirements() != null && resource.getRequirements().size() > 0) { - log.debug("validate capability Types Exist - requirements section"); - for (String type : resource.getRequirements().keySet()) { - eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, - resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction); - if (eitherResult.isRight()) { - return Either.right(eitherResult.right().value()); - } - } - } + private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource, + AuditingActionEnum actionEnum) { + Either<Boolean, ResponseFormat> eitherResult = Either.left(true); + if (resource.getResourceType() == null) { + log.debug("Invalid resource type for resource"); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + eitherResult = Either.right(errorResponse); + componentsUtils.auditResource(errorResponse, user, resource, actionEnum); + } + return eitherResult; + } - return eitherResult; - } + private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource, + AuditingActionEnum actionEnum) { + Either<Boolean, ResponseFormat> eitherResult = Either.left(true); + if (resource.getInterfaces() != null && resource.getInterfaces() + .size() > 0) { + log.debug("validate interface lifecycle Types Exist"); + Iterator<InterfaceDefinition> intItr = resource.getInterfaces() + .values() + .iterator(); + while (intItr.hasNext() && eitherResult.isLeft()) { + InterfaceDefinition interfaceDefinition = intItr.next(); + String intType = interfaceDefinition.getUniqueId(); + Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation + .getInterface(intType); + if (eitherCapTypeFound.isRight()) { + if (eitherCapTypeFound.right() + .value() == StorageOperationStatus.NOT_FOUND) { + BeEcompErrorManager.getInstance() + .logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", + "Interface", intType); + log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", + intType, resource.getName()); + BeEcompErrorManager.getInstance() + .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate"); + log.debug("request to data model failed with error: {}", eitherCapTypeFound.right() + .value() + .name()); + } + + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType); + eitherResult = Either.right(errorResponse); + componentsUtils.auditResource(errorResponse, user, resource, actionEnum); + } - // @param typeObject- the object to which the validation is done - private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, - ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects, - AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type, - boolean inTransaction) { - Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation - .getCapabilityType(type, inTransaction); - if (eitherCapTypeFound.isRight()) { - if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logBeGraphObjectMissingError( - CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type); - log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, - resource.getName()); - BeEcompErrorManager.getInstance() - .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES); - } - log.debug("Trying to get capability type {} failed with error: {}", type, - eitherCapTypeFound.right().value().name()); - ResponseFormat errorResponse = null; - if (type != null) { - errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type); - } else { - errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, - validationObjects); - } - eitherResult = Either.right(errorResponse); - componentsUtils.auditResource(errorResponse, user, resource, actionEnum); - } - return eitherResult; - } + } + } + return eitherResult; + } - private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, - ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, - Either<Boolean, ResponseFormat> eitherResult, Entry<String, List<CapabilityDefinition>> typeEntry, - boolean inTransaction) { - Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation - .getCapabilityType(typeEntry.getKey(), inTransaction); - if (eitherCapTypeFound.isRight()) { - if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logBeGraphObjectMissingError( - CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey()); - log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", - typeEntry.getKey(), resource.getName()); - BeEcompErrorManager.getInstance() - .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES); - } - log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), - eitherCapTypeFound.right().value().name()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, - typeEntry.getKey()); - eitherResult = Either.right(errorResponse); - componentsUtils.auditResource(errorResponse, user, resource, actionEnum); - } - CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value(); - if (capabilityTypeDefinition.getProperties() != null) { - for (CapabilityDefinition capDef : typeEntry.getValue()) { - List<ComponentInstanceProperty> properties = capDef.getProperties(); - if (properties == null || properties.isEmpty()) { - properties = new ArrayList<>(); - for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) { - ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue()); - properties.add(newProp); - } - } else { - for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) { - PropertyDefinition porpFromDef = prop.getValue(); - List<ComponentInstanceProperty> propsToAdd = new ArrayList<>(); - for (ComponentInstanceProperty cip : properties) { - if (!cip.getName().equals(porpFromDef.getName())) { - ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef); - propsToAdd.add(newProp); - } - } - if (!propsToAdd.isEmpty()) { - properties.addAll(propsToAdd); - } - } - } - capDef.setProperties(properties); - } - } - return eitherResult; - } + private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user, + ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, + boolean inTransaction) { - public Resource createResourceByDao(Resource resource, User user, - AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction) { - // create resource + Either<Boolean, ResponseFormat> eitherResult = Either.left(true); + if (resource.getCapabilities() != null && resource.getCapabilities() + .size() > 0) { + log.debug("validate capability Types Exist - capabilities section"); - // lock new resource name in order to avoid creation resource with same - // name - Resource createdResource = null; - if (!inTransaction) { - Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, - CREATE_RESOURCE); - if (lockResult.isRight()) { - ResponseFormat responseFormat = lockResult.right().value(); - componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw new ByResponseFormatComponentException(responseFormat); - } + for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities() + .entrySet()) { - log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult); - } - try { - if (resource.deriveFromGeneric()) { - handleResourceGenericType(resource); - } - createdResource = createResourceTransaction(resource, user, isNormative - ); - componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user, - createdResource, actionEnum); - ASDCKpiApi.countCreatedResourcesKPI(); - } catch(ByActionStatusComponentException e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); - componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw e; - } catch(ByResponseFormatComponentException e) { - ResponseFormat responseFormat = e.getResponseFormat(); - componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw e; - } catch (StorageException e){ - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus())); - componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw e; - } - finally { - if (!inTransaction) { - graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), - NodeTypeEnum.Resource); - } - } - return createdResource; - } + eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, + eitherResult, typeEntry, inTransaction); + if (eitherResult.isRight()) { + return Either.right(eitherResult.right() + .value()); + } + } + } - private Resource createResourceTransaction(Resource resource, User user, - boolean isNormative) { - // validate resource name uniqueness - log.debug("validate resource name"); - Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists( - resource.getName(), resource.getResourceType(), resource.getComponentType()); - if (eitherValidation.isRight()) { - log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(), - eitherValidation.right().value()); - ResponseFormat errorResponse = componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value())); - throw new ByResponseFormatComponentException(errorResponse); - } - if (eitherValidation.left().value()) { - log.debug("resource with name: {}, already exists", resource.getName()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, - ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); - throw new ByResponseFormatComponentException(errorResponse); - } + if (resource.getRequirements() != null && resource.getRequirements() + .size() > 0) { + log.debug("validate capability Types Exist - requirements section"); + for (String type : resource.getRequirements() + .keySet()) { + eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, + resource.getRequirements() + .get(type), + actionEnum, eitherResult, type, inTransaction); + if (eitherResult.isRight()) { + return Either.right(eitherResult.right() + .value()); + } + } + } - log.debug("send resource {} to dao for create", resource.getName()); - - createArtifactsPlaceHolderData(resource, user); - // enrich object - if (!isNormative) { - log.debug("enrich resource with creator, version and state"); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - resource.setVersion(INITIAL_VERSION); - resource.setHighestVersion(true); - if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) { - resource.setAbstract(false); - } - } - return toscaOperationFacade.createToscaComponent(resource) - .left() - .on(r->throwComponentExceptionByResource(r, resource)); - } + return eitherResult; + } - private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(status), resource); - throw new ByResponseFormatComponentException(responseFormat); - } + // @param typeObject- the object to which the validation is done + private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, + ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects, + AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type, + boolean inTransaction) { + Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation + .getCapabilityType(type, inTransaction); + if (eitherCapTypeFound.isRight()) { + if (eitherCapTypeFound.right() + .value() == StorageOperationStatus.NOT_FOUND) { + BeEcompErrorManager.getInstance() + .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", + type); + log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, + resource.getName()); + BeEcompErrorManager.getInstance() + .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES); + } + log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right() + .value() + .name()); + ResponseFormat errorResponse = null; + if (type != null) { + errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type); + } else { + errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, + validationObjects); + } + eitherResult = Either.right(errorResponse); + componentsUtils.auditResource(errorResponse, user, resource, actionEnum); + } + return eitherResult; + } - private void createArtifactsPlaceHolderData(Resource resource, User user) { - // create mandatory artifacts + private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, + ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, + Either<Boolean, ResponseFormat> eitherResult, Entry<String, List<CapabilityDefinition>> typeEntry, + boolean inTransaction) { + Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation + .getCapabilityType(typeEntry.getKey(), inTransaction); + if (eitherCapTypeFound.isRight()) { + if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) { + BeEcompErrorManager.getInstance() + .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", + typeEntry.getKey()); + log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", + typeEntry.getKey(), resource.getName()); + BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES); + } + log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), + eitherCapTypeFound.right().value().name()); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, + typeEntry.getKey()); + componentsUtils.auditResource(errorResponse, user, resource, actionEnum); + return Either.right(errorResponse); + } + CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value(); + if (capabilityTypeDefinition.getProperties() != null) { + for (CapabilityDefinition capDef : typeEntry.getValue()) { + List<ComponentInstanceProperty> properties = capDef.getProperties(); + List<ComponentInstanceProperty> changedProperties = new ArrayList<>(); + if (properties == null || properties.isEmpty()) { + for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) { + ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue()); + changedProperties.add(newProp); + } + } else { + List<ComponentInstanceProperty> propsToAdd = new ArrayList<>(); + for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) { + PropertyDefinition propFromDef = prop.getValue(); + boolean propFound = false; + for (ComponentInstanceProperty cip : properties) { + if (propFromDef.getName().equals(cip.getName())) { + //merge property value and property description only, ignore other fields + if(cip.getDescription() != null && !cip.getDescription().equals(propFromDef.getDescription())){ + propFromDef.setDescription(cip.getDescription()); + } + propertyDataValueMergeBusinessLogic.mergePropertyValue(propFromDef, cip, new ArrayList<>()); + if(cip.getValue() != null){ + propFromDef.setValue(cip.getValue()); + } + propsToAdd.add(new ComponentInstanceProperty(propFromDef)); + propFound = true; + properties.remove(cip); + break; + } + } + if(!propFound) { + propsToAdd.add(new ComponentInstanceProperty(propFromDef)); + } + } + if (!propsToAdd.isEmpty()) { + changedProperties.addAll(propsToAdd); + } + } + capDef.setProperties(changedProperties); + } + } + return eitherResult; + } - // TODO it must be removed after that artifact uniqueId creation will be - // moved to ArtifactOperation + public Resource createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum, + boolean isNormative, boolean inTransaction) { + // create resource + + // lock new resource name in order to avoid creation resource with same + // name + Resource createdResource = null; + if (!inTransaction) { + Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, + CREATE_RESOURCE); + if (lockResult.isRight()) { + ResponseFormat responseFormat = lockResult.right().value(); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + throw new ByResponseFormatComponentException(responseFormat); + } - setInformationalArtifactsPlaceHolder(resource, user); - setDeploymentArtifactsPlaceHolder(resource, user); - setToscaArtifactsPlaceHolders(resource, user); - } + log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult); + } + try { + if (resource.deriveFromGeneric()) { + handleResourceGenericType(resource); + } + createdResource = createResourceTransaction(resource, user, isNormative); + componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user, + createdResource, actionEnum); + ASDCKpiApi.countCreatedResourcesKPI(); + } catch (ComponentException e) { + ResponseFormat responseFormat = e.getResponseFormat() == null + ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat(); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + throw e; + } catch (StorageException e) { + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus())); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + throw e; + } finally { + if (!inTransaction) { + graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), + NodeTypeEnum.Resource); + } + } + return createdResource; + } - @SuppressWarnings("unchecked") - @Override - public void setDeploymentArtifactsPlaceHolder(Component component, User user) { - Resource resource = (Resource) component; - Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts(); - if (artifactMap == null) { - artifactMap = new HashMap<>(); - } - Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager() - .getConfiguration().getDeploymentResourceArtifacts(); - if (deploymentResourceArtifacts != null) { - Map<String, ArtifactDefinition> finalArtifactMap = artifactMap; - deploymentResourceArtifacts.forEach((k, v)->processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k,v)); - } - resource.setDeploymentArtifacts(artifactMap); - } + private Resource createResourceTransaction(Resource resource, User user, boolean isNormative) { + // validate resource name uniqueness + log.debug("validate resource name"); + Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists( + resource.getName(), resource.getResourceType(), resource.getComponentType()); + if (eitherValidation.isRight()) { + loggerSupportability.log(LoggerSupportabilityActions.VALIDATE_NAME,resource.getComponentMetadataForSupportLog(), + StatusCode.ERROR,"ERROR while validate component name {} Status is: {}",resource.getName(),eitherValidation.right().value()); + log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(), + eitherValidation.right() + .value()); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherValidation.right() + .value())); + } + if (eitherValidation.left() + .value()) { + log.debug("resource with name: {}, already exists", resource.getName()); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(), + StatusCode.ERROR,"resource with name: {} already exists",resource.getName()); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, + ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); + } - private void processDeploymentResourceArtifacts(User user, Resource resource, Map<String, ArtifactDefinition> artifactMap, String k, Object v) { - boolean shouldCreateArtifact = true; - Map<String, Object> artifactDetails = (Map<String, Object>) v; - Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES); - if (object != null) { - List<String> artifactTypes = (List<String>) object; - if (!artifactTypes.contains(resource.getResourceType().name())) { - shouldCreateArtifact = false; - return; - } - } else { - log.info("resource types for artifact placeholder {} were not defined. default is all resources", - k); - } - if (shouldCreateArtifact) { - if (artifactsBusinessLogic != null) { - ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo( - resource.getUniqueId(), k, (Map<String, Object>) v, - user, ArtifactGroupTypeEnum.DEPLOYMENT); - if (artifactDefinition != null - && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) { - artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); - } - } - } - } + log.debug("send resource {} to dao for create", resource.getName()); + + createArtifactsPlaceHolderData(resource, user); + // enrich object + if (!isNormative) { + log.debug("enrich resource with creator, version and state"); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + resource.setVersion(INITIAL_VERSION); + resource.setHighestVersion(true); + if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) { + resource.setAbstract(false); + } + } + return toscaOperationFacade.createToscaComponent(resource) + .left() + .on(r -> throwComponentExceptionByResource(r, resource)); + } - @SuppressWarnings("unchecked") - private void setInformationalArtifactsPlaceHolder(Resource resource, User user) { - Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts(); - if (artifactMap == null) { - artifactMap = new HashMap<>(); - } - String resourceUniqueId = resource.getUniqueId(); - List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration() - .getExcludeResourceCategory(); - List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration() - .getExcludeResourceType(); - Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager() - .getConfiguration().getInformationalResourceArtifacts(); - List<CategoryDefinition> categories = resource.getCategories(); - boolean isCreateArtifact = true; - if (exludeResourceCategory != null) { - String category = categories.get(0).getName(); - isCreateArtifact = exludeResourceCategory.stream().noneMatch(e->e.equalsIgnoreCase(category)); - } - if (isCreateArtifact && exludeResourceType != null) { - String resourceType = resource.getResourceType().name(); - isCreateArtifact = exludeResourceType.stream().noneMatch(e->e.equalsIgnoreCase(resourceType)); - } - if (informationalResourceArtifacts != null && isCreateArtifact) { - Set<String> keys = informationalResourceArtifacts.keySet(); - for (String informationalResourceArtifactName : keys) { - Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts - .get(informationalResourceArtifactName); - ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo( - resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user, - ArtifactGroupTypeEnum.INFORMATIONAL); - artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); + private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) { + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource); + throw new ByResponseFormatComponentException(responseFormat); + } - } - } - resource.setArtifacts(artifactMap); - } + private void createArtifactsPlaceHolderData(Resource resource, User user) { + // create mandatory artifacts - /** - * deleteResource - * - * @param resourceId - * @param user - * @return - */ - public ResponseFormat deleteResource(String resourceId, User user) { - ResponseFormat responseFormat; - validateUserExists(user, DELETE_RESOURCE, false); - - Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId); - if (resourceStatus.isRight()) { - log.debug("failed to get resource {}", resourceId); - return componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), ""); - } + // TODO it must be removed after that artifact uniqueId creation will be + // moved to ArtifactOperation - Resource resource = resourceStatus.left().value(); + setInformationalArtifactsPlaceHolder(resource, user); + setDeploymentArtifactsPlaceHolder(resource, user); + setToscaArtifactsPlaceHolders(resource, user); + } - StorageOperationStatus result = StorageOperationStatus.OK; - Either<Boolean, ResponseFormat> lockResult = lockComponent(resourceId, resource, "Mark resource to delete"); - if (lockResult.isRight()) { - return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - } + @SuppressWarnings("unchecked") + @Override + public void setDeploymentArtifactsPlaceHolder(Component component, User user) { + Resource resource = (Resource) component; + Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts(); + if (artifactMap == null) { + artifactMap = new HashMap<>(); + } + Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getDeploymentResourceArtifacts(); + if (deploymentResourceArtifacts != null) { + Map<String, ArtifactDefinition> finalArtifactMap = artifactMap; + deploymentResourceArtifacts + .forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v)); + } + resource.setDeploymentArtifacts(artifactMap); + } - try { + private void processDeploymentResourceArtifacts(User user, Resource resource, + Map<String, ArtifactDefinition> artifactMap, String k, Object v) { + boolean shouldCreateArtifact = true; + Map<String, Object> artifactDetails = (Map<String, Object>) v; + Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES); + if (object != null) { + List<String> artifactTypes = (List<String>) object; + if (!artifactTypes.contains(resource.getResourceType() + .name())) { + shouldCreateArtifact = false; + return; + } + } else { + log.info("resource types for artifact placeholder {} were not defined. default is all resources", k); + } + if (shouldCreateArtifact) { + if (artifactsBusinessLogic != null) { + ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo( + resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT); + if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) { + artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); + } + } + } + } - result = markComponentToDelete(resource); - if (result.equals(StorageOperationStatus.OK)) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); - } else { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); - responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName()); - } - return responseFormat; + @SuppressWarnings("unchecked") + private void setInformationalArtifactsPlaceHolder(Resource resource, User user) { + Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts(); + if (artifactMap == null) { + artifactMap = new HashMap<>(); + } + String resourceUniqueId = resource.getUniqueId(); + List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getExcludeResourceCategory(); + List<String> exludeResourceType = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getExcludeResourceType(); + Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getInformationalResourceArtifacts(); + List<CategoryDefinition> categories = resource.getCategories(); + boolean isCreateArtifact = true; + if (exludeResourceCategory != null) { + String category = categories.get(0) + .getName(); + isCreateArtifact = exludeResourceCategory.stream() + .noneMatch(e -> e.equalsIgnoreCase(category)); + } + if (isCreateArtifact && exludeResourceType != null) { + String resourceType = resource.getResourceType() + .name(); + isCreateArtifact = exludeResourceType.stream() + .noneMatch(e -> e.equalsIgnoreCase(resourceType)); + } + if (informationalResourceArtifacts != null && isCreateArtifact) { + Set<String> keys = informationalResourceArtifacts.keySet(); + for (String informationalResourceArtifactName : keys) { + Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts + .get(informationalResourceArtifactName); + ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo( + resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user, + ArtifactGroupTypeEnum.INFORMATIONAL); + artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); - } finally { - if (result == null || !result.equals(StorageOperationStatus.OK)) { - janusGraphDao.rollback(); - } else { - janusGraphDao.commit(); - } - graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); - } + } + } + resource.setArtifacts(artifactMap); + } - } + /** + * deleteResource + * + * @param resourceId + * @param user + * @return + */ + public ResponseFormat deleteResource(String resourceId, User user) { + ResponseFormat responseFormat; + validateUserExists(user); + + Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId); + if (resourceStatus.isRight()) { + log.debug("failed to get resource {}", resourceId); + return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right() + .value()), ""); + } - public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); - validateUserExists(user, DELETE_RESOURCE, false); - Resource resource = null; - StorageOperationStatus result = StorageOperationStatus.OK; - try { + Resource resource = resourceStatus.left() + .value(); - Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade - .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version); - if (resourceStatus.isRight()) { - log.debug("failed to get resource {} version {}", resourceName, version); - return componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName); - } + StorageOperationStatus result = StorageOperationStatus.OK; + lockComponent(resourceId, resource, "Mark resource to delete"); + try { - resource = resourceStatus.left().value(); + result = markComponentToDelete(resource); + if (result == StorageOperationStatus.OK) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); + } else { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); + responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName()); + } + return responseFormat; - } finally { - if (result == null || !result.equals(StorageOperationStatus.OK)) { - janusGraphDao.rollback(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); - responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName); - } else { + } finally { + if (result == null || result != StorageOperationStatus.OK) { + janusGraphDao.rollback(); + } else { janusGraphDao.commit(); - } - } - if (resource != null) { - Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource, - DELETE_RESOURCE); - if (lockResult.isRight()) { - result = StorageOperationStatus.GENERAL_ERROR; - return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - } - try { - result = markComponentToDelete(resource); - if (!result.equals(StorageOperationStatus.OK)) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); - responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName()); - return responseFormat; - } - - } finally { - if (result == null || !result.equals(StorageOperationStatus.OK)) { - janusGraphDao.rollback(); - } else { - janusGraphDao.commit(); - } - graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource); - } - } - return responseFormat; - } + } + graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); + } - public Either<Resource, ResponseFormat> getResource(String resourceId, User user) { + } - if (user != null) { - validateUserExists(user, CREATE_RESOURCE, false); - } + public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); + validateUserExists(user); + Resource resource = null; + StorageOperationStatus result = StorageOperationStatus.OK; + boolean failed = false; + try { + + Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade + .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version); + if (resourceStatus.isRight()) { + log.debug("failed to get resource {} version {}", resourceName, version); + return componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right() + .value()), resourceName); + } - Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId); - if (storageStatus.isRight()) { - log.debug("failed to get resource by id {}", resourceId); - return Either.right(componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId)); - } - if (!(storageStatus.left().value() instanceof Resource)) { - return Either.right(componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId)); - } - return Either.left(storageStatus.left().value()); + resource = resourceStatus.left() + .value(); - } + } finally { + janusGraphDao.commit(); + } + if (resource != null) { + lockComponent(resource.getUniqueId(), resource, DELETE_RESOURCE); + try { + result = markComponentToDelete(resource); + if (result != StorageOperationStatus.OK) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); + responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName()); + return responseFormat; + } + }catch (ComponentException e){ + failed = true; + throw e; + }finally { + if (failed || result == null || result != StorageOperationStatus.OK) { + janusGraphDao.rollback(); + } else { + janusGraphDao.commit(); + } + graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource); + } + } + return responseFormat; + } - public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion, - String userId) { + public Either<Resource, ResponseFormat> getResource(String resourceId, User user) { - validateUserExists(userId, "get Resource By Name And Version", false); + if (user != null) { + validateUserExists(user); + } - Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade - .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion); - if (getResource.isRight()) { - log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion); - return Either.right(componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName)); - } - return Either.left(getResource.left().value()); - } + Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId); + if (storageStatus.isRight()) { + log.debug("failed to get resource by id {}", resourceId); + return Either.right(componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right() + .value()), resourceId)); + } + if (!(storageStatus.left() + .value() instanceof Resource)) { + return Either.right(componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId)); + } + return Either.left(storageStatus.left() + .value()); - /** - * updateResourceMetadata - * - * @param user - modifier data (userId) - * @param inTransaction TODO - * @param resourceIdToUpdate - the resource identifier - * @param newResource - * @return Either<Resource , responseFormat> - */ - public Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource, - Resource currentResource, User user, boolean inTransaction) { + } - validateUserExists(user.getUserId(), "update Resource Metadata", false); + public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion, + String userId) { - log.debug("Get resource with id {}", resourceIdToUpdate); - boolean needToUnlock = false; - boolean rollbackNeeded = true; + validateUserExists(userId); - try { - if (currentResource == null) { - Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade - .getToscaElement(resourceIdToUpdate); - if (storageStatus.isRight()) { - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(storageStatus.right().value()), "")); - } + Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade + .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion); + if (getResource.isRight()) { + log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion); + return Either.right(componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right() + .value()), resourceName)); + } + return Either.left(getResource.left() + .value()); + } - currentResource = storageStatus.left().value(); - } - // verify that resource is checked-out and the user is the last - // updater - if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) { - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } + /** + * updateResourceMetadata + * + * @param user + * - modifier data (userId) + * @param inTransaction + * TODO + * @param resourceIdToUpdate + * - the resource identifier + * @param newResource + * @return Either<Resource , responseFormat> + */ + public Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource, + User user, boolean inTransaction) { + + validateUserExists(user.getUserId()); + + log.debug("Get resource with id {}", resourceIdToUpdate); + boolean needToUnlock = false; + + try { + if (currentResource == null) { + Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade + .getToscaElement(resourceIdToUpdate); + if (storageStatus.isRight()) { + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(storageStatus.right() + .value()), + "")); + } + + currentResource = storageStatus.left() + .value(); + } + // verify that resource is checked-out and the user is the last + // updater + if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) { + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } - // lock resource - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate, - NodeTypeEnum.Resource); - if (!lockResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ", - NodeTypeEnum.Resource.getName(), resourceIdToUpdate); - log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult); - ResponseFormat responseFormat = componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult)); - throw new ByResponseFormatComponentException(responseFormat); - } + // lock resource + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate, + NodeTypeEnum.Resource); + if (lockResult != StorageOperationStatus.OK) { + BeEcompErrorManager.getInstance() + .logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(), + resourceIdToUpdate); + log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult)); + throw new ByResponseFormatComponentException(responseFormat); + } - needToUnlock = true; + needToUnlock = true; - // critical section starts here - // convert json to object + // critical section starts here + // convert json to object - // Update and updated resource must have a non-empty "derivedFrom" - // list - // This code is not called from import resources, because of root - // VF "derivedFrom" should be null (or ignored) - if (ModelConverter.isAtomicComponent(currentResource)) { - validateDerivedFromNotEmpty(null, newResource, null); - validateDerivedFromNotEmpty(null, currentResource, null); - } else { - newResource.setDerivedFrom(null); - } + // Update and updated resource must have a non-empty "derivedFrom" + // list + // This code is not called from import resources, because of root + // VF "derivedFrom" should be null (or ignored) + if (ModelConverter.isAtomicComponent(currentResource)) { + validateDerivedFromNotEmpty(null, newResource, null); + validateDerivedFromNotEmpty(null, currentResource, null); + } else { + newResource.setDerivedFrom(null); + } Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource, user, currentResource, false, true); if (dataModelResponse.isRight()) { log.debug("failed to update resource metadata!!!"); - rollbackNeeded = true; throw new ByResponseFormatComponentException(dataModelResponse.right().value()); } - log.debug("Resource metadata updated successfully!!!"); - rollbackNeeded = false; - return dataModelResponse.left().value(); + log.debug("Resource metadata updated successfully!!!"); + return dataModelResponse.left() + .value(); - } catch (ComponentException|StorageException e){ - rollback(inTransaction, newResource, null, null); - throw e; - } - finally { - if (!inTransaction) { + } catch (ComponentException | StorageException e) { + rollback(inTransaction, newResource, null, null); + throw e; + } finally { + if (!inTransaction) { janusGraphDao.commit(); - } - if (needToUnlock) { - graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource); - } - } - } - - private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, - User user, Resource currentResource, boolean shouldLock, boolean inTransaction) { - updateVfModuleGroupsNames(currentResource, newResource); - validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false); - // Setting last updater and uniqueId - newResource.setContactId(newResource.getContactId().toLowerCase()); - newResource.setLastUpdaterUserId(user.getUserId()); - newResource.setUniqueId(resourceIdToUpdate); - // Cannot set highest version through UI - newResource.setHighestVersion(currentResource.isHighestVersion()); - newResource.setCreationDate(currentResource.getCreationDate()); - - Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource, - newResource, user.getUserId(), inTransaction); - - if (processUpdateOfDerivedFrom.isRight()) { - log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate); - return Either.right(processUpdateOfDerivedFrom.right().value()); - } - - log.debug("send resource {} to dao for update", newResource.getUniqueId()); - if (isNotEmpty(newResource.getGroups())) { - for (GroupDefinition group : newResource.getGroups()) { - if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) { - groupBusinessLogic.validateAndUpdateGroupMetadata( - newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId(), - user, newResource.getComponentType(), group, true, false); - } - } - } - Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade - .updateToscaElement(newResource); - - if (dataModelResponse.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource); - return Either.right(responseFormat); - } else if (dataModelResponse.left().value() == null) { - log.debug("No response from updateResource"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return Either.left(dataModelResponse.left().value()); - } - - - private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) { - if(currentResource.getGroups() != null && !currentResource.getName().equals(newResource.getName())){ - List<GroupDefinition> updatedGroups = currentResource.getGroups() - .stream() - .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName())) - .collect(toList()); - newResource.setGroups(updatedGroups); - } - } - - private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) { - GroupDefinition updatedGroup = new GroupDefinition(currGroup); - if(updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)){ - String prefix = updatedGroup.getName().substring(0, replacePattern.length()); - String newGroupName = updatedGroup.getName().replaceFirst(prefix, with); - updatedGroup.setName(newGroupName); - } - return updatedGroup; - } - /** - * validateResourceFieldsBeforeCreate - * - * @param user - modifier data (userId) - * @return Either<Boolean , ErrorResponse> - */ - private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource, - AuditingActionEnum actionEnum, boolean inTransaction) { - validateComponentFieldsBeforeCreate(user, resource, actionEnum); - // validate category - log.debug("validate category"); - validateCategory(user, resource, actionEnum, inTransaction); - // validate vendor name & release & model number - log.debug("validate vendor name"); - validateVendorName(user, resource, actionEnum); - log.debug("validate vendor release"); - validateVendorReleaseName(user, resource, actionEnum); - log.debug("validate resource vendor model number"); - validateResourceVendorModelNumber(user, resource, actionEnum); - // validate cost - log.debug("validate cost"); - validateCost(resource); - // validate licenseType - log.debug("validate licenseType"); - validateLicenseType(user, resource, actionEnum); - // validate template (derived from) - log.debug("validate derived from"); - if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) { - resource.setDerivedFrom(null); - } - validateDerivedFromExist(user, resource, actionEnum); - // warn about non-updatable fields - checkComponentFieldsForOverrideAttempt(resource); - String currentCreatorFullName = resource.getCreatorFullName(); - if (currentCreatorFullName != null) { - log.debug("Resource Creator fullname is automatically set and cannot be updated"); - } - - String currentLastUpdaterFullName = resource.getLastUpdaterFullName(); - if (currentLastUpdaterFullName != null) { - log.debug("Resource LastUpdater fullname is automatically set and cannot be updated"); - } - - Long currentLastUpdateDate = resource.getLastUpdateDate(); - if (currentLastUpdateDate != null) { - log.debug("Resource last update date is automatically set and cannot be updated"); - } - - Boolean currentAbstract = resource.isAbstract(); - if (currentAbstract != null) { - log.debug("Resource abstract is automatically set and cannot be updated"); - } - - return Either.left(true); - } - - /** - * validateResourceFieldsBeforeUpdate - * - * @param currentResource - Resource object to validate - * @param isNested - */ - private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, - boolean inTransaction, boolean isNested) { - validateFields(currentResource, updateInfoResource, inTransaction, isNested); - warnNonEditableFields(currentResource, updateInfoResource); - } - - private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) { - String currentResourceVersion = currentResource.getVersion(); - String updatedResourceVersion = updateInfoResource.getVersion(); - - if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) { - log.debug("Resource version is automatically set and cannot be updated"); - } + } + if (needToUnlock) { + graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource); + } + } + } - String currentCreatorUserId = currentResource.getCreatorUserId(); - String updatedCreatorUserId = updateInfoResource.getCreatorUserId(); + private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, + User user, Resource currentResource, boolean shouldLock, boolean inTransaction) { + updateVfModuleGroupsNames(currentResource, newResource); + validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false); + // Setting last updater and uniqueId + newResource.setContactId(newResource.getContactId() + .toLowerCase()); + newResource.setLastUpdaterUserId(user.getUserId()); + newResource.setUniqueId(resourceIdToUpdate); + // Cannot set highest version through UI + newResource.setHighestVersion(currentResource.isHighestVersion()); + newResource.setCreationDate(currentResource.getCreationDate()); + + Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource, + newResource, user.getUserId(), inTransaction); + + if (processUpdateOfDerivedFrom.isRight()) { + log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate); + return Either.right(processUpdateOfDerivedFrom.right() + .value()); + } - if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) { - log.debug("Resource Creator UserId is automatically set and cannot be updated"); - } + log.debug("send resource {} to dao for update", newResource.getUniqueId()); + if (isNotEmpty(newResource.getGroups())) { + for (GroupDefinition group : newResource.getGroups()) { + if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) { + groupBusinessLogic.validateAndUpdateGroupMetadata(newResource.getComponentMetadataDefinition() + .getMetadataDataDefinition() + .getUniqueId(), user, newResource.getComponentType(), group, true, false); + } + } + } + Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade + .updateToscaElement(newResource); + + if (dataModelResponse.isRight()) { + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right() + .value()), newResource); + return Either.right(responseFormat); + } else if (dataModelResponse.left() + .value() == null) { + log.debug("No response from updateResource"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return Either.left(dataModelResponse.left() + .value()); + } - String currentCreatorFullName = currentResource.getCreatorFullName(); - String updatedCreatorFullName = updateInfoResource.getCreatorFullName(); + private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) { + if (currentResource.getGroups() != null && !currentResource.getName() + .equals(newResource.getName())) { + List<GroupDefinition> updatedGroups = currentResource.getGroups() + .stream() + .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName())) + .collect(toList()); + newResource.setGroups(updatedGroups); + } + } - if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) { - log.debug("Resource Creator fullname is automatically set and cannot be updated"); - } + private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) { + GroupDefinition updatedGroup = new GroupDefinition(currGroup); + if (updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType() + .equals(DEFAULT_GROUP_VF_MODULE)) { + String prefix = updatedGroup.getName() + .substring(0, replacePattern.length()); + String newGroupName = updatedGroup.getName() + .replaceFirst(prefix, with); + updatedGroup.setName(newGroupName); + } + return updatedGroup; + } - String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId(); - String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId(); + /** + * validateResourceFieldsBeforeCreate + * + * @param user + * - modifier data (userId) + */ + private void validateResourceFieldsBeforeCreate(User user, Resource resource, + AuditingActionEnum actionEnum, boolean inTransaction) { + componentValidator.validate(user, resource, actionEnum); + // validate category + log.debug("validate category"); + validateCategory(user, resource, actionEnum, inTransaction); + // validate vendor name & release & model number + log.debug("validate vendor name"); + validateVendorName(user, resource, actionEnum); + log.debug("validate vendor release"); + validateVendorReleaseName(user, resource, actionEnum); + log.debug("validate resource vendor model number"); + validateResourceVendorModelNumber(user, resource, actionEnum); + // validate cost + log.debug("validate cost"); + validateCost(resource); + // validate licenseType + log.debug("validate licenseType"); + validateLicenseType(user, resource, actionEnum); + // validate template (derived from) + log.debug("validate derived from"); + if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) { + resource.setDerivedFrom(null); + } + validateDerivedFromExist(user, resource, actionEnum); + // warn about non-updatable fields + checkComponentFieldsForOverrideAttempt(resource); + String currentCreatorFullName = resource.getCreatorFullName(); + if (currentCreatorFullName != null) { + log.debug("Resource Creator fullname is automatically set and cannot be updated"); + } - if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) { - log.debug("Resource LastUpdater userId is automatically set and cannot be updated"); - } + String currentLastUpdaterFullName = resource.getLastUpdaterFullName(); + if (currentLastUpdaterFullName != null) { + log.debug("Resource LastUpdater fullname is automatically set and cannot be updated"); + } - String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName(); - String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName(); + Long currentLastUpdateDate = resource.getLastUpdateDate(); + if (currentLastUpdateDate != null) { + log.debug("Resource last update date is automatically set and cannot be updated"); + } - if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) { - log.debug("Resource LastUpdater fullname is automatically set and cannot be updated"); - } + Boolean currentAbstract = resource.isAbstract(); + if (currentAbstract != null) { + log.debug("Resource abstract is automatically set and cannot be updated"); + } + } - Long currentCreationDate = currentResource.getCreationDate(); - Long updatedCreationDate = updateInfoResource.getCreationDate(); + /** + * validateResourceFieldsBeforeUpdate + * + * @param currentResource + * - Resource object to validate + * @param isNested + */ + private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, + boolean inTransaction, boolean isNested) { + validateFields(currentResource, updateInfoResource, inTransaction, isNested); + warnNonEditableFields(currentResource, updateInfoResource); + } - if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) { - log.debug("Resource Creation date is automatically set and cannot be updated"); - } + private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) { + String currentResourceVersion = currentResource.getVersion(); + String updatedResourceVersion = updateInfoResource.getVersion(); - Long currentLastUpdateDate = currentResource.getLastUpdateDate(); - Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate(); + if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) { + log.debug("Resource version is automatically set and cannot be updated"); + } - if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) { - log.debug("Resource last update date is automatically set and cannot be updated"); - } + String currentCreatorUserId = currentResource.getCreatorUserId(); + String updatedCreatorUserId = updateInfoResource.getCreatorUserId(); - LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState(); - LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState(); + if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) { + log.debug("Resource Creator UserId is automatically set and cannot be updated"); + } - if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) { - log.debug("Resource lifecycle state date is automatically set and cannot be updated"); - } + String currentCreatorFullName = currentResource.getCreatorFullName(); + String updatedCreatorFullName = updateInfoResource.getCreatorFullName(); - Boolean currentAbstract = currentResource.isAbstract(); - Boolean updatedAbstract = updateInfoResource.isAbstract(); + if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) { + log.debug("Resource Creator fullname is automatically set and cannot be updated"); + } - if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) { - log.debug("Resource abstract is automatically set and cannot be updated"); - } + String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId(); + String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId(); - Boolean currentHighestVersion = currentResource.isHighestVersion(); - Boolean updatedHighestVersion = updateInfoResource.isHighestVersion(); + if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) { + log.debug("Resource LastUpdater userId is automatically set and cannot be updated"); + } - if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) { - log.debug("Resource highest version is automatically set and cannot be updated"); - } + String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName(); + String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName(); - String currentUuid = currentResource.getUUID(); - String updatedUuid = updateInfoResource.getUUID(); + if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) { + log.debug("Resource LastUpdater fullname is automatically set and cannot be updated"); + } + Long currentCreationDate = currentResource.getCreationDate(); + Long updatedCreationDate = updateInfoResource.getCreationDate(); - if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) { - log.debug("Resource UUID is automatically set and cannot be updated"); - } + if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) { + log.debug("Resource Creation date is automatically set and cannot be updated"); + } - ResourceTypeEnum currentResourceType = currentResource.getResourceType(); - ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType(); + Long currentLastUpdateDate = currentResource.getLastUpdateDate(); + Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate(); - if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) { - log.debug("Resource Type cannot be updated"); + if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) { + log.debug("Resource last update date is automatically set and cannot be updated"); + } - } - updateInfoResource.setResourceType(currentResource.getResourceType()); + LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState(); + LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState(); - String currentInvariantUuid = currentResource.getInvariantUUID(); - String updatedInvariantUuid = updateInfoResource.getInvariantUUID(); + if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) { + log.debug("Resource lifecycle state date is automatically set and cannot be updated"); + } - if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) { - log.debug("Resource invariant UUID is automatically set and cannot be updated"); - updateInfoResource.setInvariantUUID(currentInvariantUuid); - } - } + Boolean currentAbstract = currentResource.isAbstract(); + Boolean updatedAbstract = updateInfoResource.isAbstract(); - private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) { - boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion()); - log.debug("validate resource name before update"); - validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested); - log.debug("validate description before update"); - validateDescriptionAndCleanup(null, updateInfoResource, null); - log.debug("validate icon before update"); - validateIcon(currentResource, updateInfoResource, hasBeenCertified); - log.debug("validate tags before update"); - validateTagsListAndRemoveDuplicates(null, updateInfoResource, null); - log.debug("validate vendor name before update"); - validateVendorName(null, updateInfoResource, null); - log.debug("validate resource vendor model number before update"); - validateResourceVendorModelNumber(currentResource, updateInfoResource); - log.debug("validate vendor release before update"); - validateVendorReleaseName(null, updateInfoResource, null); - log.debug("validate contact info before update"); - validateContactId(null, updateInfoResource, null); - log.debug(VALIDATE_DERIVED_BEFORE_UPDATE); - validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified); - log.debug("validate category before update"); - validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction); - } + if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) { + log.debug("Resource abstract is automatically set and cannot be updated"); + } + Boolean currentHighestVersion = currentResource.isHighestVersion(); + Boolean updatedHighestVersion = updateInfoResource.isHighestVersion(); - private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) { - String resourceNameUpdated = updateInfoResource.getName(); - String resourceNameCurrent = currentResource.getName(); - if (resourceNameCurrent.equals(resourceNameUpdated)) { - return true; - } - // In case of CVFC type we should support the case of old VF with CVFC - // instances that were created without the "Cvfc" suffix - return currentResource.getResourceType().equals(ResourceTypeEnum.CVFC) && - resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent)); - } + if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) { + log.debug("Resource highest version is automatically set and cannot be updated"); + } - private String addCvfcSuffixToResourceName(String resourceName) { - return resourceName + "Cvfc"; - } + String currentUuid = currentResource.getUUID(); + String updatedUuid = updateInfoResource.getUUID(); - private void validateResourceName(Resource currentResource, Resource updateInfoResource, - boolean hasBeenCertified, boolean isNested) { - String resourceNameUpdated = updateInfoResource.getName(); - if (!isResourceNameEquals(currentResource, updateInfoResource)) { - if (isNested || !hasBeenCertified) { - validateComponentName(null, updateInfoResource, null); - validateResourceNameUniqueness(updateInfoResource); - currentResource.setName(resourceNameUpdated); - currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated)); - currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated)); + if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) { + log.debug("Resource UUID is automatically set and cannot be updated"); + } - } else { - log.info("Resource name: {}, cannot be updated once the resource has been certified once.", - resourceNameUpdated); - throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED); - } - } - } + log.debug("Resource Type cannot be updated"); + String currentInvariantUuid = currentResource.getInvariantUUID(); + String updatedInvariantUuid = updateInfoResource.getInvariantUUID(); - private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) { - String iconUpdated = updateInfoResource.getIcon(); - String iconCurrent = currentResource.getIcon(); - if (!iconCurrent.equals(iconUpdated)) { - if (!hasBeenCertified) { - validateIcon(null, updateInfoResource, null); - } else { - log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated); - throw new ByActionStatusComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED); - } - } - } + if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) { + log.debug("Resource invariant UUID is automatically set and cannot be updated"); + updateInfoResource.setInvariantUUID(currentInvariantUuid); + } + } - private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) { - String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber(); - String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber(); - if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) { - validateResourceVendorModelNumber(null, updateInfoResource, null); - } - } + private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, + boolean isNested) { + boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion()); + log.debug("validate resource name before update"); + validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested); + log.debug("validate description before update"); + componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null); + log.debug("validate icon before update"); + validateIcon(currentResource, updateInfoResource, hasBeenCertified); + log.debug("validate tags before update"); + componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null); + log.debug("validate vendor name before update"); + validateVendorName(null, updateInfoResource, null); + log.debug("validate resource vendor model number before update"); + validateResourceVendorModelNumber(currentResource, updateInfoResource); + log.debug("validate vendor release before update"); + validateVendorReleaseName(null, updateInfoResource, null); + log.debug("validate contact info before update"); + componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null); + log.debug(VALIDATE_DERIVED_BEFORE_UPDATE); + validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified); + log.debug("validate category before update"); + validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction); + } - private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource, - boolean hasBeenCertified, boolean inTransaction) { - validateCategory(null, updateInfoResource, null, inTransaction); - if (hasBeenCertified) { - CategoryDefinition currentCategory = currentResource.getCategories().get(0); - SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0); - CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0); - SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0); - if (!currentCategory.getName().equals(updateCategory.getName()) - || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) { - log.info("Category {} cannot be updated once the resource has been certified once.", - currentResource.getCategories()); - ResponseFormat errorResponse = componentsUtils - .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED); - return Either.right(errorResponse); - } - } - return Either.left(true); - } + private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) { + String resourceNameUpdated = updateInfoResource.getName(); + String resourceNameCurrent = currentResource.getName(); + if (resourceNameCurrent.equals(resourceNameUpdated)) { + return true; + } + // In case of CVFC type we should support the case of old VF with CVFC + // instances that were created without the "Cvfc" suffix + return currentResource.getResourceType() == ResourceTypeEnum.CVFC + && resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent)); + } - private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource, - Resource updateInfoResource, boolean hasBeenCertified) { + private String addCvfcSuffixToResourceName(String resourceName) { + return resourceName + "Cvfc"; + } - List<String> currentDerivedFrom = currentResource.getDerivedFrom(); - List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom(); - if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null - || updatedDerivedFrom.isEmpty()) { - log.trace("Update normative types"); - return Either.left(true); - } + private void validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, + boolean isNested) { + String resourceNameUpdated = updateInfoResource.getName(); + if (!isResourceNameEquals(currentResource, updateInfoResource)) { + if (isNested || !hasBeenCertified) { + componentNameValidator.validateAndCorrectField(null, updateInfoResource, null); + validateResourceNameUniqueness(updateInfoResource); + currentResource.setName(resourceNameUpdated); + currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated)); + currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated)); + + } else { + log.info("Resource name: {}, cannot be updated once the resource has been certified once.", + resourceNameUpdated); + throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED); + } + } + } - String derivedFromCurrent = currentDerivedFrom.get(0); - String derivedFromUpdated = updatedDerivedFrom.get(0); + private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) { + String iconUpdated = updateInfoResource.getIcon(); + String iconCurrent = currentResource.getIcon(); + if (!iconCurrent.equals(iconUpdated)) { + if (!hasBeenCertified) { + componentIconValidator.validateAndCorrectField(null, updateInfoResource, null); + } else { + log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated); + throw new ByActionStatusComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED); + } + } + } - if (!derivedFromCurrent.equals(derivedFromUpdated)) { - if (!hasBeenCertified) { - validateDerivedFromExist(null, updateInfoResource, null); - } else { - Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, - currentResource, updateInfoResource, null); + private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) { + String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber(); + String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber(); + if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) { + validateResourceVendorModelNumber(null, updateInfoResource, null); + } + } - if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) { - log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance"); - return validateDerivedFromExtending; - } - } - } else { - // For derived from, we must know whether it was actually changed, - // otherwise we must do no action. - // Due to changes it inflicts on data model (remove artifacts, - // properties...), it's not like a flat field which can be - // overwritten if not changed. - // So we must indicate that derived from is not changed - updateInfoResource.setDerivedFrom(null); - } - return Either.left(true); - } + private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource, + boolean hasBeenCertified, boolean inTransaction) { + validateCategory(null, updateInfoResource, null, inTransaction); + if (hasBeenCertified) { + CategoryDefinition currentCategory = currentResource.getCategories() + .get(0); + SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories() + .get(0); + CategoryDefinition updateCategory = updateInfoResource.getCategories() + .get(0); + SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories() + .get(0); + if (!currentCategory.getName() + .equals(updateCategory.getName()) + || !currentSubCategory.getName() + .equals(updtaeSubCategory.getName())) { + log.info("Category {} cannot be updated once the resource has been certified once.", + currentResource.getCategories()); + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED); + return Either.right(errorResponse); + } + } + return Either.left(true); + } - private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource, - Resource updateInfoResource, boolean hasBeenCertified) { + private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource, + Resource updateInfoResource, boolean hasBeenCertified) { - List<String> currentDerivedFrom = currentResource.getDerivedFrom(); - List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom(); - if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null - || updatedDerivedFrom.isEmpty()) { - log.trace("Update normative types"); - return Either.left(true); - } + List<String> currentDerivedFrom = currentResource.getDerivedFrom(); + List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom(); + if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null + || updatedDerivedFrom.isEmpty()) { + log.trace("Update normative types"); + return Either.left(true); + } - String derivedFromCurrent = currentDerivedFrom.get(0); - String derivedFromUpdated = updatedDerivedFrom.get(0); + String derivedFromCurrent = currentDerivedFrom.get(0); + String derivedFromUpdated = updatedDerivedFrom.get(0); + + if (!derivedFromCurrent.equals(derivedFromUpdated)) { + if (!hasBeenCertified) { + validateDerivedFromExist(null, updateInfoResource, null); + } else { + Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, + currentResource, updateInfoResource, null); + + if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left() + .value()) { + log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance"); + return validateDerivedFromExtending; + } + } + } else { + // For derived from, we must know whether it was actually changed, + // otherwise we must do no action. + // Due to changes it inflicts on data model (remove artifacts, + // properties...), it's not like a flat field which can be + // overwritten if not changed. + // So we must indicate that derived from is not changed + updateInfoResource.setDerivedFrom(null); + } + return Either.left(true); + } - if (!derivedFromCurrent.equals(derivedFromUpdated)) { - if (!hasBeenCertified) { - validateDerivedFromExist(null, updateInfoResource, null); - } else { - Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, - currentResource, updateInfoResource, null); + private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource, + Resource updateInfoResource, boolean hasBeenCertified) { - if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) { - log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance"); - return validateDerivedFromExtending; - } - } - } - return Either.left(true); - } - - private void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) { - if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) { - return; - } - String templateName = resource.getDerivedFrom().get(0); - Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade - .validateToscaResourceNameExists(templateName); - if (dataModelResponse.isRight()) { - StorageOperationStatus storageStatus = dataModelResponse.right().value(); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist"); - log.debug("request to data model failed with error: {}", storageStatus); - ResponseFormat responseFormat = componentsUtils - .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource); - log.trace("audit before sending response"); - componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus)); - } else if (!dataModelResponse.left().value()) { - log.info("resource template with name: {}, does not exists", templateName); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND); - componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw new ByActionStatusComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND); - } - } + List<String> currentDerivedFrom = currentResource.getDerivedFrom(); + List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom(); + if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null + || updatedDerivedFrom.isEmpty()) { + log.trace("Update normative types"); + return Either.left(true); + } - // Tal G for extending inheritance US815447 - private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource, - Resource updateInfoResource, AuditingActionEnum actionEnum) { - String currentTemplateName = currentResource.getDerivedFrom().get(0); - String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0); - - Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade - .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName); - if (dataModelResponse.isRight()) { - StorageOperationStatus storageStatus = dataModelResponse.right().value(); - BeEcompErrorManager.getInstance() - .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType"); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(storageStatus), currentResource); - log.trace("audit before sending response"); - componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum); - return Either.right(responseFormat); - } + String derivedFromCurrent = currentDerivedFrom.get(0); + String derivedFromUpdated = updatedDerivedFrom.get(0); + + if (!derivedFromCurrent.equals(derivedFromUpdated)) { + if (!hasBeenCertified) { + validateDerivedFromExist(null, updateInfoResource, null); + } else { + Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, + currentResource, updateInfoResource, null); + + if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left() + .value()) { + log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance"); + return validateDerivedFromExtending; + } + } + } + return Either.left(true); + } - if (!dataModelResponse.left().value()) { - log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, - currentTemplateName); - ResponseFormat responseFormat = componentsUtils - .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND); - componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum); + private void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) { + if (resource.getDerivedFrom() == null || resource.getDerivedFrom() + .isEmpty()) { + return; + } + String templateName = resource.getDerivedFrom() + .get(0); + Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade + .validateToscaResourceNameExists(templateName); + if (dataModelResponse.isRight()) { + StorageOperationStatus storageStatus = dataModelResponse.right() + .value(); + BeEcompErrorManager.getInstance() + .logBeDaoSystemError("Create Resource - validateDerivedFromExist"); + log.debug("request to data model failed with error: {}", storageStatus); + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource); + log.trace("audit before sending response"); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus)); + } else if (!dataModelResponse.left() + .value()) { + log.info("resource template with name: {}, does not exists", templateName); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + throw new ByActionStatusComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND); + } + } - return Either.right(responseFormat); + // Tal G for extending inheritance US815447 + private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource, + Resource updateInfoResource, AuditingActionEnum actionEnum) { + String currentTemplateName = currentResource.getDerivedFrom() + .get(0); + String updatedTemplateName = updateInfoResource.getDerivedFrom() + .get(0); + + Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade + .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName); + if (dataModelResponse.isRight()) { + StorageOperationStatus storageStatus = dataModelResponse.right() + .value(); + BeEcompErrorManager.getInstance() + .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType"); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(storageStatus), currentResource); + log.trace("audit before sending response"); + componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum); + return Either.right(responseFormat); + } - } - return Either.left(true); - } + if (!dataModelResponse.left() + .value()) { + log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, + currentTemplateName); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND); + componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum); - public void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) { - log.debug("validate resource derivedFrom field"); - if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) - || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) { - log.info("derived from (template) field is missing for the resource"); - ResponseFormat responseFormat = componentsUtils - .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); - componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + return Either.right(responseFormat); - throw new ByActionStatusComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); - } - } + } + return Either.left(true); + } - private void validateResourceNameUniqueness(Resource resource) { - - Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade - .validateComponentNameExists(resource.getName(), resource.getResourceType(), - resource.getComponentType()); - if (resourceOperationResponse.isLeft() && resourceOperationResponse.left().value()) { - log.debug("resource with name: {}, already exists", resource.getName()); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), - resource.getName()); - } else if(resourceOperationResponse.isRight()){ - log.debug("error while validateResourceNameExists for resource: {}", resource.getName()); - throw new StorageException(resourceOperationResponse.right().value()); - } - } + public void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) { + log.debug("validate resource derivedFrom field"); + if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom() + .isEmpty()) + || (resource.getDerivedFrom() + .get(0)) == null + || (resource.getDerivedFrom() + .get(0) + .trim() + .isEmpty())) { + log.info("derived from (template) field is missing for the resource"); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + + throw new ByActionStatusComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + } + } + private void validateResourceNameUniqueness(Resource resource) { + + Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade + .validateComponentNameExists(resource.getName(), resource.getResourceType(), + resource.getComponentType()); + if (resourceOperationResponse.isLeft() && resourceOperationResponse.left() + .value()) { + log.debug("resource with name: {}, already exists", resource.getName()); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, + ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); + } else if (resourceOperationResponse.isRight()) { + log.debug("error while validateResourceNameExists for resource: {}", resource.getName()); + throw new StorageException(resourceOperationResponse.right() + .value()); + } + } - private void validateCategory(User user, Resource resource, - AuditingActionEnum actionEnum, boolean inTransaction) { + private void validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) { - List<CategoryDefinition> categories = resource.getCategories(); - if (CollectionUtils.isEmpty(categories)) { - log.debug(CATEGORY_IS_EMPTY); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, - ComponentTypeEnum.RESOURCE.getValue()); - componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, - ComponentTypeEnum.RESOURCE.getValue()); - } - if (categories.size() > 1) { - log.debug("Must be only one category for resource"); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue()); - } - CategoryDefinition category = categories.get(0); - List<SubCategoryDefinition> subcategories = category.getSubcategories(); - if (CollectionUtils.isEmpty(subcategories)) { - log.debug("Missinig subcategory for resource"); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY); - } - if (subcategories.size() > 1) { - log.debug("Must be only one sub category for resource"); - throw new ByActionStatusComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES); - } + List<CategoryDefinition> categories = resource.getCategories(); + if (CollectionUtils.isEmpty(categories)) { + log.debug(CATEGORY_IS_EMPTY); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, + ComponentTypeEnum.RESOURCE.getValue()); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, + ComponentTypeEnum.RESOURCE.getValue()); + } + if (categories.size() > 1) { + log.debug("Must be only one category for resource"); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, + ComponentTypeEnum.RESOURCE.getValue()); + } + CategoryDefinition category = categories.get(0); + List<SubCategoryDefinition> subcategories = category.getSubcategories(); + if (CollectionUtils.isEmpty(subcategories)) { + log.debug("Missinig subcategory for resource"); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY); + } + if (subcategories.size() > 1) { + log.debug("Must be only one sub category for resource"); + throw new ByActionStatusComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES); + } - SubCategoryDefinition subcategory = subcategories.get(0); + SubCategoryDefinition subcategory = subcategories.get(0); - if (!ValidationUtils.validateStringNotEmpty(category.getName())) { - log.debug(CATEGORY_IS_EMPTY); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, - ComponentTypeEnum.RESOURCE.getValue()); - componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, - ComponentTypeEnum.RESOURCE.getValue()); - } - if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) { - log.debug(CATEGORY_IS_EMPTY); - ResponseFormat responseFormat = componentsUtils.getResponseFormat( - ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue()); - componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue()); - } + if (!ValidationUtils.validateStringNotEmpty(category.getName())) { + log.debug(CATEGORY_IS_EMPTY); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, + ComponentTypeEnum.RESOURCE.getValue()); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, + ComponentTypeEnum.RESOURCE.getValue()); + } + if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) { + log.debug(CATEGORY_IS_EMPTY); + ResponseFormat responseFormat = componentsUtils.getResponseFormat( + ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, + ComponentTypeEnum.RESOURCE.getValue()); + } - validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction); - } + validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction); + } - private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, - User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) { - ResponseFormat responseFormat; - if (category != null && subcategory != null) { - log.debug("validating resource category {} against valid categories list", category); - Either<List<CategoryDefinition>, ActionStatus> categories = elementDao - .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction); - if (categories.isRight()) { - log.debug("failed to retrieve resource categories from JanusGraph"); - responseFormat = componentsUtils.getResponseFormat(categories.right().value()); - componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw new ByActionStatusComponentException(categories.right().value()); - } - List<CategoryDefinition> categoryList = categories.left().value(); - Optional<CategoryDefinition> foundCategory = categoryList.stream() - .filter(cat -> cat.getName().equals(category.getName())) - .findFirst(); - if(!foundCategory.isPresent()){ - log.debug("Category {} is not part of resource category group. Resource category valid values are {}", - category, categoryList); - failOnInvalidCategory(user, resource, actionEnum); - } - Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get() - .getSubcategories() - .stream() - .filter(subcat -> subcat.getName().equals(subcategory.getName())) - .findFirst(); - if(!foundSubcategory.isPresent()){ - log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", - subcategory, foundCategory.get().getSubcategories()); - failOnInvalidCategory(user, resource, actionEnum); - } - } - } + private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, User user, + Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) { + ResponseFormat responseFormat; + if (category != null && subcategory != null) { + log.debug("validating resource category {} against valid categories list", category); + Either<List<CategoryDefinition>, ActionStatus> categories = elementDao + .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction); + if (categories.isRight()) { + log.debug("failed to retrieve resource categories from JanusGraph"); + responseFormat = componentsUtils.getResponseFormat(categories.right() + .value()); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + throw new ByActionStatusComponentException(categories.right() + .value()); + } + List<CategoryDefinition> categoryList = categories.left() + .value(); + Optional<CategoryDefinition> foundCategory = categoryList.stream() + .filter(cat -> cat.getName() + .equals(category.getName())) + .findFirst(); + if (!foundCategory.isPresent()) { + log.debug("Category {} is not part of resource category group. Resource category valid values are {}", + category, categoryList); + failOnInvalidCategory(user, resource, actionEnum); + } + Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get() + .getSubcategories() + .stream() + .filter(subcat -> subcat.getName() + .equals(subcategory.getName())) + .findFirst(); + if (!foundSubcategory.isPresent()) { + log.debug( + "SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", + subcategory, foundCategory.get() + .getSubcategories()); + failOnInvalidCategory(user, resource, actionEnum); + } + } + } - private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) { - ResponseFormat responseFormat; - responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, - ComponentTypeEnum.RESOURCE.getValue()); - componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, - ComponentTypeEnum.RESOURCE.getValue()); - } + private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) { + ResponseFormat responseFormat; + responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, + ComponentTypeEnum.RESOURCE.getValue()); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + } - public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) { - String vendorRelease = resource.getVendorRelease(); - log.debug("validate vendor relese name"); - if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) { - log.info("vendor relese name is missing."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE); - componentsUtils.auditResource(errorResponse, user, resource, actionEnum); - throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_RELEASE); - } + public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) { + String vendorRelease = resource.getVendorRelease(); + log.debug("validate vendor relese name"); + if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) { + log.info("vendor relese name is missing."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE); + componentsUtils.auditResource(errorResponse, user, resource, actionEnum); + throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_RELEASE); + } - validateVendorReleaseName(vendorRelease, user, resource, actionEnum); - } + validateVendorReleaseName(vendorRelease, user, resource, actionEnum); + } - public void validateVendorReleaseName(String vendorRelease, User user, Resource resource, AuditingActionEnum actionEnum) { - if (vendorRelease != null) { - if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) { - log.info("vendor release exceds limit."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat( - ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); - componentsUtils.auditResource(errorResponse, user, resource, actionEnum); - throw new ByActionStatusComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); - } + public void validateVendorReleaseName(String vendorRelease, User user, Resource resource, + AuditingActionEnum actionEnum) { + if (vendorRelease != null) { + if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) { + log.info("vendor release exceds limit."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat( + ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); + componentsUtils.auditResource(errorResponse, user, resource, actionEnum); + throw new ByActionStatusComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, + "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); + } - if (!ValidationUtils.validateVendorRelease(vendorRelease)) { - log.info("vendor release is not valid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE); - componentsUtils.auditResource(errorResponse, user, resource, actionEnum); + if (!ValidationUtils.validateVendorRelease(vendorRelease)) { + log.info("vendor release is not valid."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE); + componentsUtils.auditResource(errorResponse, user, resource, actionEnum); throw new ByActionStatusComponentException(ActionStatus.INVALID_VENDOR_RELEASE, vendorRelease); } } @@ -4838,449 +5439,467 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } } - private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource, - Resource updatedResource, String userId, boolean inTransaction) { - Either<Operation, ResponseFormat> deleteArtifactByInterface; - if (updatedResource.getDerivedFrom() != null) { - log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId()); - log.debug("1. Removing interface artifacts from graph"); - // Remove all interface artifacts of resource - String resourceId = updatedResource.getUniqueId(); - Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces(); - - if (interfaces != null) { - Collection<InterfaceDefinition> values = interfaces.values(); - for (InterfaceDefinition interfaceDefinition : values) { - String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition); - - log.trace("Starting interface artifacts removal for interface type {}", interfaceType); - Map<String, Operation> operations = interfaceDefinition.getOperationsMap(); - if (operations != null) { - for (Entry<String, Operation> operationEntry : operations.entrySet()) { - Operation operation = operationEntry.getValue(); - ArtifactDefinition implementation = operation.getImplementationArtifact(); - if (implementation != null) { - String uniqueId = implementation.getUniqueId(); - log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}", - uniqueId, operationEntry.getKey(), interfaceType); - // only thing that transacts and locks here - deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId, - userId, uniqueId, - true); - if (deleteArtifactByInterface.isRight()) { - log.debug("Couldn't remove artifact definition with id {}", uniqueId); - if (!inTransaction) { + private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource, + Resource updatedResource, String userId, boolean inTransaction) { + Either<Operation, ResponseFormat> deleteArtifactByInterface; + if (updatedResource.getDerivedFrom() != null) { + log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId()); + log.debug("1. Removing interface artifacts from graph"); + // Remove all interface artifacts of resource + String resourceId = updatedResource.getUniqueId(); + Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces(); + + if (interfaces != null) { + Collection<InterfaceDefinition> values = interfaces.values(); + for (InterfaceDefinition interfaceDefinition : values) { + String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition); + + log.trace("Starting interface artifacts removal for interface type {}", interfaceType); + Map<String, Operation> operations = interfaceDefinition.getOperationsMap(); + if (operations != null) { + for (Entry<String, Operation> operationEntry : operations.entrySet()) { + Operation operation = operationEntry.getValue(); + ArtifactDefinition implementation = operation.getImplementationArtifact(); + if (implementation != null) { + String uniqueId = implementation.getUniqueId(); + log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}", + uniqueId, operationEntry.getKey(), interfaceType); + // only thing that transacts and locks here + deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId, + userId, uniqueId, true); + if (deleteArtifactByInterface.isRight()) { + log.debug("Couldn't remove artifact definition with id {}", uniqueId); + if (!inTransaction) { janusGraphDao.rollback(); - } - return Either.right(deleteArtifactByInterface.right().value()); - } - } else { - log.trace("No implementation found for operation {} - nothing to delete", - operationEntry.getKey()); - } - } - } else { - log.trace("No operations found for interface type {}", interfaceType); - } - } - } - log.debug("2. Removing properties"); - Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation - .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId); - - if (findPropertiesOfNode.isRight() - && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) { - log.debug("Failed to remove all properties of resource"); - if (!inTransaction) { + } + return Either.right(deleteArtifactByInterface.right() + .value()); + } + } else { + log.trace("No implementation found for operation {} - nothing to delete", + operationEntry.getKey()); + } + } + } else { + log.trace("No operations found for interface type {}", interfaceType); + } + } + } + log.debug("2. Removing properties"); + Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation + .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId); + + if (findPropertiesOfNode.isRight() && findPropertiesOfNode.right().value() != StorageOperationStatus.OK) { + log.debug("Failed to remove all properties of resource"); + if (!inTransaction) { janusGraphDao.rollback(); - } - return Either.right(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value()))); - } + } + return Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right() + .value()))); + } - } else { - log.debug("Derived from wasn't changed during update"); - } + } else { + log.debug("Derived from wasn't changed during update"); + } - if (inTransaction) { - return Either.left(true); - } + if (inTransaction) { + return Either.left(true); + } janusGraphDao.commit(); - return Either.left(true); - - } + return Either.left(true); - /**** Auditing *******************/ - - protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context - .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + } - return webApplicationContext.getBean(class1); - } + /**** Auditing *******************/ - public ICapabilityTypeOperation getCapabilityTypeOperation() { - return capabilityTypeOperation; - } + protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context + .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - @Autowired - public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) { - this.capabilityTypeOperation = capabilityTypeOperation; - } + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - public Either<Boolean, ResponseFormat> validatePropertiesDefaultValues(Resource resource) { - log.debug("validate resource properties default values"); - Either<Boolean, ResponseFormat> eitherResult = Either.left(true); - List<PropertyDefinition> properties = resource.getProperties(); - if (properties != null) { - eitherResult = iterateOverProperties(properties); - } - return eitherResult; - } + return webApplicationContext.getBean(class1); + } - public Either<Boolean, ResponseFormat> iterateOverProperties(List<PropertyDefinition> properties){ - Either<Boolean, ResponseFormat> eitherResult = Either.left(true); - String type = null; - String innerType = null; - for (PropertyDefinition property : properties) { - if (!propertyOperation.isPropertyTypeValid(property)) { - log.info("Invalid type for property {}", property); - ResponseFormat responseFormat = componentsUtils.getResponseFormat( - ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName()); - eitherResult = Either.right(responseFormat); - break; - } + public ICapabilityTypeOperation getCapabilityTypeOperation() { + return capabilityTypeOperation; + } - Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes( - applicationDataTypeCache); - if (allDataTypes.isRight()) { - return Either.right(allDataTypes.right().value()); - } + @Autowired + public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) { + this.capabilityTypeOperation = capabilityTypeOperation; + } - type = property.getType(); + public Boolean validatePropertiesDefaultValues(Resource resource) { + log.debug("validate resource properties default values"); + List<PropertyDefinition> properties = resource.getProperties(); + if (properties != null) { + iterateOverProperties(properties); + } + return true; + } - if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { - ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes.left().value()); - if(responseFormat != null) { - break; - } - } - eitherResult = validateDefaultPropertyValue(property, allDataTypes.left().value(), type, innerType); - } - return eitherResult; - } + public void iterateOverProperties(List<PropertyDefinition> properties) { + String type = null; + String innerType = null; + for (PropertyDefinition property : properties) { + if (!propertyOperation.isPropertyTypeValid(property)) { + log.info("Invalid type for property {}", property); + throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_TYPE, + property.getType(), property.getName()); + } - private Either<Boolean,ResponseFormat> validateDefaultPropertyValue(PropertyDefinition property, Map<String, DataTypeDefinition> allDataTypes, String type, String innerType) { - if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) { - log.info("Invalid default value for property {}", property); - ResponseFormat responseFormat; - if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, - property.getName(), type, innerType, property.getDefaultValue()); - } else { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, - property.getName(), type, property.getDefaultValue()); - } - return Either.right(responseFormat); + Map<String, DataTypeDefinition> allDataTypes = getAllDataTypes(applicationDataTypeCache); + type = property.getType(); - } - return Either.left(true); - } + if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { + ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes); + if (responseFormat != null) { + break; + } + } + validateDefaultPropertyValue(property, allDataTypes, type, innerType); + } + } - private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType, Map<String, DataTypeDefinition> allDataTypes) { - ResponseFormat responseFormat = null; - ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation - .isPropertyInnerTypeValid(property, allDataTypes); - innerType = propertyInnerTypeValid.getLeft(); - if (!propertyInnerTypeValid.getRight().booleanValue()) { - log.info("Invalid inner type for property {}", property); - responseFormat = componentsUtils.getResponseFormat( - ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName()); - } - return responseFormat; - } + private void validateDefaultPropertyValue(PropertyDefinition property, + Map<String, DataTypeDefinition> allDataTypes, String type, String innerType) { + if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) { + log.info("Invalid default value for property {}", property); + ResponseFormat responseFormat; + if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { + throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, + property.getName(), type, innerType, property.getDefaultValue()); + } + throw new ByActionStatusComponentException(ActionStatus.INVALID_DEFAULT_VALUE, + property.getName(), type, property.getDefaultValue()); + } + } - @Override - public Either<List<String>, ResponseFormat> deleteMarkedComponents() { - return deleteMarkedComponents(ComponentTypeEnum.RESOURCE); - } + private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType, + Map<String, DataTypeDefinition> allDataTypes) { + ResponseFormat responseFormat = null; + ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, + allDataTypes); + innerType = propertyInnerTypeValid.getLeft(); + if (!propertyInnerTypeValid.getRight() + .booleanValue()) { + log.info("Invalid inner type for property {}", property); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, + property.getName()); + } + return responseFormat; + } - @Override - public ComponentInstanceBusinessLogic getComponentInstanceBL() { - return componentInstanceBusinessLogic; - } + @Override + public Either<List<String>, ResponseFormat> deleteMarkedComponents() { + return deleteMarkedComponents(ComponentTypeEnum.RESOURCE); + } - private String getComponentTypeForResponse(Component component) { - String componentTypeForResponse = "SERVICE"; - if (component instanceof Resource) { - componentTypeForResponse = ((Resource) component).getResourceType().name(); - } - return componentTypeForResponse; - } + @Override + public ComponentInstanceBusinessLogic getComponentInstanceBL() { + return componentInstanceBusinessLogic; + } - public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) { - // validate user - if (user != null) { - validateUserExists(user, "Get resource from csar UUID", - false); - } - // get resource from csar uuid - Either<Resource, StorageOperationStatus> either = toscaOperationFacade - .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, ""); - if (either.isRight()) { - ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND, - csarUuid); - return Either.right(resp); - } + private String getComponentTypeForResponse(Component component) { + String componentTypeForResponse = "SERVICE"; + if (component instanceof Resource) { + componentTypeForResponse = ((Resource) component).getResourceType() + .name(); + } + return componentTypeForResponse; + } - return Either.left(either.left().value()); - } + public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) { + // validate user + if (user != null) { + validateUserExists(user); + } + // get resource from csar uuid + Either<Resource, StorageOperationStatus> either = toscaOperationFacade + .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, ""); + if (either.isRight()) { + ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND, + csarUuid); + return Either.right(resp); + } - @Override - public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs( - String componentId, String userId) { - return null; - } + return Either.left(either.left() + .value()); + } - private Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities( - String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, - Map<String, List<UploadCapInfo>> uploadedCapabilities) { + @Override + public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs( + String componentId, String userId) { + return null; + } - Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>(); - uploadedCapabilities.forEach((k,v)->addValidComponentInstanceCapabilities(k,v,resourceId,defaultCapabilities,validCapabilitiesMap)); - return validCapabilitiesMap; - } + private Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(String resourceId, + Map<String, List<CapabilityDefinition>> defaultCapabilities, + Map<String, List<UploadCapInfo>> uploadedCapabilities) { - private void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, Map<String, List<CapabilityDefinition>> validCapabilitiesMap){ - String capabilityType = capabilities.get(0).getType(); - if (defaultCapabilities.containsKey(capabilityType)) { - CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType); - validateCapabilityProperties(capabilities, resourceId, defaultCapability); - List<CapabilityDefinition> validCapabilityList = new ArrayList<>(); - validCapabilityList.add(defaultCapability); - validCapabilitiesMap.put(key, validCapabilityList); - } else { - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType)); - } - } + Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>(); + uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId, + defaultCapabilities, validCapabilitiesMap)); + return validCapabilitiesMap; + } - private void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId, CapabilityDefinition defaultCapability) { - if (CollectionUtils.isEmpty(defaultCapability.getProperties()) - && isNotEmpty(capabilities.get(0).getProperties())) { - log.debug("Failed to validate capability {} of component {}. Property list is empty. ", - defaultCapability.getName(), resourceId); - log.debug( - "Failed to update capability property values. Property list of fetched capability {} is empty. ", - defaultCapability.getName()); - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId)); - } else if (isNotEmpty(capabilities.get(0).getProperties())) { - validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0)); - } - } + private void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId, + Map<String, List<CapabilityDefinition>> defaultCapabilities, + Map<String, List<CapabilityDefinition>> validCapabilitiesMap) { + String capabilityType = capabilities.get(0) + .getType(); + if (defaultCapabilities.containsKey(capabilityType)) { + CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType); + validateCapabilityProperties(capabilities, resourceId, defaultCapability); + List<CapabilityDefinition> validCapabilityList = new ArrayList<>(); + validCapabilityList.add(defaultCapability); + validCapabilitiesMap.put(key, validCapabilityList); + } else { + throw new ByActionStatusComponentException(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType); + } + } - private CapabilityDefinition getCapability(String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, String capabilityType) { - CapabilityDefinition defaultCapability; - if (isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) { - defaultCapability = defaultCapabilities.get(capabilityType).get(0); - } else { - Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade - .getToscaFullElement(resourceId); - if (getFullComponentRes.isRight()) { - log.debug("Failed to get full component {}. Status is {}. ", resourceId, - getFullComponentRes.right().value()); - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, - resourceId)); - } - defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0); - } - return defaultCapability; - } + private void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId, + CapabilityDefinition defaultCapability) { + if (CollectionUtils.isEmpty(defaultCapability.getProperties()) && isNotEmpty(capabilities.get(0) + .getProperties())) { + log.debug("Failed to validate capability {} of component {}. Property list is empty. ", + defaultCapability.getName(), resourceId); + log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ", + defaultCapability.getName()); + throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, resourceId); + } else if (isNotEmpty(capabilities.get(0) + .getProperties())) { + validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0)); + } + } - private void validateUniquenessUpdateUploadedComponentInstanceCapability( - CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) { - List<ComponentInstanceProperty> validProperties = new ArrayList<>(); - Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream() - .collect(toMap(PropertyDefinition::getName, Function.identity())); - List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties(); - for (UploadPropInfo property : uploadedProperties) { - String propertyName = property.getName().toLowerCase(); - String propertyType = property.getType(); - ComponentInstanceProperty validProperty; - if (defaultProperties.containsKey(propertyName) && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) { - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, - propertyName)); - } - validProperty = new ComponentInstanceProperty(); - validProperty.setName(propertyName); - if (property.getValue() != null) { - validProperty.setValue(property.getValue().toString()); - } - validProperty.setDescription(property.getDescription()); - validProperty.setPassword(property.isPassword()); - validProperties.add(validProperty); - } - defaultCapability.setProperties(validProperties); - } + private CapabilityDefinition getCapability(String resourceId, + Map<String, List<CapabilityDefinition>> defaultCapabilities, String capabilityType) { + CapabilityDefinition defaultCapability; + if (isNotEmpty(defaultCapabilities.get(capabilityType) + .get(0) + .getProperties())) { + defaultCapability = defaultCapabilities.get(capabilityType) + .get(0); + } else { + Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade + .getToscaFullElement(resourceId); + if (getFullComponentRes.isRight()) { + log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right() + .value()); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NOT_FOUND, resourceId); + } + defaultCapability = getFullComponentRes.left() + .value() + .getCapabilities() + .get(capabilityType) + .get(0); + } + return defaultCapability; + } - private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName, String propertyType) { - return propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType); - } + private void validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability, + UploadCapInfo uploadedCapability) { + List<ComponentInstanceProperty> validProperties = new ArrayList<>(); + Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties() + .stream() + .collect(toMap(PropertyDefinition::getName, Function.identity())); + List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties(); + for (UploadPropInfo property : uploadedProperties) { + String propertyName = property.getName() + .toLowerCase(); + String propertyType = property.getType(); + ComponentInstanceProperty validProperty; + if (defaultProperties.containsKey(propertyName) + && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) { + throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, propertyName); + } + validProperty = new ComponentInstanceProperty(); + validProperty.setName(propertyName); + if (property.getValue() != null) { + validProperty.setValue(property.getValue() + .toString()); + } + validProperty.setDescription(property.getDescription()); + validProperty.setPassword(property.isPassword()); + validProperties.add(validProperty); + } + defaultCapability.setProperties(validProperties); + } - private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation( - List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle, - Resource resource, User user) { + private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName, + String propertyType) { + return propertyType != null && !defaultProperties.get(propertyName) + .getType() + .equals(propertyType); + } - EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>( - ArtifactOperationEnum.class); - Wrapper<ResponseFormat> responseWrapper = new Wrapper<>(); - Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either - .left(nodeTypeArtifactsToHandle); - try { - // add all found Csar artifacts to list to upload - List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList); - List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>(); - List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>(); - for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) { - ArtifactDefinition foundArtifact; - - if (!existingArtifactsToHandle.isEmpty()) { - foundArtifact = existingArtifactsToHandle.stream() - .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst() - .orElse(null); - if (foundArtifact != null) { - if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact - .getArtifactType()) { - if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) { - currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId()); - // if current artifact already exists, but has - // different content, add him to the list to - // update - artifactsToUpdate.add(currNewArtifact); - } - // remove found artifact from the list of existing - // artifacts to handle, because it was already - // handled - existingArtifactsToHandle.remove(foundArtifact); - // and remove found artifact from the list to - // upload, because it should either be updated or be - // ignored - artifactsToUpload.remove(currNewArtifact); - } else { - log.debug("Can't upload two artifact with the same name {}.", - currNewArtifact.getArtifactName()); - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat( - ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, - currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType().name(), - foundArtifact.getArtifactType()); - AuditingActionEnum auditingAction = artifactsBusinessLogic - .detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false, - ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum()); - artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(), - user, null, null, foundArtifact.getUniqueId(), responseFormat, - resource.getComponentType(), null); - responseWrapper.setInnerElement(responseFormat); - break; - } - } - } - } - if (responseWrapper.isEmpty()) { - for (ArtifactDefinition currArtifact : existingArtifactsToHandle) { - if (currArtifact.getIsFromCsar()) { - artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar())); - } else { - artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar())); - - } - } - } - if (responseWrapper.isEmpty()) { - if (!artifactsToUpload.isEmpty()) { - nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload); - } - if (!artifactsToUpdate.isEmpty()) { - nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate); - } - if (!artifactsToDelete.isEmpty()) { - nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete); - } - } - if (!responseWrapper.isEmpty()) { - nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement()); - } - } catch (Exception e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - responseWrapper.setInnerElement(responseFormat); - log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e); - nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement()); - } - return nodeTypeArtifactsToHandleRes; - } + private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation( + List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle, + Resource resource, User user) { + + EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>( + ArtifactOperationEnum.class); + Wrapper<ResponseFormat> responseWrapper = new Wrapper<>(); + Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either + .left(nodeTypeArtifactsToHandle); + try { + // add all found Csar artifacts to list to upload + List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList); + List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>(); + List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>(); + for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) { + ArtifactDefinition foundArtifact; + + if (!existingArtifactsToHandle.isEmpty()) { + foundArtifact = existingArtifactsToHandle.stream() + .filter(a -> a.getArtifactName() + .equals(currNewArtifact.getArtifactName())) + .findFirst() + .orElse(null); + if (foundArtifact != null) { + if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact + .getArtifactType()) { + if (!foundArtifact.getArtifactChecksum() + .equals(currNewArtifact.getArtifactChecksum())) { + currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId()); + // if current artifact already exists, but has + // different content, add him to the list to + // update + artifactsToUpdate.add(currNewArtifact); + } + // remove found artifact from the list of existing + // artifacts to handle, because it was already + // handled + existingArtifactsToHandle.remove(foundArtifact); + // and remove found artifact from the list to + // upload, because it should either be updated or be + // ignored + artifactsToUpload.remove(currNewArtifact); + } else { + log.debug("Can't upload two artifact with the same name {}.", + currNewArtifact.getArtifactName()); + ResponseFormat responseFormat = ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, + currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType() + .name(), + foundArtifact.getArtifactType()); + AuditingActionEnum auditingAction = artifactsBusinessLogic + .detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false, + ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum()); + artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(), + user, null, null, foundArtifact.getUniqueId(), responseFormat, + resource.getComponentType(), null); + responseWrapper.setInnerElement(responseFormat); + break; + } + } + } + } + if (responseWrapper.isEmpty()) { + for (ArtifactDefinition currArtifact : existingArtifactsToHandle) { + if (currArtifact.getIsFromCsar()) { + artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, + ArtifactTypeEnum.findType(currArtifact.getArtifactType()), + currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), + currArtifact.getIsFromCsar())); + } else { + artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, + ArtifactTypeEnum.findType(currArtifact.getArtifactType()), + currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), + currArtifact.getIsFromCsar())); + + } + } + } + if (responseWrapper.isEmpty()) { + if (!artifactsToUpload.isEmpty()) { + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload); + } + if (!artifactsToUpdate.isEmpty()) { + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate); + } + if (!artifactsToDelete.isEmpty()) { + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete); + } + } + if (!responseWrapper.isEmpty()) { + nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement()); + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + responseWrapper.setInnerElement(responseFormat); + log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e); + } + return nodeTypeArtifactsToHandleRes; + } - ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, - String nodeTypeFullName) { - String actualType; - String actualVfName; - if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) { - actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name(); - actualType = ResourceTypeEnum.VFC.name(); - } else { - actualVfName = vfResourceName; - actualType = nodeResourceType; - } + ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, + String nodeTypeFullName) { + String actualType; + String actualVfName; + if (ResourceTypeEnum.CVFC.name() + .equals(nodeResourceType)) { + actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name(); + actualType = ResourceTypeEnum.VFC.name(); + } else { + actualVfName = vfResourceName; + actualType = nodeResourceType; + } String nameWithouNamespacePrefix; - try { - StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX); + try { + StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX); if (!nodeTypeFullName.contains(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)){ - nameWithouNamespacePrefix = nodeTypeFullName; + nameWithouNamespacePrefix = nodeTypeFullName; } else { nameWithouNamespacePrefix = nodeTypeFullName - .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); - } - String[] findTypes = nameWithouNamespacePrefix.split("\\."); - String resourceType = findTypes[0]; - String actualName = nameWithouNamespacePrefix.substring(resourceType.length()); - - if (actualName.startsWith(Constants.ABSTRACT)) { - toscaResourceName.append(resourceType.toLowerCase()).append('.') - .append(ValidationUtils.convertToSystemName(actualVfName)); - } else { - toscaResourceName.append(actualType.toLowerCase()).append('.') - .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT); - } - StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName); - return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(), - previousToscaResourceName - .append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase()) - .toString()); - } catch (Exception e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE); - log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e); - throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName); - } - } + .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); + } String[] findTypes = nameWithouNamespacePrefix.split("\\."); + String resourceType = findTypes[0]; + String actualName = nameWithouNamespacePrefix.substring(resourceType.length()); + + if (actualName.startsWith(Constants.ABSTRACT)) { + toscaResourceName.append(resourceType.toLowerCase()).append('.') + .append(ValidationUtils.convertToSystemName(actualVfName)); + } else { + toscaResourceName.append(actualType.toLowerCase()).append('.') + .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT); + } + StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName); + return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(), + previousToscaResourceName + .append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase()) + .toString()); + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE); + log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e); + throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName); + } + } - @Override + @Override public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId, List<String> dataParamsToReturn) { ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn); Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, - paramsToRetuen); + paramsToRetuen); if (resourceResultEither.isRight()) { - if (resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + if (resourceResultEither.right().value() == StorageOperationStatus.NOT_FOUND) { log.debug("Failed to found resource with id {} ", resourceId); Either .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); } log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn); - return Either.right(componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), "")); + return Either.right(componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right() + .value()), "")); } Resource resource = resourceResultEither.left().value(); @@ -5294,19 +5913,20 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.left(dataTransfer); } - @Override - public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) { - Resource resource = (Resource) clonedComponent; - if (ModelConverter.isAtomicComponent(resource.getResourceType())) { - Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade - .shouldUpgradeToLatestDerived(resource); - if (shouldUpgradeToLatestDerived.isRight()) { - return Either.right( - componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right().value())); - } - return Either.left(shouldUpgradeToLatestDerived.left().value()); - } else { - return super.shouldUpgradeToLatestDerived(clonedComponent); - } - } + @Override + public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) { + Resource resource = (Resource) clonedComponent; + if (ModelConverter.isAtomicComponent(resource.getResourceType())) { + Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade + .shouldUpgradeToLatestDerived(resource); + if (shouldUpgradeToLatestDerived.isRight()) { + return Either.right(componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right() + .value())); + } + return Either.left(shouldUpgradeToLatestDerived.left() + .value()); + } else { + return super.shouldUpgradeToLatestDerived(clonedComponent); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java index 7d1729bcff..dfd7c6c58d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java @@ -32,6 +32,7 @@ import org.openecomp.sdc.be.components.csar.CsarInfo; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.Constants; import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; +import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -43,7 +44,16 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; -import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.InterfaceDefinition; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.UploadResourceInfo; +import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; @@ -65,8 +75,15 @@ import org.springframework.web.context.WebApplicationContext; import org.yaml.snakeyaml.Yaml; import javax.servlet.ServletContext; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.Set; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -100,26 +117,27 @@ public class ResourceImportManager { this.toscaOperationFacade = toscaOperationFacade; } - public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importNormativeResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) { + public ImmutablePair<Resource, ActionStatus> importNormativeResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) { LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(); lifecycleChangeInfo.setUserRemarks("certification on import"); - Function<Resource, Either<Boolean, ResponseFormat>> validator = resource -> resourceBusinessLogic.validatePropertiesDefaultValues(resource); + Function<Resource, Boolean> validator = resource -> resourceBusinessLogic.validatePropertiesDefaultValues(resource); return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false, null, null, false); } - public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importNormativeResourceFromCsar(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) { + public ImmutablePair<Resource, ActionStatus> importNormativeResourceFromCsar(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) { LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(); lifecycleChangeInfo.setUserRemarks("certification on import"); - Function<Resource, Either<Boolean, ResponseFormat>> validator = resource -> resourceBusinessLogic.validatePropertiesDefaultValues(resource); + Function<Resource, Boolean> validator = resource -> resourceBusinessLogic.validatePropertiesDefaultValues(resource); return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false, null, null, false); } - public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importCertifiedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, Function<Resource, Either<Boolean, ResponseFormat>> validationFunction, - LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName, boolean isNested) { + public ImmutablePair<Resource, ActionStatus> importCertifiedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, + Function<Resource, Boolean> validationFunction, + LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName, boolean isNested) { Resource resource = new Resource(); ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED); Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> response = Either.left(responsePair); @@ -130,54 +148,33 @@ public class ResourceImportManager { setConstantMetaData(resource, shouldBeCertified); setMetaDataFromJson(resourceMetaData, resource); - Either<Boolean, ResponseFormat> validateResourceFromYaml = populateResourceFromYaml(resourceYml, resource); - if (validateResourceFromYaml.isRight()) { - ResponseFormat validationErrorResponse = validateResourceFromYaml.right().value(); - auditErrorImport(resourceMetaData, creator, validationErrorResponse, true); - return Either.right(validationErrorResponse); + populateResourceFromYaml(resourceYml, resource); - } - - Either<Boolean, ResponseFormat> isValidResource = validationFunction.apply(resource); - if (isValidResource.isLeft()) { - // The flag createNewVersion if false doesn't create new version + Boolean isValidResource = validationFunction.apply(resource); if (!createNewVersion) { Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName()); if (latestByName.isLeft()) { - return Either.right(componentsUtils.getResponseFormatByResource(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, resource)); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, resource.getName()); } } resource = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock, csarInfo, nodeName, isNested).left; - Either<Resource, ResponseFormat> changeStateResponse; + Resource changeStateResponse; if (nodeTypeArtifactsToHandle != null && !nodeTypeArtifactsToHandle.isEmpty()) { Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = resourceBusinessLogic.handleNodeTypeArtifacts(resource, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, creator, isInTransaction, false); if (handleNodeTypeArtifactsRes.isRight()) { - return Either.right(handleNodeTypeArtifactsRes.right().value()); + //TODO: should be used more correct action + throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } } latestCertifiedResourceId = getLatestCertifiedResourceId(resource); changeStateResponse = resourceBusinessLogic.propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock, forceCertificationAllowed); - if (changeStateResponse.isRight()) { - response = Either.right(changeStateResponse.right().value()); - } - else { - responsePair = new ImmutablePair<>(changeStateResponse.left().value(), response.left() - .value().right); - response = Either.left(responsePair); - } - } - else { - ResponseFormat validationErrorResponse = isValidResource.right().value(); - auditErrorImport(resourceMetaData, creator, validationErrorResponse, true); - response = Either.right(validationErrorResponse); - } - + responsePair = new ImmutablePair<>(changeStateResponse, response.left() + .value().right); } catch (RuntimeException e) { - ResponseFormat exceptionResponse = handleImportResourceException(resourceMetaData, creator, true, e, null); - response = Either.right(exceptionResponse); + handleImportResourceException(resourceMetaData, creator, true, e); } finally { if (latestCertifiedResourceId != null && needLock) { @@ -186,7 +183,16 @@ public class ResourceImportManager { } } - return response; + return responsePair; + } + + private ResponseFormat getResponseFormatFromComponentException(RuntimeException e) { + if(e instanceof ComponentException){ + return ((ComponentException) e).getResponseFormat() == null ? + componentsUtils.getResponseFormat(((ComponentException) e).getActionStatus(), ((ComponentException) e).getParams()) : + ((ComponentException) e).getResponseFormat(); + } + return null; } private String getLatestCertifiedResourceId(Resource resource) { @@ -225,90 +231,65 @@ public class ResourceImportManager { } } - public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importUserDefinedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction) { + public ImmutablePair<Resource, ActionStatus> importUserDefinedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction) { Resource resource = new Resource(); ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED); - Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> response = Either.left(responsePair); try { setMetaDataFromJson(resourceMetaData, resource); - Either<Boolean, ResponseFormat> validateResourceFromYaml = populateResourceFromYaml(resourceYml, resource); - if (validateResourceFromYaml.isRight()) { - ResponseFormat validationErrorResponse = validateResourceFromYaml.right().value(); - auditErrorImport(resourceMetaData, creator, validationErrorResponse, false); - return Either.right(validationErrorResponse); - - } + populateResourceFromYaml(resourceYml, resource); // currently import VF isn't supported. In future will be supported // import VF only with CSAR file!! - if (ResourceTypeEnum.VF.equals(resource.getResourceType())) { + if (ResourceTypeEnum.VF == resource.getResourceType()) { log.debug("Now import VF isn't supported. It will be supported in future with CSAR file only"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION); } resourceBusinessLogic.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE); - Either<Boolean, ResponseFormat> validatePropertiesTypes = resourceBusinessLogic.validatePropertiesDefaultValues(resource); + Boolean validatePropertiesTypes = resourceBusinessLogic.validatePropertiesDefaultValues(resource); - if (validatePropertiesTypes.isLeft()) { - response = Either.left(resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, false, isInTransaction, true, null, null, false)); - } - else { - ResponseFormat validationErrorResponse = validatePropertiesTypes.right().value(); - auditErrorImport(resourceMetaData, creator, validationErrorResponse, false); - response = Either.right(validationErrorResponse); - } + responsePair = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, + false, isInTransaction, true, null, null, false); } - catch (ComponentException e) { - response = Either.right(handleImportResourceException(resourceMetaData, creator, false, e, - e.getResponseFormat())); - } catch (RuntimeException e) { - response = Either.right(handleImportResourceException(resourceMetaData, creator, false, e, null)); + handleImportResourceException(resourceMetaData, creator, false, e); } - return response; + return responsePair; } - Either<Boolean, ResponseFormat> populateResourceFromYaml(String resourceYml, Resource resource) { + void populateResourceFromYaml(String resourceYml, Resource resource) { @SuppressWarnings("unchecked") - Either<Boolean, ResponseFormat> eitherResult = Either.left(true); - Map<String, Object> toscaJsonAll = (Map<String, Object>) new Yaml().load(resourceYml); - Map<String, Object> toscaJson = toscaJsonAll; - - // Checks if exist and builds the node_types map - if (toscaJsonAll.containsKey(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName()) && resource.getResourceType() != ResourceTypeEnum.CVFC) { - toscaJson = new HashMap<>(); - toscaJson.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), toscaJsonAll.get(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName())); - } - // Derived From - Either<Resource, ResponseFormat> setDerivedFrom = setDerivedFrom(toscaJson, resource); - if (setDerivedFrom.isRight()) { - return Either.right(setDerivedFrom.right().value()); +// Either<Boolean, ResponseFormat> eitherResult = Either.left(true); + Object ymlObj = new Yaml().load(resourceYml); + if (ymlObj instanceof Map) { + Map<String, Object> toscaJsonAll = (Map<String, Object>) ymlObj; + Map<String, Object> toscaJson = toscaJsonAll; + + // Checks if exist and builds the node_types map + if (toscaJsonAll.containsKey(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName()) && resource.getResourceType() != ResourceTypeEnum.CVFC) { + toscaJson = new HashMap<>(); + toscaJson.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), toscaJsonAll.get(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName())); + } + // Derived From + Resource parentResource = setDerivedFrom(toscaJson, resource); + if (StringUtils.isEmpty(resource.getToscaResourceName())) { + setToscaResourceName(toscaJson, resource); + } + setAttributes(toscaJson, resource); + setCapabilities(toscaJson, resource, parentResource); + setProperties(toscaJson, resource); + setRequirements(toscaJson, resource, parentResource); + setInterfaceLifecycle(toscaJson, resource); } - Resource parentResource = setDerivedFrom.left().value(); - if (StringUtils.isEmpty(resource.getToscaResourceName())) { - setToscaResourceName(toscaJson, resource); - } - setAttributes(toscaJson, resource); - eitherResult = setCapabilities(toscaJson, resource, parentResource); - if (eitherResult.isRight()) { - return eitherResult; - } - eitherResult = setProperties(toscaJson, resource); - if (eitherResult.isRight()) { - return eitherResult; - } - eitherResult = setRequirements(toscaJson, resource, parentResource); - if (eitherResult.isRight()) { - return eitherResult; + else { + throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } - setInterfaceLifecycle(toscaJson, resource); - return eitherResult; } private void setToscaResourceName(Map<String, Object> toscaJson, Resource resource) { @@ -374,8 +355,7 @@ public class ResourceImportManager { return result; } - private Either<Boolean, ResponseFormat> setRequirements(Map<String, Object> toscaJson, Resource resource, Resource parentResource) {// Note that parentResource can be null - Either<Boolean, ResponseFormat> eitherResult = Either.left(true); + private void setRequirements(Map<String, Object> toscaJson, Resource resource, Resource parentResource) {// Note that parentResource can be null Either<List<Object>, ResultStatusEnum> toscaRequirements = ImportUtils.findFirstToscaListElement(toscaJson, TypeUtils.ToscaTagNamesEnum.REQUIREMENTS); if (toscaRequirements.isLeft()) { List<Object> jsonRequirements = toscaRequirements.left().value(); @@ -384,13 +364,7 @@ public class ResourceImportManager { Set<String> reqNames = new HashSet<>(); // Getting flattened list of capabilities of parent node - cap name // to cap type - Either<Map<String, String>, ResponseFormat> reqName2Type = getReqName2Type(parentResource); - if (reqName2Type.isRight()) { - ResponseFormat responseFormat = reqName2Type.right().value(); - log.debug("Error during setting requirements of imported resource: {}", responseFormat); - return Either.right(responseFormat); - } - Map<String, String> reqName2TypeMap = reqName2Type.left().value(); + Map<String, String> reqName2TypeMap = getReqName2Type(parentResource); for (Object jsonRequirementObj : jsonRequirements) { // Requirement Map<String, Object> requirementJsonWrapper = (Map<String, Object>) jsonRequirementObj; @@ -398,16 +372,11 @@ public class ResourceImportManager { String reqNameLowerCase = requirementName.toLowerCase(); if (reqNames.contains(reqNameLowerCase)) { log.debug("More than one requirement with same name {} (case-insensitive) in imported TOSCA file is invalid", reqNameLowerCase); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "requirement", reqNameLowerCase)); + throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "requirement", reqNameLowerCase); } reqNames.add(reqNameLowerCase); - Either<RequirementDefinition, ResponseFormat> eitherRequirement = createRequirementFromImportFile(requirementJsonWrapper + RequirementDefinition requirementDef = createRequirementFromImportFile(requirementJsonWrapper .get(requirementName)); - if (eitherRequirement.isRight()) { - log.info("error when creating Requirement:{}, for resource:{}", requirementName, resource.getName()); - return Either.right(eitherRequirement.right().value()); - } - RequirementDefinition requirementDef = eitherRequirement.left().value(); requirementDef.setName(requirementName); if (moduleRequirements.containsKey(requirementDef.getCapability())) { moduleRequirements.get(requirementDef.getCapability()).add(requirementDef); @@ -419,18 +388,14 @@ public class ResourceImportManager { } // Validating against req/cap of "derived from" node - Either<Boolean, ResponseFormat> validateVsParentCap = validateCapNameVsDerived(reqName2TypeMap, requirementDef + Boolean validateVsParentCap = validateCapNameVsDerived(reqName2TypeMap, requirementDef .getCapability(), requirementDef.getName()); - if (validateVsParentCap.isRight()) { - return Either.right(validateVsParentCap.right().value()); - } - if (!validateVsParentCap.left().value()) { + if (!validateVsParentCap) { log.debug("Requirement with name {} already exists in parent {}", requirementDef.getName(), parentResource .getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "requirement", requirementDef + throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "requirement", requirementDef .getName() .toLowerCase(), parentResource.getName()); - return Either.right(responseFormat); } } if (moduleRequirements.size() > 0) { @@ -438,64 +403,44 @@ public class ResourceImportManager { } } - return eitherResult; - - } + } - private Either<RequirementDefinition, ResponseFormat> createRequirementFromImportFile(Object requirementJson) { + private RequirementDefinition createRequirementFromImportFile(Object requirementJson) { RequirementDefinition requirement = new RequirementDefinition(); - Either<RequirementDefinition, ResponseFormat> result = Either.left(requirement); - try { - if (requirementJson instanceof String) { - String requirementJsonString = (String) requirementJson; - requirement.setCapability(requirementJsonString); - } - else if (requirementJson instanceof Map) { - Map<String, Object> requirementJsonMap = (Map<String, Object>) requirementJson; - if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.CAPABILITY.getElementName())) { - requirement.setCapability((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.CAPABILITY.getElementName())); - } - - if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.NODE.getElementName())) { - requirement.setNode((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.NODE.getElementName())); - } + if (requirementJson instanceof String) { + String requirementJsonString = (String) requirementJson; + requirement.setCapability(requirementJsonString); + } + else if (requirementJson instanceof Map) { + Map<String, Object> requirementJsonMap = (Map<String, Object>) requirementJson; + if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.CAPABILITY.getElementName())) { + requirement.setCapability((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.CAPABILITY.getElementName())); + } - if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.RELATIONSHIP.getElementName())) { - requirement.setRelationship((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.RELATIONSHIP.getElementName())); - } - if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName())) { - List<Object> occurrencesList = (List) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName()); - Either<Boolean, ResponseFormat> validateAndSetOccurrencesStatus = validateOccurrences(occurrencesList); - if (validateAndSetOccurrencesStatus.isRight()) { - result = Either.right(validateAndSetOccurrencesStatus.right().value()); - return result; - } - if (validateAndSetOccurrencesStatus.left().value()) { - requirement.setMinOccurrences(occurrencesList.get(0).toString()); - requirement.setMaxOccurrences(occurrencesList.get(1).toString()); - } + if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.NODE.getElementName())) { + requirement.setNode((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.NODE.getElementName())); + } - } + if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.RELATIONSHIP.getElementName())) { + requirement.setRelationship((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.RELATIONSHIP.getElementName())); } - else { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); + if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName())) { + List<Object> occurrencesList = (List) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName()); + validateOccurrences(occurrencesList); + requirement.setMinOccurrences(occurrencesList.get(0).toString()); + requirement.setMaxOccurrences(occurrencesList.get(1).toString()); } - } - catch (Exception e) { - BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create Requirement"); - log.debug("error when creating requirement, message:{}", e.getMessage(), e); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); + else { + throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML); } - - return result; + return requirement; } - private Either<Boolean, ResponseFormat> setProperties(Map<String, Object> toscaJson, Resource resource) { + private void setProperties(Map<String, Object> toscaJson, Resource resource) { Map<String, Object> reducedToscaJson = new HashMap<>(toscaJson); ImportUtils.removeElementFromJsonMap(reducedToscaJson, "capabilities"); - Either<Boolean, ResponseFormat> result = Either.left(true); Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(reducedToscaJson); if (properties.isLeft()) { List<PropertyDefinition> propertiesList = new ArrayList<>(); @@ -505,7 +450,7 @@ public class ResourceImportManager { String name = entry.getKey(); if (!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(name).matches()) { log.debug("The property with invalid name {} occured upon import resource {}. ", name, resource.getName()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, JsonPresentationFields.PROPERTY))); + throw new ByActionStatusComponentException(componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, JsonPresentationFields.PROPERTY)); } PropertyDefinition propertyDefinition = entry.getValue(); propertyDefinition.setName(name); @@ -515,11 +460,10 @@ public class ResourceImportManager { resource.setProperties(propertiesList); } else if (properties.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromResultStatusEnum(properties + throw new ByActionStatusComponentException(componentsUtils.convertFromResultStatusEnum(properties .right() - .value(), JsonPresentationFields.PROPERTY))); + .value(), JsonPresentationFields.PROPERTY)); } - return result; } private ResultStatusEnum setAttributes(Map<String, Object> toscaJson, Resource resource) { @@ -544,7 +488,7 @@ public class ResourceImportManager { return result; } - private Either<Resource, ResponseFormat> setDerivedFrom(Map<String, Object> toscaJson, Resource resource) { + private Resource setDerivedFrom(Map<String, Object> toscaJson, Resource resource) { Either<String, ResultStatusEnum> toscaDerivedFromElement = ImportUtils.findFirstToscaStringElement(toscaJson, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM); Resource derivedFromResource = null; if (toscaDerivedFromElement.isLeft()) { @@ -555,22 +499,21 @@ public class ResourceImportManager { if (latestByToscaResourceName.isRight()) { StorageOperationStatus operationStatus = latestByToscaResourceName.right().value(); - if (operationStatus.equals(StorageOperationStatus.NOT_FOUND)) { + if (operationStatus == StorageOperationStatus.NOT_FOUND) { operationStatus = StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND; } log.debug("Error when fetching parent resource {}, error: {}", derivedFrom, operationStatus); ActionStatus convertFromStorageResponse = componentsUtils.convertFromStorageResponse(operationStatus); BeEcompErrorManager.getInstance() .logBeComponentMissingError("Import TOSCA YAML", "resource", derivedFrom); - return Either.right(componentsUtils.getResponseFormat(convertFromStorageResponse, derivedFrom)); + throw new ByActionStatusComponentException(convertFromStorageResponse, derivedFrom); } derivedFromResource = latestByToscaResourceName.left().value(); } - return Either.left(derivedFromResource); + return derivedFromResource; } - private Either<Boolean, ResponseFormat> setCapabilities(Map<String, Object> toscaJson, Resource resource, Resource parentResource) {// Note that parentResource can be null - Either<Boolean, ResponseFormat> eitherResult = Either.left(true); + private void setCapabilities(Map<String, Object> toscaJson, Resource resource, Resource parentResource) {// Note that parentResource can be null Either<Map<String, Object>, ResultStatusEnum> toscaCapabilities = ImportUtils.findFirstToscaMapElement(toscaJson, TypeUtils.ToscaTagNamesEnum.CAPABILITIES); if (toscaCapabilities.isLeft()) { Map<String, Object> jsonCapabilities = toscaCapabilities.left().value(); @@ -579,13 +522,7 @@ public class ResourceImportManager { Set<String> capNames = new HashSet<>(); // Getting flattened list of capabilities of parent node - cap name // to cap type - Either<Map<String, String>, ResponseFormat> capName2Type = getCapName2Type(parentResource); - if (capName2Type.isRight()) { - ResponseFormat responseFormat = capName2Type.right().value(); - log.debug("Error during setting capabilities of imported resource: {}", responseFormat); - return Either.right(responseFormat); - } - Map<String, String> capName2TypeMap = capName2Type.left().value(); + Map<String, String> capName2TypeMap = getCapName2Type(parentResource); while (capabilitiesNameValue.hasNext()) { Entry<String, Object> capabilityNameValue = capabilitiesNameValue.next(); @@ -593,19 +530,12 @@ public class ResourceImportManager { String capNameLowerCase = capabilityNameValue.getKey().toLowerCase(); if (capNames.contains(capNameLowerCase)) { log.debug("More than one capability with same name {} (case-insensitive) in imported TOSCA file is invalid", capNameLowerCase); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "capability", capNameLowerCase)); + throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "capability", capNameLowerCase); } capNames.add(capNameLowerCase); - Either<CapabilityDefinition, ResponseFormat> eitherCapability = createCapabilityFromImportFile(capabilityNameValue + CapabilityDefinition capabilityDef = createCapabilityFromImportFile(capabilityNameValue .getValue()); - if (eitherCapability.isRight()) { - log.debug("error when creating capability:{}, for resource:{}", capabilityNameValue.getKey(), resource - .getName()); - return Either.right(eitherCapability.right().value()); - } - - CapabilityDefinition capabilityDef = eitherCapability.left().value(); capabilityDef.setName(capabilityNameValue.getKey()); if (moduleCapabilities.containsKey(capabilityDef.getType())) { moduleCapabilities.get(capabilityDef.getType()).add(capabilityDef); @@ -617,32 +547,26 @@ public class ResourceImportManager { } // Validating against req/cap of "derived from" node - Either<Boolean, ResponseFormat> validateVsParentCap = validateCapNameVsDerived(capName2TypeMap, capabilityDef + Boolean validateVsParentCap = validateCapNameVsDerived(capName2TypeMap, capabilityDef .getType(), capabilityDef.getName()); - if (validateVsParentCap.isRight()) { - return Either.right(validateVsParentCap.right().value()); - } - if (!validateVsParentCap.left().value()) { + + if (!validateVsParentCap) { // Here parentResource is for sure not null, so it's // null-safe log.debug("Capability with name {} already exists in parent {}", capabilityDef.getName(), parentResource .getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "capability", capabilityDef + throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "capability", capabilityDef .getName() .toLowerCase(), parentResource.getName()); - return Either.right(responseFormat); } } if (moduleCapabilities.size() > 0) { resource.setCapabilities(moduleCapabilities); } } - - return eitherResult; - } - private Either<Map<String, String>, ResponseFormat> getCapName2Type(Resource parentResource) { + private Map<String, String> getCapName2Type(Resource parentResource) { Map<String, String> capName2type = new HashMap<>(); if (parentResource != null) { Map<String, List<CapabilityDefinition>> capabilities = parentResource.getCapabilities(); @@ -655,17 +579,17 @@ public class ResourceImportManager { log.debug("Resource with name {} has more than one capability with name {}, ignoring case", parentResourceName, nameLowerCase); BeEcompErrorManager.getInstance() .logInternalDataError("Import resource", "Parent resource " + parentResourceName + " of imported resource has one or more capabilities with name " + nameLowerCase, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } capName2type.put(nameLowerCase, capDefinition.getType()); } } } } - return Either.left(capName2type); + return capName2type; } - private Either<Map<String, String>, ResponseFormat> getReqName2Type(Resource parentResource) { + private Map<String, String> getReqName2Type(Resource parentResource) { Map<String, String> reqName2type = new HashMap<>(); if (parentResource != null) { Map<String, List<RequirementDefinition>> requirements = parentResource.getRequirements(); @@ -678,123 +602,115 @@ public class ResourceImportManager { log.debug("Resource with name {} has more than one requirement with name {}, ignoring case", parentResourceName, nameLowerCase); BeEcompErrorManager.getInstance() .logInternalDataError("Import resource", "Parent resource " + parentResourceName + " of imported resource has one or more requirements with name " + nameLowerCase, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } reqName2type.put(nameLowerCase, reqDefinition.getCapability()); } } } } - return Either.left(reqName2type); + return reqName2type; } - private Either<Boolean, ResponseFormat> validateCapNameVsDerived(Map<String, String> parentCapName2Type, String childCapabilityType, String reqCapName) { + private Boolean validateCapNameVsDerived(Map<String, String> parentCapName2Type, String childCapabilityType, String reqCapName) { String capNameLowerCase = reqCapName.toLowerCase(); log.trace("Validating capability {} vs parent resource", capNameLowerCase); String parentCapType = parentCapName2Type.get(capNameLowerCase); if (parentCapType != null) { if (childCapabilityType.equals(parentCapType)) { log.debug("Capability with name {} is of same type {} for imported resource and its parent - this is OK", capNameLowerCase, childCapabilityType); - return Either.left(true); + return true; } Either<Boolean, StorageOperationStatus> capabilityTypeDerivedFrom = capabilityTypeOperation.isCapabilityTypeDerivedFrom(childCapabilityType, parentCapType); if (capabilityTypeDerivedFrom.isRight()) { log.debug("Couldn't check whether imported resource capability derives from its parent's capability"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(capabilityTypeDerivedFrom + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(capabilityTypeDerivedFrom .right() .value())); - return Either.right(responseFormat); } - return Either.left(capabilityTypeDerivedFrom.left().value()); + return capabilityTypeDerivedFrom.left().value(); } - return Either.left(true); + return true; } - private Either<CapabilityDefinition, ResponseFormat> createCapabilityFromImportFile(Object capabilityJson) { + private CapabilityDefinition createCapabilityFromImportFile(Object capabilityJson) { CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); - Either<CapabilityDefinition, ResponseFormat> result = Either.left(capabilityDefinition); - - try { - if (capabilityJson instanceof String) { - String capabilityJsonString = (String) capabilityJson; - capabilityDefinition.setType(capabilityJsonString); - } - else if (capabilityJson instanceof Map) { - Map<String, Object> capabilityJsonMap = (Map<String, Object>) capabilityJson; - // Type - if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())) { - capabilityDefinition.setType((String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())); - } - // ValidSourceTypes - if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) { - capabilityDefinition.setValidSourceTypes((List<String>) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES - .getElementName())); - } - // ValidSourceTypes - if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName())) { - capabilityDefinition.setDescription((String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName())); - } - if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName())) { - List<Object> occurrencesList = (List) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName()); - Either<Boolean, ResponseFormat> validateAndSetOccurrencesStatus = validateOccurrences(occurrencesList); - if (validateAndSetOccurrencesStatus.isRight()) { - result = Either.right(validateAndSetOccurrencesStatus.right().value()); - return result; - } - if (validateAndSetOccurrencesStatus.left().value()) { - capabilityDefinition.setMinOccurrences(occurrencesList.get(0).toString()); - capabilityDefinition.setMaxOccurrences(occurrencesList.get(1).toString()); - } - } - if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.PROPERTIES.getElementName())) { - Either<Map<String, PropertyDefinition>, ResultStatusEnum> propertiesRes = ImportUtils.getProperties(capabilityJsonMap); - if (propertiesRes.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND)); - return result; - } - else { - propertiesRes.left() - .value() - .entrySet() - .stream() - .forEach(e -> e.getValue().setName(e.getKey().toLowerCase())); - List<ComponentInstanceProperty> capabilityProperties = propertiesRes.left() - .value() - .values() - .stream() - .map(p -> new ComponentInstanceProperty(p, p - .getDefaultValue(), null)) - .collect(Collectors.toList()); - capabilityDefinition.setProperties(capabilityProperties); - } - } + if (capabilityJson instanceof String) { + String capabilityJsonString = (String) capabilityJson; + capabilityDefinition.setType(capabilityJsonString); + } + else if (capabilityJson instanceof Map) { + Map<String, Object> capabilityJsonMap = (Map<String, Object>) capabilityJson; + // Type + if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())) { + capabilityDefinition.setType((String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())); } - else if (!(capabilityJson instanceof List)) { - - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); + // ValidSourceTypes + if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) { + capabilityDefinition.setValidSourceTypes((List<String>) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES + .getElementName())); + } + // ValidSourceTypes + if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName())) { + capabilityDefinition.setDescription((String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName())); + } + if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName())) { + List<Object> occurrencesList = (List) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName()); + validateOccurrences(occurrencesList); + capabilityDefinition.setMinOccurrences(occurrencesList.get(0).toString()); + capabilityDefinition.setMaxOccurrences(occurrencesList.get(1).toString()); + } + if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.PROPERTIES.getElementName())) { + Either<Map<String, PropertyDefinition>, ResultStatusEnum> propertiesRes = ImportUtils.getProperties(capabilityJsonMap); + if (propertiesRes.isRight()) { + throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND); + } + else { + propertiesRes.left() + .value() + .entrySet() + .stream() + .forEach(e -> e.getValue().setName(e.getKey().toLowerCase())); + List<ComponentInstanceProperty> capabilityProperties = propertiesRes.left() + .value() + .values() + .stream() + .map(p -> new ComponentInstanceProperty(p, p + .getDefaultValue(), null)) + .collect(Collectors.toList()); + capabilityDefinition.setProperties(capabilityProperties); + } } } - catch (Exception e) { - BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability"); - log.debug("error when creating capability, message:{}", e.getMessage(), e); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); + else if (!(capabilityJson instanceof List)) { + throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML); } - - return result; + return capabilityDefinition; } - private ResponseFormat handleImportResourceException(UploadResourceInfo resourceMetaData, User user, boolean isNormative, RuntimeException e, ResponseFormat responseFormat) { - if(responseFormat == null ){ + private void handleImportResourceException(UploadResourceInfo resourceMetaData, User user, boolean isNormative, RuntimeException e) { + ResponseFormat responseFormat; + ComponentException newException; + if (e instanceof ComponentException) { + ComponentException componentException = (ComponentException)e; + responseFormat = componentException.getResponseFormat(); + if (responseFormat == null) { + responseFormat = getResponseFormatManager().getResponseFormat(componentException.getActionStatus(), componentException.getParams()); + } + newException = componentException; + } + else{ responseFormat = getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR); + newException = new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } String payloadName = (resourceMetaData != null) ? resourceMetaData.getPayloadName() : ""; BeEcompErrorManager.getInstance().logBeSystemError("Import Resource " + payloadName); log.debug("Error when importing resource from payload:{} Exception text: {}", payloadName, e.getMessage(), e); auditErrorImport(resourceMetaData, user, responseFormat, isNormative); - return responseFormat; + throw newException; } private void auditErrorImport(UploadResourceInfo resourceMetaData, User user, ResponseFormat errorResponseWrapper, boolean isNormative) { @@ -876,45 +792,37 @@ public class ResourceImportManager { } - private Either<Boolean, ResponseFormat> validateOccurrences(List<Object> occurrensesList) { + private void validateOccurrences(List<Object> occurrensesList) { if (!ValidationUtils.validateListNotEmpty(occurrensesList)) { log.debug("Occurrenses list empty"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); - return Either.right(responseFormat); + throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES); } if (occurrensesList.size() < 2) { log.debug("Occurrenses list size not 2"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); - return Either.right(responseFormat); + throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES); } Object minObj = occurrensesList.get(0); Object maxObj = occurrensesList.get(1); Integer minOccurrences; - Integer maxOccurrences = null; + Integer maxOccurrences; if (minObj instanceof Integer) { minOccurrences = (Integer) minObj; } else { log.debug("Invalid occurrenses format. low_bound occurrense must be Integer {}", minObj); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); - return Either.right(responseFormat); + throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES); } if (minOccurrences < 0) { log.debug("Invalid occurrenses format.low_bound occurrense negative {}", minOccurrences); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); - return Either.right(responseFormat); + throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES); } - if (maxObj instanceof String) { - if ("UNBOUNDED".equals(maxObj)) { - return Either.left(true); - } - else { + if (maxObj instanceof String){ + if(!"UNBOUNDED".equals(maxObj)) { log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); - return Either.right(responseFormat); + throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES); } } else { @@ -923,19 +831,14 @@ public class ResourceImportManager { } else { log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); - return Either.right(responseFormat); + throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES); } if (maxOccurrences <= 0 || maxOccurrences < minOccurrences) { log.debug("Invalid occurrenses format. min occurrence is {}, Max occurrence is {}", minOccurrences, maxOccurrences); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); - return Either.right(responseFormat); + throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES); } } - - return Either.left(true); - } public synchronized void init(ServletContext servletContext) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java index 19d63f30b4..27adf93516 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java @@ -64,11 +64,11 @@ public class ResponseFormatManager { String errorMessage = errorInfo.getMessage(); String errorMessageId = errorInfo.getMessageId(); ErrorInfoType errorInfoType = errorInfo.getErrorInfoType(); - if (errorInfoType.equals(ErrorInfoType.SERVICE_EXCEPTION)) { + if (errorInfoType == ErrorInfoType.SERVICE_EXCEPTION) { errorResponseWrapper.setServiceException(new ServiceException(errorMessageId, errorMessage, variables)); - } else if (errorInfoType.equals(ErrorInfoType.POLICY_EXCEPTION)) { + } else if (errorInfoType == ErrorInfoType.POLICY_EXCEPTION) { errorResponseWrapper.setPolicyException(new PolicyException(errorMessageId, errorMessage, variables)); - } else if (errorInfoType.equals(ErrorInfoType.OK)) { + } else if (errorInfoType == ErrorInfoType.OK) { errorResponseWrapper.setOkResponseInfo(new OkResponseInfo(errorMessageId, errorMessage, variables)); } return errorResponseWrapper; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java index 28fc2597b8..c1f7808958 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java @@ -22,43 +22,17 @@ package org.openecomp.sdc.be.components.impl; -import static org.apache.commons.collections.CollectionUtils.isEmpty; -import static org.apache.commons.collections.CollectionUtils.isNotEmpty; -import static org.openecomp.sdc.be.components.utils.ConsumptionUtils.handleConsumptionInputMappedToCapabilityProperty; -import static org.openecomp.sdc.be.components.utils.ConsumptionUtils.isAssignedValueFromValidType; -import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getOperationOutputName; -import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.isOperationInputMappedToOtherOperationOutput; -import static org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum.UPDATE_SERVICE_METADATA; -import static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.SELF; -import static org.openecomp.sdc.be.types.ServiceConsumptionSource.SERVICE_INPUT; -import static org.openecomp.sdc.be.types.ServiceConsumptionSource.STATIC; - import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.gson.Gson; import com.google.gson.GsonBuilder; - -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.Callable; -import java.util.function.Function; -import java.util.stream.Collectors; - import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.collections4.ListUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum; import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine; import org.openecomp.sdc.be.components.distribution.engine.INotificationData; import org.openecomp.sdc.be.components.distribution.engine.VfModuleArtifactPayload; @@ -73,6 +47,19 @@ import org.openecomp.sdc.be.components.utils.InterfaceOperationUtils; import org.openecomp.sdc.be.components.utils.PropertiesUtils; import org.openecomp.sdc.be.components.validation.NodeFilterValidator; import org.openecomp.sdc.be.components.validation.ServiceDistributionValidation; +import org.openecomp.sdc.be.components.validation.component.ComponentContactIdValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentDescriptionValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentIconValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentNameValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentProjectCodeValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentTagsValidator; +import org.openecomp.sdc.be.components.validation.component.ComponentValidator; +import org.openecomp.sdc.be.components.validation.service.ServiceCategoryValidator; +import org.openecomp.sdc.be.components.validation.service.ServiceFunctionValidator; +import org.openecomp.sdc.be.components.validation.service.ServiceInstantiationTypeValidator; +import org.openecomp.sdc.be.components.validation.service.ServiceRoleValidator; +import org.openecomp.sdc.be.components.validation.service.ServiceTypeValidator; +import org.openecomp.sdc.be.components.validation.service.ServiceValidator; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -90,7 +77,6 @@ import org.openecomp.sdc.be.datatypes.elements.OperationOutputDefinition; import org.openecomp.sdc.be.datatypes.elements.RequirementNodeFilterPropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.InstantiationTypes; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; @@ -148,6 +134,7 @@ import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.kpi.api.ASDCKpiApi; +import org.openecomp.sdc.common.log.elements.LoggerSupportability; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.GeneralUtility; import org.openecomp.sdc.common.util.ThreadLocalsHolder; @@ -159,6 +146,31 @@ import org.springframework.web.context.WebApplicationContext; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static org.apache.commons.collections.CollectionUtils.isNotEmpty; +import static org.openecomp.sdc.be.components.utils.ConsumptionUtils.handleConsumptionInputMappedToCapabilityProperty; +import static org.openecomp.sdc.be.components.utils.ConsumptionUtils.isAssignedValueFromValidType; +import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getOperationOutputName; +import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.isOperationInputMappedToOtherOperationOutput; +import static org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum.UPDATE_SERVICE_METADATA; +import static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.SELF; +import static org.openecomp.sdc.be.types.ServiceConsumptionSource.SERVICE_INPUT; +import static org.openecomp.sdc.be.types.ServiceConsumptionSource.STATIC; + @org.springframework.stereotype.Component("serviceBusinessLogic") public class ServiceBusinessLogic extends ComponentBusinessLogic { @@ -171,6 +183,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { private static final String INITIAL_VERSION = "0.1"; private static final String STATUS_SUCCESS_200 = "200"; private static final String STATUS_DEPLOYED = "DEPLOYED"; + private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ServiceBusinessLogic.class.getName()); static final String IS_VALID = "isValid"; private ForwardingPathOperation forwardingPathOperation; @@ -184,6 +197,34 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { private final NodeFilterOperation serviceFilterOperation; private final NodeFilterValidator serviceFilterValidator; + private ServiceTypeValidator serviceTypeValidator; + + @Autowired + public void setServiceTypeValidator(ServiceTypeValidator serviceTypeValidator) { + this.serviceTypeValidator = serviceTypeValidator; + } + + + private ServiceFunctionValidator serviceFunctionValidator; + + @Autowired + public void setServiceFunctionValidator(ServiceFunctionValidator serviceFunctionValidator) { + this.serviceFunctionValidator = serviceFunctionValidator; + } + + @Autowired + private ServiceRoleValidator serviceRoleValidator; + + @Autowired + private ServiceInstantiationTypeValidator serviceInstantiationTypeValidator; + + @Autowired + private ServiceCategoryValidator serviceCategoryValidator; + + @Autowired + private ServiceValidator serviceValidator; + + @Autowired public ServiceBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, @@ -196,9 +237,18 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { IDistributionEngine distributionEngine, ComponentInstanceBusinessLogic componentInstanceBusinessLogic, ServiceDistributionValidation serviceDistributionValidation, ForwardingPathValidator forwardingPathValidator, UiComponentDataConverter uiComponentDataConverter, NodeFilterOperation serviceFilterOperation, - NodeFilterValidator serviceFilterValidator, ArtifactsOperations artifactToscaOperation) { + NodeFilterValidator serviceFilterValidator, ArtifactsOperations artifactToscaOperation, + ComponentContactIdValidator componentContactIdValidator, + ComponentNameValidator componentNameValidator, + ComponentTagsValidator componentTagsValidator, + ComponentValidator componentValidator, + ComponentIconValidator componentIconValidator, + ComponentProjectCodeValidator componentProjectCodeValidator, + ComponentDescriptionValidator componentDescriptionValidator) { super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic, - interfaceOperation, interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation); + interfaceOperation, interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, componentContactIdValidator, + componentNameValidator, componentTagsValidator, componentValidator, + componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator); this.distributionEngine = distributionEngine; this.componentInstanceBusinessLogic = componentInstanceBusinessLogic; this.serviceDistributionValidation = serviceDistributionValidation; @@ -206,76 +256,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { this.uiComponentDataConverter = uiComponentDataConverter; this.serviceFilterOperation = serviceFilterOperation; this.serviceFilterValidator = serviceFilterValidator; - } - - public Either<Service, ResponseFormat> changeServiceDistributionState(String serviceId, String state, LifecycleChangeInfoWithAction commentObj, User user) { - - validateUserExists(user.getUserId(), "change Service Distribution State", false); - - log.debug("check request state"); - Either<DistributionTransitionEnum, ResponseFormat> validateEnum = validateTransitionEnum(state); - if (validateEnum.isRight()) { - return Either.right(validateEnum.right().value()); - } - DistributionTransitionEnum distributionTransition = validateEnum.left().value(); - AuditingActionEnum auditAction = distributionTransition == DistributionTransitionEnum.APPROVE ? AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV : AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REJECT; - Either<String, ResponseFormat> commentResponse = validateComment(commentObj); - if (commentResponse.isRight()) { - return Either.right(commentResponse.right().value()); - } - String comment = commentResponse.left().value(); - - Either<Service, ResponseFormat> validateService = validateServiceDistributionChange(user, serviceId, auditAction, comment); - if (validateService.isRight()) { - return Either.right(validateService.right().value()); - } - Service service = validateService.left().value(); - Either<User, ResponseFormat> validateUser = validateUserDistributionChange(user, service, auditAction, comment); - if (validateUser.isRight()) { - return Either.right(validateUser.right().value()); - } - user = validateUser.left().value(); - - // lock resource - - Either<Boolean, ResponseFormat> lockResult = lockComponent(serviceId, service, "ChangeServiceDistributionState"); - if (lockResult.isRight()) { - ResponseFormat responseFormat = lockResult.right().value(); - createAudit(user, auditAction, comment, service, responseFormat); - return Either.right(responseFormat); - } - - try { - - DistributionStatusEnum newState; - if (distributionTransition == DistributionTransitionEnum.APPROVE) { - newState = DistributionStatusEnum.DISTRIBUTION_APPROVED; - } else { - newState = DistributionStatusEnum.DISTRIBUTION_REJECTED; - } - Either<Service, StorageOperationStatus> result = toscaOperationFacade.updateDistributionStatus(service, user, newState); - if (result.isRight()) { - janusGraphDao.rollback(); - BeEcompErrorManager.getInstance().logBeSystemError("ChangeServiceDistributionState"); - log.debug("service {} is change destribuation status failed", service.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, service.getVersion(), service.getName()); - createAudit(user, auditAction, comment, service, responseFormat); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - janusGraphDao.commit(); - Service updatedService = result.left().value(); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - log.debug(AUDIT_BEFORE_SENDING_RESPONSE); - componentsUtils.auditComponent(responseFormat, user, updatedService, auditAction, new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()), ResourceVersionInfo.newBuilder().build(), comment); - return Either.left(result.left().value()); - } finally { - graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); - } } + public Either<List<Map<String, Object>>, ResponseFormat> getComponentAuditRecords(String componentVersion, String componentUUID, String userId) { - validateUserExists(userId, "get Component Audit Records", false); + validateUserExists(userId); Either<List<Map<String, Object>>, ActionStatus> result; try { @@ -358,7 +344,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { String operationId, String userId, ServiceConsumptionData serviceConsumptionData) { - validateUserExists(userId, "create Property", false); + validateUserExists(userId); Either<Service, StorageOperationStatus> serviceEither = toscaOperationFacade.getToscaElement(serviceId); @@ -703,33 +689,19 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { private Either<Boolean, ResponseFormat> validateOperationInputConstraint( OperationInputDefinition operationInputDefinition, String value, String type) { - - if (Objects.nonNull(operationInputDefinition.getParentPropertyType()) - && !operationInputDefinition.getParentPropertyType().equals(operationInputDefinition.getType())) { - InputDefinition inputDefinition = new InputDefinition(); - inputDefinition.setDefaultValue(value); - inputDefinition.setInputPath(operationInputDefinition.getSubPropertyInputPath()); - inputDefinition.setName(operationInputDefinition.getName()); - inputDefinition.setType(type); - - ComponentInstanceProperty propertyDefinition = new ComponentInstanceProperty(); - propertyDefinition.setType(operationInputDefinition.getParentPropertyType()); - if (operationInputDefinition.getParentPropertyType() != null) { + ComponentInstanceProperty propertyDefinition = new ComponentInstanceProperty(); + propertyDefinition.setType(operationInputDefinition.getParentPropertyType()); + + InputDefinition inputDefinition = new InputDefinition(); + inputDefinition.setDefaultValue(value); + inputDefinition.setInputPath(operationInputDefinition.getSubPropertyInputPath()); + inputDefinition.setType(type); + if (Objects.nonNull(operationInputDefinition.getParentPropertyType())) { inputDefinition.setProperties(Collections.singletonList(propertyDefinition)); - } - - return PropertyValueConstraintValidationUtil.getInstance() - .validatePropertyConstraints(Collections.singletonList(inputDefinition), applicationDataTypeCache); - } else { - PropertyDefinition propertyDefinition = new PropertyDefinition(); - propertyDefinition.setType(operationInputDefinition.getType()); - propertyDefinition.setSchema(operationInputDefinition.getSchema()); - propertyDefinition.setValue(value); - propertyDefinition.setName(operationInputDefinition.getName()); - - return PropertyValueConstraintValidationUtil.getInstance() - .validatePropertyConstraints(Collections.singletonList(propertyDefinition), applicationDataTypeCache); } + + return PropertyValueConstraintValidationUtil.getInstance() + .validatePropertyConstraints(Collections.singletonList(inputDefinition), applicationDataTypeCache); } private void addStaticValueToInputOperation(String value, Operation operation, @@ -833,6 +805,16 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.left(archiveAudit); } + @VisibleForTesting + public void setServiceValidator(ServiceValidator serviceValidator) { + this.serviceValidator = serviceValidator; + } + + @VisibleForTesting + public void setServiceCategoryValidator(ServiceCategoryValidator serviceCategoryValidator) { + this.serviceCategoryValidator = serviceCategoryValidator; + } + private List<Map<String, Object>> getAuditingFieldsList(List<? extends AuditingGenericEvent> prevVerAuditList) { List<Map<String, Object>> prevVerAudit = new ArrayList<>(); @@ -856,6 +838,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { // get user details user = validateUser(user, "Create Service", service, AuditingActionEnum.CREATE_RESOURCE, false); + log.debug("User returned from validation: "+ user.toString()); // validate user role validateUserRole(user, service, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null); service.setCreatorUserId(user.getUserId()); @@ -867,12 +850,16 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { service.setVersion(INITIAL_VERSION); service.setConformanceLevel(ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel()); service.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - + service.setComponentType(ComponentTypeEnum.SERVICE); Either<Service, ResponseFormat> createServiceResponse = validateServiceBeforeCreate(service, user, AuditingActionEnum.CREATE_RESOURCE); if (createServiceResponse.isRight()) { return createServiceResponse; } - return createServiceByDao(service, AuditingActionEnum.CREATE_RESOURCE, user); + return createServiceByDao(service, AuditingActionEnum.CREATE_RESOURCE, user) + .left() + .bind(c -> updateCatalog(c, ChangeTypeEnum.LIFECYCLE) + .left() + .map (r -> (Service) r)); } private void checkFieldsForOverideAttampt(Service service) { @@ -961,12 +948,18 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } } - private Either<Service, ResponseFormat> validateServiceBeforeCreate(Service service, User user, AuditingActionEnum actionEnum) { + @VisibleForTesting + protected Either<Service, ResponseFormat> validateServiceBeforeCreate(Service service, User user, AuditingActionEnum actionEnum) { - Either<Boolean, ResponseFormat> validationResponse = validateServiceFieldsBeforeCreate(user, service, actionEnum); - if (validationResponse.isRight()) { - return Either.right(validationResponse.right().value()); + try { + serviceValidator.validate(user,service,actionEnum); + } catch (ComponentException exp) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(exp); + componentsUtils.auditComponentAdmin(responseFormat, user, service, + AuditingActionEnum.CREATE_SERVICE, ComponentTypeEnum.SERVICE); + throw exp; } + service.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); service.setContactId(service.getContactId().toLowerCase()); @@ -978,57 +971,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.left(service); } - - - private Either<Boolean, ResponseFormat> validateServiceFieldsBeforeCreate(User user, Service service, AuditingActionEnum actionEnum) { - try { - validateComponentFieldsBeforeCreate(user, service, actionEnum); - - Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, service, actionEnum); - if (serviceNameUniquenessValidation.isRight()) { - throw new ByResponseFormatComponentException(serviceNameUniquenessValidation.right().value()); - } - Either<Boolean, ResponseFormat> categoryValidation = validateServiceCategory(user, service, actionEnum); - if (categoryValidation.isRight()) { - return categoryValidation; - } - Either<Boolean, ResponseFormat> projectCodeValidation = validateProjectCode(user, service, actionEnum); - if (projectCodeValidation.isRight()) { - return projectCodeValidation; - } - validateServiceTypeAndCleanup(service); - - Either<Boolean, ResponseFormat> serviceRoleValidation = validateServiceRoleAndCleanup(user, service, actionEnum); - if (serviceRoleValidation.isRight()) { - return serviceRoleValidation; - } - return validateInstantiationTypeValue(user, service, actionEnum); - } catch (ComponentException exception) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(exception); - componentsUtils.auditComponentAdmin(responseFormat, user, service, - AuditingActionEnum.CREATE_SERVICE, ComponentTypeEnum.SERVICE); - return Either.right(responseFormat); - } - } - - private Either<Boolean, ResponseFormat> validateServiceCategory(User user, Service service, AuditingActionEnum actionEnum) { - log.debug("validate Service category"); - if (isEmpty(service.getCategories())) { - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); - componentsUtils.auditComponentAdmin(errorResponse, user, service, actionEnum, ComponentTypeEnum.SERVICE); - return Either.right(errorResponse); - } - Either<Boolean, ResponseFormat> validatCategory = validateServiceCategory(service.getCategories()); - if (validatCategory.isRight()) { - ResponseFormat responseFormat = validatCategory.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, service, actionEnum, ComponentTypeEnum.SERVICE); - return Either.right(responseFormat); - } - return Either.left(true); - } - public Either<Map<String, Boolean>, ResponseFormat> validateServiceNameExists(String serviceName, String userId) { - validateUserExists(userId, "validate Service Name Exists", false); + validateUserExists(userId); Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(serviceName, null, ComponentTypeEnum.SERVICE); // DE242223 @@ -1044,6 +988,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.right(responseFormat); } + public void setElementDao(IElementOperation elementDao) { + this.elementDao = elementDao; + } + @Autowired public void setCassandraAuditingDao(AuditCassandraDao auditingDao) { this.auditCassandraDao = auditingDao; @@ -1053,6 +1001,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return artifactsBusinessLogic; } + public void setArtifactBl(ArtifactsBusinessLogic artifactBl) { + this.artifactsBusinessLogic = artifactBl; + } + public Either<Service, ResponseFormat> updateServiceMetadata(String serviceId, Service serviceUpdate, User user) { user = validateUser(user, "updateServiceMetadata", serviceUpdate, null, false); // validate user role @@ -1078,42 +1030,49 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { Service serviceToUpdate = validationRsponse.left().value(); // lock resource - Either<Boolean, ResponseFormat> lockResult = lockComponent(serviceId, currentService, "Update Service Metadata"); - if (lockResult.isRight()) { - return Either.right(lockResult.right().value()); - } + lockComponent(serviceId, currentService, "Update Service Metadata"); try { - Either<Service, StorageOperationStatus> updateResponse = toscaOperationFacade.updateToscaElement(serviceToUpdate); - if (updateResponse.isRight()) { - janusGraphDao.rollback(); - BeEcompErrorManager.getInstance().logBeSystemError("Update Service Metadata"); - log.debug("failed to update sevice {}", serviceToUpdate.getUniqueId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - janusGraphDao.commit(); - return Either.left(updateResponse.left().value()); + return toscaOperationFacade.updateToscaElement(serviceToUpdate) + .right() + .map(rf -> { + janusGraphDao.rollback(); + BeEcompErrorManager.getInstance().logBeSystemError("Update Service Metadata"); + log.debug("failed to update sevice {}", serviceToUpdate.getUniqueId()); + return (componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + }) + .left() + .bind(c -> updateCatalogAndCommit(c)); + } finally { graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); } } - public Either<Set<String>, ResponseFormat> deleteForwardingPaths(String serviceId, Set<String> pathIdsToDelete, User user, boolean lock) { + private Either<Service, ResponseFormat> updateCatalogAndCommit(Service service){ + Either<Service, ResponseFormat> res = updateCatalog(service, ChangeTypeEnum.LIFECYCLE).left().map(s -> (Service)s); + janusGraphDao.commit(); + return res; + + } + + public Set<String> deleteForwardingPaths(String serviceId, Set<String> pathIdsToDelete, User user, boolean lock) { Service serviceToDelete = initServiceToDeletePaths(serviceId, pathIdsToDelete); user = validateUser(user, "deleteForwardingPaths", serviceToDelete, null, false); // validate user role validateUserRole(user, serviceToDelete, new ArrayList<>(), null, null); Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId); if (storageStatus.isRight()) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "")); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""); } Service service = storageStatus.left().value(); Either<Set<String>, StorageOperationStatus> result = null; if (lock) { - Either<Boolean, ResponseFormat> lockResult = lockComponent(service.getUniqueId(), service, "Delete Forwarding Path on Service"); - if (lockResult.isRight()) { + try { + lockComponent(service.getUniqueId(), service, "Delete Forwarding Path on Service"); + } catch (ComponentException e) { janusGraphDao.rollback(); - return Either.right(componentsUtils.getResponseFormat(componentsUtils - .convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "")); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse + (storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""); } } try{ @@ -1121,19 +1080,20 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { if (result.isRight()) { log.debug(FAILED_TO_LOCK_SERVICE_RESPONSE_IS, service.getName(), result.right().value()); janusGraphDao.rollback(); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE))); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse + (storageStatus.right().value(), ComponentTypeEnum.SERVICE)); } janusGraphDao.commit(); log.debug(THE_SERVICE_WITH_SYSTEM_NAME_LOCKED, service.getSystemName()); - } catch (Exception e){ + } catch (ComponentException e){ log.error("Exception occurred during delete forwarding path : {}", e.getMessage(), e); janusGraphDao.rollback(); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } finally { graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service); } - return Either.left(result.left().value()); + return result.left().value(); } private Service initServiceToDeletePaths(String serviceId, Collection<String> pathIdsToDelete) { @@ -1144,11 +1104,11 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return serviceToDelete; } - public Either<Service, ResponseFormat> updateForwardingPath(String serviceId, Service serviceUpdate, User user, boolean lock) { + public Service updateForwardingPath(String serviceId, Service serviceUpdate, User user, boolean lock) { return createOrUpdateForwardingPath(serviceId, serviceUpdate, user, true,"updateForwardingPath", lock); } - public Either<Service, ResponseFormat> createForwardingPath(String serviceId, Service serviceUpdate, User user, boolean lock) { + public Service createForwardingPath(String serviceId, Service serviceUpdate, User user, boolean lock) { return createOrUpdateForwardingPath(serviceId, serviceUpdate, user, false, "createForwardingPath", lock); } @@ -1164,7 +1124,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return dataDefinition; } - private Either<Service, ResponseFormat> createOrUpdateForwardingPath(String serviceId, Service serviceUpdate, User user, boolean isUpdate, String errorContext, boolean lock) { + private Service createOrUpdateForwardingPath(String serviceId, Service serviceUpdate, User user, boolean isUpdate, String errorContext, boolean lock) { validateUserAndRole(serviceUpdate, user, errorContext); Map<String, ForwardingPathDataDefinition> forwardingPaths = serviceUpdate.getForwardingPaths(); @@ -1173,83 +1133,80 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { forwardingPaths.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> new ForwardingPathDataDefinition(getTrimmedValues(entry.getValue())))); - Either<Boolean, ResponseFormat> booleanResponseFormatEither = forwardingPathValidator.validateForwardingPaths(trimmedForwardingPaths.values(), + forwardingPathValidator.validateForwardingPaths(trimmedForwardingPaths.values(), serviceId, isUpdate); - if(booleanResponseFormatEither.isRight()){ - return Either.right(booleanResponseFormatEither.right().value()); - } Either<Service, StorageOperationStatus> serviceStorageOperationStatusEither = toscaOperationFacade.getToscaElement(serviceId); if(serviceStorageOperationStatusEither.isRight()){ StorageOperationStatus errorStatus = serviceStorageOperationStatusEither.right().value(); log.debug("Failed to fetch service information by service id, error {}", errorStatus); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus))); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(errorStatus)); } Service storedService = serviceStorageOperationStatusEither.left().value(); Either<ForwardingPathDataDefinition, StorageOperationStatus> result; - Either<Component, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade.getLatestByName(ForwardingPathUtils.FORWARDING_PATH_NODE_NAME); - if (forwardingPathOrigin.isRight()) { - StorageOperationStatus errorStatus = forwardingPathOrigin.right().value(); - log.debug("Failed to fetch normative forwarding path resource by tosca name, error {}", errorStatus); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus))); - } - Component component = forwardingPathOrigin.left().value(); + Component component = getForwardingPathOriginComponent(); final String toscaResourceName; if ( component.getComponentType() == ComponentTypeEnum.RESOURCE) { toscaResourceName = ((Resource) component).getToscaResourceName(); } else { toscaResourceName = ""; } - Either<Boolean, ResponseFormat> lockResult = null; if (lock) { - lockResult = - lockComponent(storedService.getUniqueId(), storedService, "Add or Update Forwarding Path on Service"); - if (lockResult.isRight()) { - log.debug(FAILED_TO_LOCK_SERVICE_RESPONSE_IS, storedService.getName(), - lockResult.right().value().getFormattedMessage()); - return Either.right(lockResult.right().value()); - } else { - log.debug(THE_SERVICE_WITH_SYSTEM_NAME_LOCKED, storedService.getSystemName()); - } + lockComponent(storedService.getUniqueId(), storedService, "Add or Update Forwarding Path on Service"); + log.debug(THE_SERVICE_WITH_SYSTEM_NAME_LOCKED, storedService.getSystemName()); } Map<String, ForwardingPathDataDefinition> resultMap = new HashMap<>(); try { trimmedForwardingPaths.values().forEach(fp -> fp.setToscaResourceName(toscaResourceName)); - try { - for (ForwardingPathDataDefinition forwardingPathDataDefinition : trimmedForwardingPaths.values()) { - if (isUpdate) { - result = forwardingPathOperation.updateForwardingPath(serviceId, forwardingPathDataDefinition); - } else { - result = forwardingPathOperation.addForwardingPath(serviceId, forwardingPathDataDefinition); - } - if (result.isRight()) { - janusGraphDao.rollback(); - return Either.right(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(result.right().value(), ComponentTypeEnum.SERVICE), - "")); - } else { - ForwardingPathDataDefinition fpDataDefinition = result.left().value(); - resultMap.put(fpDataDefinition.getUniqueId(), forwardingPathDataDefinition); - } - } - - } catch (Exception e) { - janusGraphDao.rollback(); - log.error("Exception occurred during add or update forwarding path property values: {}", e.getMessage(), - e); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } + populateForwardingPaths(serviceId, isUpdate, trimmedForwardingPaths, resultMap); janusGraphDao.commit(); } finally { - if (lockResult != null && lockResult.isLeft() && lockResult.left().value()) { + if (lock) { graphLockOperation.unlockComponent(storedService.getUniqueId(), NodeTypeEnum.Service); } } - Service service = createServiceWithForwardingPathForResponse(serviceId, resultMap); - return Either.left(service); + return createServiceWithForwardingPathForResponse(serviceId, resultMap); + } + + private Component getForwardingPathOriginComponent() { + Either<Component, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade.getLatestByName(ForwardingPathUtils.FORWARDING_PATH_NODE_NAME); + if (forwardingPathOrigin.isRight()) { + StorageOperationStatus errorStatus = forwardingPathOrigin.right().value(); + log.debug("Failed to fetch normative forwarding path resource by tosca name, error {}", errorStatus); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(errorStatus)); + } + return forwardingPathOrigin.left().value(); + } + + private void populateForwardingPaths(String serviceId, boolean isUpdate, Map<String, ForwardingPathDataDefinition> trimmedForwardingPaths, Map<String, ForwardingPathDataDefinition> resultMap) { + Either<ForwardingPathDataDefinition, StorageOperationStatus> result; + try { + for (ForwardingPathDataDefinition forwardingPathDataDefinition : trimmedForwardingPaths.values()) { + if (isUpdate) { + result = forwardingPathOperation.updateForwardingPath(serviceId, forwardingPathDataDefinition); + } else { + result = forwardingPathOperation.addForwardingPath(serviceId, forwardingPathDataDefinition); + } + if (result.isRight()) { + janusGraphDao.rollback(); + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(result.right().value(), ComponentTypeEnum.SERVICE), + "")); + } else { + ForwardingPathDataDefinition fpDataDefinition = result.left().value(); + resultMap.put(fpDataDefinition.getUniqueId(), forwardingPathDataDefinition); + } + } + + } catch (ComponentException e) { + janusGraphDao.rollback(); + log.error("Exception occurred during add or update forwarding path property values: {}", + e.getMessage(), e); + throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); + } } private Service createServiceWithForwardingPathForResponse(String serviceId, Map<String,ForwardingPathDataDefinition> forwardingPathDataDefinitionMap) { @@ -1324,6 +1281,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { verifyValuesAreIdentical(serviceUpdate.getUUID(), currentService.getUUID(), "uuid"); validateAndUpdateServiceType(currentService, serviceUpdate); + validateAndUpdateServiceFunction(currentService, serviceUpdate); response = validateAndUpdateServiceRole(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA); if (response.isRight()) { @@ -1363,7 +1321,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { currentService.setEcompGeneratedNaming(isEcompGeneratedUpdate); } String namingPolicyUpdate = serviceUpdate.getNamingPolicy(); - if (currentService.isEcompGeneratedNaming()) { + if (currentService.isEcompGeneratedNaming() != null && currentService.isEcompGeneratedNaming()) { currentService.setNamingPolicy(namingPolicyUpdate); } else { if (!StringUtils.isEmpty(namingPolicyUpdate)) { @@ -1377,7 +1335,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { String contactIdUpdated = serviceUpdate.getContactId(); String contactIdCurrent = currentService.getContactId(); if (!contactIdCurrent.equals(contactIdUpdated)) { - validateContactId(user, serviceUpdate, audatingAction); + componentContactIdValidator.validateAndCorrectField(user, serviceUpdate, audatingAction); currentService.setContactId(contactIdUpdated.toLowerCase()); } return Either.left(true); @@ -1393,7 +1351,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } if (!(tagsCurrent.containsAll(tagsUpdated) && tagsUpdated.containsAll(tagsCurrent))) { - validateTagsListAndRemoveDuplicates(user, serviceUpdate, audatingAction); + componentTagsValidator.validateAndCorrectField(user, serviceUpdate, audatingAction); currentService.setTags(tagsUpdated); } return Either.left(true); @@ -1403,7 +1361,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { String descriptionUpdated = serviceUpdate.getDescription(); String descriptionCurrent = currentService.getDescription(); if (!descriptionCurrent.equals(descriptionUpdated)) { - validateDescriptionAndCleanup(user, serviceUpdate, audatingAction); + componentDescriptionValidator.validateAndCorrectField(user, serviceUpdate, audatingAction); currentService.setDescription(serviceUpdate.getDescription()); } return Either.left(true); @@ -1412,11 +1370,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { private Either<Boolean, ResponseFormat> validateAndUpdateProjectCode(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) { String projectCodeUpdated = serviceUpdate.getProjectCode(); String projectCodeCurrent = currentService.getProjectCode(); - if (!projectCodeCurrent.equals(projectCodeUpdated)) { + if (StringUtils.isEmpty(projectCodeCurrent) + || !projectCodeCurrent.equals(projectCodeUpdated)) { - Either<Boolean, ResponseFormat> validatProjectCodeResponse = validateProjectCode(user, serviceUpdate, audatingAction); - if (validatProjectCodeResponse.isRight()) { - ResponseFormat errorRespons = validatProjectCodeResponse.right().value(); + try { + componentProjectCodeValidator.validateAndCorrectField(user, serviceUpdate, audatingAction); + } catch (ComponentException exp) { + ResponseFormat errorRespons = exp.getResponseFormat(); return Either.right(errorRespons); } currentService.setProjectCode(projectCodeUpdated); @@ -1430,7 +1390,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { String iconCurrent = currentService.getIcon(); if (!iconCurrent.equals(iconUpdated)) { if (!hasBeenCertified) { - validateIcon(user, serviceUpdate, audatingAction); + componentIconValidator.validateAndCorrectField(user, serviceUpdate, audatingAction); currentService.setIcon(iconUpdated); } else { log.info("icon {} cannot be updated once the service has been certified once.", iconUpdated); @@ -1446,10 +1406,11 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { String serviceNameCurrent = currentService.getName(); if (!serviceNameCurrent.equals(serviceNameUpdated)) { if (!hasBeenCertified) { - validateComponentName(user, serviceUpdate, auditingAction); - Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, serviceUpdate, auditingAction); - if (serviceNameUniquenessValidation.isRight()) { - return serviceNameUniquenessValidation; + componentNameValidator.validateAndCorrectField(user, serviceUpdate, auditingAction); + try { + componentNameValidator.validateComponentNameUnique(user, serviceUpdate, auditingAction); + } catch (ComponentException exp) { + return Either.right(exp.getResponseFormat()); } currentService.setName(serviceNameUpdated); currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(serviceNameUpdated)); @@ -1468,34 +1429,17 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { String updatedServiceType = updatedService.getServiceType(); String currentServiceType = currentService.getServiceType(); if (!currentServiceType.equals(updatedServiceType)) { - validateServiceTypeAndCleanup(updatedService); + serviceTypeValidator.validateAndCorrectField(null, updatedService, null); currentService.setServiceType(updatedServiceType); } } - private void validateServiceTypeAndCleanup(Component component) { - log.debug("validate service type"); - String serviceType = ((Service)component).getServiceType(); - if (serviceType == null) { - log.info("service type is not valid."); - throw new ByActionStatusComponentException(ActionStatus.INVALID_SERVICE_TYPE); - } - serviceType = cleanUpText(serviceType); - validateServiceType(serviceType); - } - - - private void validateServiceType(String serviceType) { - if (serviceType.isEmpty()) { - return; - } - if (!ValidationUtils.validateServiceTypeLength(serviceType)) { - log.info("service type exceeds limit."); - throw new ByActionStatusComponentException(ActionStatus.SERVICE_TYPE_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_TYPE_MAX_LENGTH); - } - if (!ValidationUtils.validateIsEnglish(serviceType)) { - log.info("service type is not valid."); - throw new ByActionStatusComponentException(ActionStatus.INVALID_SERVICE_TYPE); + private void validateAndUpdateServiceFunction(Service currentService, Service updatedService) { + String updatedServiceFunction = updatedService.getServiceFunction(); + String currentServiceFunction = currentService.getServiceFunction(); + if (!currentServiceFunction.equals(updatedServiceFunction)) { + serviceFunctionValidator.validateAndCorrectField(null, updatedService, null); + currentService.setServiceFunction(updatedService.getServiceFunction()); } } @@ -1503,9 +1447,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { String updatedServiceRole = updatedService.getServiceRole(); String currentServiceRole = currentService.getServiceRole(); if (!currentServiceRole.equals(updatedServiceRole)) { - Either<Boolean, ResponseFormat> validateServiceRole = validateServiceRoleAndCleanup(user, updatedService , auditingAction); - if (validateServiceRole.isRight()) { - ResponseFormat errorResponse = validateServiceRole.right().value(); + try { + serviceRoleValidator.validateAndCorrectField(user, updatedService, auditingAction); + } catch (ComponentException exp) { + ResponseFormat errorResponse = exp.getResponseFormat(); componentsUtils.auditComponentAdmin(errorResponse, user, updatedService, auditingAction, ComponentTypeEnum.SERVICE); return Either.right(errorResponse); } @@ -1514,31 +1459,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.left(true); } - protected Either<Boolean, ResponseFormat> validateServiceRoleAndCleanup(User user, Component component, AuditingActionEnum actionEnum) { - log.debug("validate service role"); - String serviceRole = ((Service)component).getServiceRole(); - if (serviceRole != null){ - serviceRole = cleanUpText(serviceRole); - - Either<Boolean, ResponseFormat> validateServiceRole = validateServiceRole(serviceRole); - if (validateServiceRole.isRight()) { - ResponseFormat responseFormat = validateServiceRole.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, ComponentTypeEnum.SERVICE); - return Either.right(responseFormat); - } - return Either.left(true); - } else { - return Either.left(false); - } - } - private Either<Boolean, ResponseFormat> validateAndUpdateInstantiationTypeValue(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) { String updatedInstaType= updatedService.getInstantiationType(); String currentInstaType = currentService.getInstantiationType(); if (!currentInstaType.equals(updatedInstaType)) { - Either<Boolean, ResponseFormat> validateInstantiationType = validateInstantiationTypeValue(user, updatedService , auditingAction); - if (validateInstantiationType.isRight()) { - ResponseFormat errorResponse = validateInstantiationType.right().value(); + try { + serviceInstantiationTypeValidator.validateAndCorrectField(user, updatedService, auditingAction); + } catch (ComponentException exp) { + ResponseFormat errorResponse = exp.getResponseFormat(); componentsUtils.auditComponentAdmin(errorResponse, user, updatedService, auditingAction, ComponentTypeEnum.SERVICE); return Either.right(errorResponse); } @@ -1547,95 +1475,27 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.left(true); } - private Either<Boolean, ResponseFormat> validateInstantiationTypeValue(User user, Service service, AuditingActionEnum actionEnum) { - log.debug("validate instantiation type"); - String instantiationType = service.getInstantiationType(); - if (!InstantiationTypes.containsName(instantiationType) || instantiationType == null){ - log.error("Recieved Instantiation type {} is not valid.", instantiationType); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_INSTANTIATION_TYPE); - componentsUtils.auditComponentAdmin(errorResponse, user, service, actionEnum, ComponentTypeEnum.SERVICE); - return Either.right(errorResponse); - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateServiceRole(String serviceRole) { - if (serviceRole.equals("")){ - return Either.left(true); - } else { - if (!ValidationUtils.validateServiceRoleLength(serviceRole)) { - log.info("service role exceeds limit."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_ROLE_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_ROLE_MAX_LENGTH); - return Either.right(errorResponse); - } - - if (!ValidationUtils.validateIsEnglish(serviceRole)) { - log.info("service role is not valid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_ROLE); - return Either.right(errorResponse); - } - return Either.left(true); - } - } - private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) { - List<CategoryDefinition> categoryUpdated = serviceUpdate.getCategories(); - List<CategoryDefinition> categoryCurrent = currentService.getCategories(); - Either<Boolean, ResponseFormat> validateCategoryResponse = validateServiceCategory(user, serviceUpdate, audatingAction); - if (validateCategoryResponse.isRight()) { - return Either.right(validateCategoryResponse.right().value()); - } - if (!categoryCurrent.get(0).getName().equals(categoryUpdated.get(0).getName())) { - if (!hasBeenCertified) { - currentService.setCategories(categoryUpdated); - } else { - log.info("category {} cannot be updated once the service has been certified once.", categoryUpdated); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_CATEGORY_CANNOT_BE_CHANGED); - return Either.right(errorResponse); + try { + List<CategoryDefinition> categoryUpdated = serviceUpdate.getCategories(); + List<CategoryDefinition> categoryCurrent = currentService.getCategories(); + serviceCategoryValidator.validateAndCorrectField(user, serviceUpdate, audatingAction); + if (!categoryCurrent.get(0).getName().equals(categoryUpdated.get(0).getName())) { + if (!hasBeenCertified) { + currentService.setCategories(categoryUpdated); + } else { + log.info("category {} cannot be updated once the service has been certified once.", categoryUpdated); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_CATEGORY_CANNOT_BE_CHANGED); + return Either.right(errorResponse); + } } + } catch (ComponentException exp) { + return Either.right(exp.getResponseFormat()); } return Either.left(true); } - private Either<Boolean, ResponseFormat> validateServiceCategory(List<CategoryDefinition> list) { - if (list != null) { - if (list.size() > 1) { - log.debug("Must be only one category for service"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.SERVICE.getValue()); - return Either.right(responseFormat); - } - CategoryDefinition category = list.get(0); - if (category.getSubcategories() != null) { - log.debug("Subcategories cannot be defined for service"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_CANNOT_CONTAIN_SUBCATEGORY); - return Either.right(responseFormat); - } - if (!ValidationUtils.validateStringNotEmpty(category.getName())) { - log.debug("Resource category is empty"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); - return Either.right(responseFormat); - } - - log.debug("validating service category {} against valid categories list", list); - Either<List<CategoryDefinition>, ActionStatus> categorys = elementDao.getAllServiceCategories(); - if (categorys.isRight()) { - log.debug("failed to retrieve service categories from JanusGraph"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(categorys.right().value()); - return Either.right(responseFormat); - } - List<CategoryDefinition> categoryList = categorys.left().value(); - for (CategoryDefinition value : categoryList) { - if (value.getName().equals(category.getName())) { - return Either.left(true); - } - } - log.debug("Category {} is not part of service category group. Service category valid values are {}", list, categoryList); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue())); - } - return Either.left(false); - } - public Either<ServiceRelations, ResponseFormat> getServiceComponentsRelations(String serviceId, User user) { Either<Service, ResponseFormat> serviceResponseFormatEither = getService(serviceId, user); if (serviceResponseFormatEither.isRight()){ @@ -1649,9 +1509,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { public ResponseFormat deleteService(String serviceId, User user) { ResponseFormat responseFormat; - String ecompErrorContext = "delete service"; - validateUserExists(user, ecompErrorContext, false); + validateUserExists(user); Either<Service, StorageOperationStatus> serviceStatus = toscaOperationFacade.getToscaElement(serviceId); if (serviceStatus.isRight()) { log.debug("failed to get service {}", serviceId); @@ -1661,21 +1520,20 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { Service service = serviceStatus.left().value(); StorageOperationStatus result = StorageOperationStatus.OK; - Either<Boolean, ResponseFormat> lockResult = lockComponent(service, "Mark service to delete"); - if (lockResult.isRight()) { - return lockResult.right().value(); - } try { + lockComponent(service, "Mark service to delete"); result = markComponentToDelete(service); - if (result.equals(StorageOperationStatus.OK)) { + if (result == StorageOperationStatus.OK) { responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); } else { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName()); } return responseFormat; - } finally { - if (result == null || !result.equals(StorageOperationStatus.OK)) { + }catch (ComponentException e){ + return e.getResponseFormat(); + }finally { + if (result == null || result != StorageOperationStatus.OK) { log.warn("operation failed. do rollback"); BeEcompErrorManager.getInstance().logBeSystemError("Delete Service"); janusGraphDao.rollback(); @@ -1691,7 +1549,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { ResponseFormat responseFormat; String ecompErrorContext = "delete service"; validateUserNotEmpty(user, ecompErrorContext); - user = validateUserExists(user, ecompErrorContext, false); + user = validateUserExists(user); Either<Service, ResponseFormat> getResult = getServiceByNameAndVersion(serviceName, version, user.getUserId()); if (getResult.isRight()) { @@ -1700,15 +1558,11 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { Service service = getResult.left().value(); StorageOperationStatus result = StorageOperationStatus.OK; - Either<Boolean, ResponseFormat> lockResult = lockComponent(service, "Mark service to delete"); - if (lockResult.isRight()) { - result = StorageOperationStatus.GENERAL_ERROR; - return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - } try { + lockComponent(service, "Mark service to delete"); result = markComponentToDelete(service); - if (result.equals(StorageOperationStatus.OK)) { + if (result == StorageOperationStatus.OK) { responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); } else { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); @@ -1716,8 +1570,11 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } return responseFormat; - } finally { - if (result == null || !result.equals(StorageOperationStatus.OK)) { + }catch (ComponentException e){ + result = StorageOperationStatus.GENERAL_ERROR; + return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + }finally { + if (result == null || result != StorageOperationStatus.OK) { log.warn("operation failed. do rollback"); BeEcompErrorManager.getInstance().logBeSystemError("Delete Service"); janusGraphDao.rollback(); @@ -1732,7 +1589,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { public Either<Service, ResponseFormat> getService(String serviceId, User user) { String ecompErrorContext = "Get service"; validateUserNotEmpty(user, ecompErrorContext); - validateUserExists(user, ecompErrorContext, false); + validateUserExists(user); Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId); if (storageStatus.isRight()) { @@ -1752,7 +1609,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } public Either<Service, ResponseFormat> getServiceByNameAndVersion(String serviceName, String serviceVersion, String userId) { - validateUserExists(userId, "get Service By Name And Version", false); + validateUserExists(userId); Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.SERVICE, serviceName, serviceVersion); if (storageStatus.isRight()) { log.debug("failed to get service by name {} and version {}", serviceName, serviceVersion); @@ -1812,28 +1669,24 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return artifactInfo; } - private Either<DistributionTransitionEnum, ResponseFormat> validateTransitionEnum(String distributionTransition) { - DistributionTransitionEnum transitionEnum = null; + private DistributionTransitionEnum validateTransitionEnum(String distributionTransition) { + DistributionTransitionEnum transitionEnum; transitionEnum = DistributionTransitionEnum.getFromDisplayName(distributionTransition); if (transitionEnum == null) { BeEcompErrorManager.getInstance().logBeSystemError(CHANGE_SERVICE_DISTRIBUTION); log.info("state operation is not valid. operations allowed are: {}", DistributionTransitionEnum.valuesAsString()); - ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - return Either.right(error); + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_DISTRIBUTION_STATUS, distributionTransition)); } - return Either.left(transitionEnum); + return transitionEnum; } - private Either<String, ResponseFormat> validateComment(LifecycleChangeInfoWithAction comment) { - String data = comment.getUserRemarks(); - - if (data == null || data.trim().isEmpty()) { - BeEcompErrorManager.getInstance().logBeInvalidJsonInput(CHANGE_SERVICE_DISTRIBUTION); - log.debug("user comment cannot be empty or null."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + private String validateComment(LifecycleChangeInfoWithAction comment) { + if (comment==null || StringUtils.isEmpty(comment.getUserRemarks())) { + return ""; } + String data = comment.getUserRemarks(); data = ValidationUtils.removeNoneUtf8Chars(data); data = ValidationUtils.removeHtmlTags(data); data = ValidationUtils.normaliseWhitespace(data); @@ -1842,45 +1695,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { if (!ValidationUtils.validateLength(data, ValidationUtils.COMMENT_MAX_LENGTH)) { BeEcompErrorManager.getInstance().logBeInvalidJsonInput(CHANGE_SERVICE_DISTRIBUTION); log.debug("user comment exceeds limit."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, "comment", String.valueOf(ValidationUtils.COMMENT_MAX_LENGTH))); + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, "comment", String.valueOf(ValidationUtils.COMMENT_MAX_LENGTH))); } - if (!ValidationUtils.validateIsEnglish(data)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - return Either.left(data); - } - - private Either<Service, ResponseFormat> validateServiceDistributionChange(User user, String serviceId, AuditingActionEnum auditAction, String comment) { - Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId); - if (storageStatus.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId); - log.debug(AUDIT_BEFORE_SENDING_RESPONSE); - componentsUtils.auditComponent(responseFormat, user, auditAction, new ResourceCommonInfo(serviceId, ComponentTypeEnum.SERVICE.getValue()), comment); - return Either.right(responseFormat); + if (!ValidationUtils.validateCommentPattern(data)) { + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); } - Service service = storageStatus.left().value(); - if (service.getLifecycleState() != LifecycleStateEnum.CERTIFIED) { - log.info("service {} is not available for distribution. Should be in certified state", service.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, service.getVersion(), service.getName()); - createAudit(user, auditAction, comment, service, responseFormat); - return Either.right(responseFormat); - } - return Either.left(service); - } - - private Either<User, ResponseFormat> validateUserDistributionChange(User user, Service service, AuditingActionEnum auditAction, String comment) { - log.debug("get user from DB"); - - // get user details - user = validateUser(user, "Activate Distribution", service, auditAction, false); - // validate user role - List<Role> roles = new ArrayList<>(); - roles.add(Role.ADMIN); - roles.add(Role.GOVERNOR); - roles.add(Role.OPS); - validateUserRole(user, service, roles, auditAction, comment); - return Either.left(user); + return data; } private void createAudit(User user, AuditingActionEnum auditAction, String comment, Service component, ResponseFormat responseFormat) { @@ -1931,10 +1752,11 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { public Either<Service, ResponseFormat> activateDistribution(String serviceId, String envName, User modifier, HttpServletRequest request) { - User user = validateUserExists(modifier.getUserId(), "activate Distribution", false); - Either<Service, ResponseFormat> result = null; - ResponseFormat response = null; - Service updatedService = null; + User user = validateUserExists(modifier.getUserId()); + validateUserRole(user, Collections.singletonList(Role.DESIGNER)); + Either<Service, ResponseFormat> result; + ResponseFormat response; + Service updatedService; String did = ThreadLocalsHolder.getUuid(); // DE194021 String configuredEnvName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0); @@ -1965,10 +1787,19 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.right(response); } Service service = serviceRes.left().value(); + if (service.isArchived()) { + log.info("Component is archived. Component id: {}", serviceId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, service.getName())); + } + if (service.getLifecycleState() != LifecycleStateEnum.CERTIFIED) { + log.info("service {} is not available for distribution. Should be in certified state", service.getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, service.getVersion(), service.getName()); + return Either.right(responseFormat); + } String dcurrStatus = service.getDistributionStatus().name(); String updatedStatus = dcurrStatus; StorageOperationStatus readyForDistribution = distributionEngine.isReadyForDistribution(envName); - if (readyForDistribution.equals(StorageOperationStatus.OK)) { + if (readyForDistribution == StorageOperationStatus.OK) { INotificationData notificationData = distributionEngine.buildServiceForDistribution(service, did, null); ActionStatus notifyServiceResponse = distributionEngine.notifyService(did, service, notificationData, envName, user); if (notifyServiceResponse == ActionStatus.OK) { @@ -1990,7 +1821,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { result = Either.right(response); } } else { - response = componentsUtils.getResponseFormatByDE(componentsUtils.convertFromStorageResponse(readyForDistribution), envName); + response = componentsUtils.getResponseFormatByDE(componentsUtils.convertFromStorageResponse(readyForDistribution, ComponentTypeEnum.SERVICE), envName); result = Either.right(response); } componentsUtils.auditComponent(response, user, service, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, @@ -2008,13 +1839,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { // convert to private after deletion of temp url public Either<Service, ResponseFormat> updateDistributionStatusForActivation(Service service, User user, DistributionStatusEnum state) { - validateUserExists(user.getUserId(), "update Distribution Status For Activation", false); + validateUserExists(user.getUserId()); String serviceId = service.getUniqueId(); - Either<Boolean, ResponseFormat> lockResult = lockComponent(serviceId, service, "updateDistributionStatusForActivation"); - if (lockResult.isRight()) { - return Either.right(lockResult.right().value()); - } + lockComponent(serviceId, service, "updateDistributionStatusForActivation"); try { Either<Service, StorageOperationStatus> result = toscaOperationFacade.updateDistributionStatus(service, user, state); if (result.isRight()) { @@ -2024,6 +1852,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } janusGraphDao.commit(); + updateCatalog(service, ChangeTypeEnum.LIFECYCLE); return Either.left(result.left().value()); } finally { graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); @@ -2032,7 +1861,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { public Either<Service, ResponseFormat> markDistributionAsDeployed(String serviceId, String did, User user) { - validateUserExists(user.getUserId(), "mark Distribution As Deployed", false); + validateUserExists(user.getUserId()); log.debug("mark distribution deployed"); AuditingActionEnum auditAction = AuditingActionEnum.DISTRIBUTION_DEPLOY; @@ -2172,13 +2001,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } vfModuleArtifactDefinition.setArtifactChecksum(newCheckSum); - Either<ArtifactDefinition, StorageOperationStatus> addArifactToComponent = artifactToscaOperation.addArifactToComponent(vfModuleArtifactDefinition, service.getUniqueId(), NodeTypeEnum.ResourceInstance, true, currVF.getUniqueId()); + Either<ArtifactDefinition, StorageOperationStatus> addArtifactToComponent = artifactToscaOperation.addArtifactToComponent( + vfModuleArtifactDefinition, service, NodeTypeEnum.ResourceInstance, true, currVF.getUniqueId()); Either<ArtifactDefinition, ResponseFormat> result; - if (addArifactToComponent.isLeft()) { - result = Either.left(addArifactToComponent.left().value()); + if (addArtifactToComponent.isLeft()) { + result = Either.left(addArtifactToComponent.left().value()); } else { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArifactToComponent.right().value()))); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtifactToComponent.right().value()))); } return result; @@ -2205,19 +2035,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { if (service.getComponentInstances() != null) { List<ArtifactGenerator<CallVal>> artifactGenList = service.getComponentInstances().stream().flatMap(ri -> artifactTaskGeneratorCreator.apply(ri).stream()).collect(Collectors.toList()); if (artifactGenList != null && !artifactGenList.isEmpty()) { - for (ArtifactGenerator<CallVal> entry : artifactGenList) { - Either<CallVal, ResponseFormat> callRes; - try { - callRes = entry.call(); - if (callRes.isRight()) { - log.debug("Failed to generate artifact error : {}", callRes.right().value()); - return Either.right(callRes.right().value()); - } - } catch (Exception e) { - log.debug("Failed to generate artifact exception : {}", e); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } + Either<Service, ResponseFormat> callRes = checkDeploymentArtifact(artifactGenList); + if (callRes != null) return callRes; } } Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaFullElement(service.getUniqueId()); @@ -2231,6 +2050,23 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } + private <CallVal> Either<Service, ResponseFormat> checkDeploymentArtifact(List<ArtifactGenerator<CallVal>> artifactGenList) { + for (ArtifactGenerator<CallVal> entry : artifactGenList) { + Either<CallVal, ResponseFormat> callRes; + try { + callRes = entry.call(); + if (callRes.isRight()) { + log.debug("Failed to generate artifact error : {}", callRes.right().value()); + return Either.right(callRes.right().value()); + } + } catch (Exception e) { + log.debug("Failed to generate artifact exception : {}", e); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + return null; + } + abstract class ArtifactGenerator<CallVal> implements Callable<Either<CallVal, ResponseFormat>> { } @@ -2388,19 +2224,11 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } private User validateRoleForDeploy(String did, User user, AuditingActionEnum auditAction, Service service) { - Either<User, ActionStatus> eitherCreator = userAdmin.getUser(user.getUserId(), false); - if (eitherCreator.isRight() || eitherCreator.left().value() == null) { - BeEcompErrorManager.getInstance().logBeUserMissingError("Deploy Service", user.getUserId()); - log.debug("validateRoleForDeploy method - user is not listed. userId= {}", user.getUserId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, user.getUserId()); - auditDeployError(did, user, auditAction, service, ActionStatus.USER_NOT_FOUND); - throw new ByActionStatusComponentException(ActionStatus.USER_NOT_FOUND, user.getUserId()); - } - user = eitherCreator.left().value(); + user = userAdmin.getUser(user.getUserId()); log.debug("validate user role"); List<Role> roles = new ArrayList<>(); roles.add(Role.ADMIN); - roles.add(Role.OPS); + roles.add(Role.DESIGNER); try{ validateUserRole(user, service, roles, auditAction, null); } catch (ByActionStatusComponentException e){ @@ -2440,7 +2268,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { @Override public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, String userId) { - validateUserExists(userId, "Get Component Instances", false); + validateUserExists(userId); Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll); if (getComponentRes.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentRes.right().value())); @@ -2566,7 +2394,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { private Either<ImmutablePair<Component, User>, ResponseFormat> validateUserAndComponent(String serviceId, User modifier) { Either<ImmutablePair<Component, User>, ResponseFormat> result = null; - Either<Component, ResponseFormat> validateComponentExistsRes = null; User currUser = null; Component component = null; Either<User, ResponseFormat> validationUserResult = validateUserIgnoreAudit(modifier, "updateGroupInstancePropertyValues"); @@ -2576,19 +2403,18 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } if (result == null) { currUser = validationUserResult.left().value(); - validateComponentExistsRes = validateComponentExists(serviceId, ComponentTypeEnum.SERVICE, null); - if (validateComponentExistsRes.isRight()) { + try { + component = validateComponentExists(serviceId, ComponentTypeEnum.SERVICE, null); + if (!ComponentValidationUtils.canWorkOnComponent(component, currUser.getUserId())) { + log.info("#validateUserAndComponent - Restricted operation for user: {}, on service: {}", currUser.getUserId(), component.getCreatorUserId()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + } catch (ComponentException e) { log.debug("#validateUserAndComponent - Failed to validate service existing {}. ", serviceId); - result = Either.right(validateComponentExistsRes.right().value()); - } - } - if (result == null) { - component = validateComponentExistsRes.left().value(); - if (!ComponentValidationUtils.canWorkOnComponent(component, currUser.getUserId())) { - log.info("#validateUserAndComponent - Restricted operation for user: {}, on service: {}", currUser.getUserId(), component.getCreatorUserId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + result = Either.right(e.getResponseFormat()); } } + if (result == null) { result = Either.left(new ImmutablePair<>(component, currUser)); } @@ -2641,7 +2467,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { Either<Service, StorageOperationStatus> serviceResultEither = toscaOperationFacade.getToscaElement(serviceId, paramsToReturn); if (serviceResultEither.isRight()) { - if(serviceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + if(serviceResultEither.right().value() == StorageOperationStatus.NOT_FOUND) { log.debug("#getUiComponentDataTransferByComponentId - Failed to find service with id {} ", serviceId); return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId)); } @@ -2661,11 +2487,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } public Either<String, ResponseFormat> deleteIfNotAlreadyDeletedServiceFilter(String serviceId, String resourceId, String userId, boolean lock) { - Service serviceToDelete = initServiceToDeleteServiceFilter(serviceId); - User user = validateUserExists(userId, "Create service Filter", false); - - user = - validateUser(user, "deleteIfNotAlreadyDeletedServiceFilter", serviceToDelete, null, false); + validateUserExists(userId); Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId); if (storageStatus.isRight()) { @@ -2687,15 +2509,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } Either<String, StorageOperationStatus> result; - if (lock) { - Either<Boolean, ResponseFormat> lockResult = lockComponent(service.getUniqueId(), service, "Delete Service Filter from service"); - if (lockResult.isRight()) { - janusGraphDao.rollback(); - return Either.right(componentsUtils.getResponseFormat(componentsUtils - .convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "")); - } - } try{ + if (lock) { + lockComponent(service.getUniqueId(), service, "Delete Service Filter from service"); + } result = serviceFilterOperation.deleteNodeFilter(service , resourceId); if (result.isRight()) { log.debug("Failed to delete node filter in service {}. Response is {}. ", service.getName(), result.right().value()); @@ -2716,16 +2533,9 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } - private Service initServiceToDeleteServiceFilter(String serviceId) { - Service serviceToDelete = new Service(); - serviceToDelete.setUniqueId(serviceId); - return serviceToDelete; - } - - public Either<CINodeFilterDataDefinition, ResponseFormat> createIfNotAlreadyExistServiceFilter(String serviceId, String componentInstanceId, String userId, boolean lock) { String errorContext = "createIfNotAlreadyExistServiceFilter"; - User user = validateUserExists(userId, "Create service Filter", false); + User user = validateUserExists(userId); Either<Service, StorageOperationStatus> serviceEither = toscaOperationFacade.getToscaElement(serviceId); if (serviceEither.isRight()) { @@ -2743,21 +2553,11 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { if (serviceFilter != null){ return Either.left(serviceFilter); } - - Either<CINodeFilterDataDefinition, StorageOperationStatus> result; - - Either<Boolean, ResponseFormat> lockResult = null; if (lock) { - lockResult = - lockComponent(service.getUniqueId(), service, "Create Service Filter"); - if (lockResult.isRight()) { - log.debug("Failed to lock service {}. Response is {}. ", service.getName(), - lockResult.right().value().getFormattedMessage()); - return Either.right(lockResult.right().value()); - } else { - log.debug("The service with system name {} locked. ", service.getSystemName()); - } + lockComponent(service.getUniqueId(), service, "Create Service Filter"); } + Either<CINodeFilterDataDefinition, StorageOperationStatus> result; + CINodeFilterDataDefinition serviceFilterResult; try { result = serviceFilterOperation.createNodeFilter(serviceId, componentInstanceId); @@ -2778,9 +2578,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } finally { - if (lockResult != null && lockResult.isLeft() && lockResult.left().value()) { - graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service); - } + graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service); } return Either.left(serviceFilterResult); } @@ -2788,8 +2586,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { public Either<CINodeFilterDataDefinition, ResponseFormat> updateServiceFilter(String serviceId, String componentInstanceId, List<String> constraints, User inUser, boolean lock) { - String errorContext = "createIfNotAlreadyExistServiceFilter"; - User user = validateUserExists(inUser, errorContext, true); + User user = validateUserExists(inUser.getUserId()); validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN)); Either<Service, StorageOperationStatus> serviceStorageOperationStatusEither = toscaOperationFacade.getToscaElement(serviceId); @@ -2810,15 +2607,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { Either<Boolean, ResponseFormat> lockResult = null; if (lock) { - lockResult = - lockComponent(storedService.getUniqueId(), storedService, "Add or Update Service Filter on Service"); - if (lockResult.isRight()) { - log.debug("Failed to lock service {}. Response is {}. ", storedService.getName(), - lockResult.right().value().getFormattedMessage()); - return Either.right(lockResult.right().value()); - } else { - log.debug("The service with system name {} locked. ", storedService.getSystemName()); - } + lockComponent(storedService.getUniqueId(), storedService, "Add or Update Service Filter on Service"); } Optional<ComponentInstance> componentInstanceOptional = storedService.getComponentInstanceById(componentInstanceId); if (!componentInstanceOptional.isPresent()){ @@ -2865,8 +2654,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { public Either<CINodeFilterDataDefinition, ResponseFormat> addOrDeleteServiceFilter(String serviceId, String componentInstanceId, NodeFilterConstraintAction action, String propertyName, String constraint, int position, User inUser, boolean lock) { - String errorContext = "createIfNotAlreadyExistServiceFilter"; - User user = validateUserExists(inUser, errorContext, true); + User user = validateUserExists(inUser.getUserId()); validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN)); Either<Service, StorageOperationStatus> serviceStorageOperationStatusEither = toscaOperationFacade.getToscaElement(serviceId); @@ -2891,24 +2679,16 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { CINodeFilterDataDefinition serviceFilterResult = null; try { if (lock) { - lockResult = - lockComponent(storedService.getUniqueId(), storedService, "Add or Update Service Filter on Service"); - if (lockResult.isRight()) { - log.debug("Failed to lock service {}. Response is {}. ", storedService.getName(), - lockResult.right().value().getFormattedMessage()); - return Either.right(lockResult.right().value()); - } else { - log.debug("The service with system name {} locked. ", storedService.getSystemName()); - } + lockComponent(storedService.getUniqueId(), storedService, "Add or Update Service Filter on Service"); } Optional<ComponentInstance> componentInstanceOptional = storedService.getComponentInstanceById(componentInstanceId); - if (!componentInstanceOptional.isPresent()){ - return Either.right(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND)); + if (!componentInstanceOptional.isPresent()) { + return Either.right(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND)); } CINodeFilterDataDefinition serviceFilter = componentInstanceOptional.get().getNodeFilter(); - if(serviceFilter == null){ - return Either.right(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND)); + if (serviceFilter == null) { + return Either.right(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND)); } @@ -2917,13 +2697,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { RequirementNodeFilterPropertyDataDefinition newProperty = new RequirementNodeFilterPropertyDataDefinition(); newProperty.setName(propertyName); newProperty.setConstraints(Collections.singletonList(constraint)); - result = serviceFilterOperation.addNewProperty(serviceId, componentInstanceId,serviceFilter,newProperty); + result = serviceFilterOperation.addNewProperty(serviceId, componentInstanceId, serviceFilter, newProperty); break; case DELETE: result = serviceFilterOperation.deleteConstraint(serviceId, componentInstanceId, serviceFilter, position); break; default: - log.error("Unsupported operation "+action); + log.error("Unsupported operation " + action); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/SoftwareInformationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/SoftwareInformationBusinessLogic.java index 3129befb8c..3605856994 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/SoftwareInformationBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/SoftwareInformationBusinessLogic.java @@ -19,23 +19,24 @@ package org.openecomp.sdc.be.components.impl; -import static java.util.stream.Collectors.toList; -import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue; - -import java.util.List; -import java.util.Optional; import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.components.csar.CsarInfo; +import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException; import org.openecomp.sdc.be.csar.pnf.PnfSoftwareInformation; import org.openecomp.sdc.be.csar.pnf.PnfSoftwareVersion; import org.openecomp.sdc.be.csar.pnf.SoftwareInformationArtifactYamlParser; -import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.List; +import java.util.Optional; + +import static java.util.stream.Collectors.toList; +import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue; + @Component("softwareInformationBusinessLogic") public class SoftwareInformationBusinessLogic { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafPermission.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafPermission.java new file mode 100644 index 0000000000..9c952415a3 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafPermission.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl.aaf; + +import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; + +public enum AafPermission { + + READ(PermNames.READ_VALUE), + WRITE(PermNames.WRITE_VALUE), + DELETE(PermNames.DELETE_VALUE), + INTERNAL_ALL(PermNames.INTERNAL_ALL_VALUE); + + private String permission; + private String permissionSuffix; + + AafPermission(String permissionSuffix) { + this.permissionSuffix = permissionSuffix; + this.permission = String.format("%s.%s", + ConfigurationManager.getConfigurationManager().getConfiguration().getAafNamespace(), + permissionSuffix); + } + + public String getFullPermission() { + return permission; + } + + public static AafPermission getEnumByString(String perm) { + for (AafPermission e : AafPermission.values()) { + if (perm.equals(e.getPermissionSuffix())) + return e; + } + throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY, perm); + } + + public String getPermissionSuffix() { + return this.permissionSuffix; + } + + public static class PermNames { + public static final String READ_VALUE = "endpoint.api.access|*|read"; + public static final String WRITE_VALUE = "endpoint.api.access|*|write"; + public static final String DELETE_VALUE = "endpoint.api.access|*|delete"; + public static final String INTERNAL_ALL_VALUE = "endpoint.api.internal.access|*|all"; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafRoles.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafRoles.java new file mode 100644 index 0000000000..34ca5965a1 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafRoles.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl.aaf; + +import org.openecomp.sdc.be.config.ConfigurationManager; + +public enum AafRoles { + + READ_ONLY("app.readonly"), + ALL("app.all"); + + private String role; + + AafRoles(String roleSuffix) { + this.role = ConfigurationManager.getConfigurationManager().getConfiguration().getAafNamespace() + "." + roleSuffix; + } + + public String getRole() { + return role; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/PermissionAllowed.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/PermissionAllowed.java new file mode 100644 index 0000000000..a963e5e533 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/PermissionAllowed.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl.aaf; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface PermissionAllowed { + String[] value(); +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/RoleAuthorizationHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/RoleAuthorizationHandler.java new file mode 100644 index 0000000000..859872f5f3 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/RoleAuthorizationHandler.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl.aaf; + + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.servlets.BeGenericServlet; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; + +import javax.servlet.http.HttpServletRequest; + +// aop id defined via application-context.xml. the annotations are only for test purposes +@Aspect +public class RoleAuthorizationHandler { + + private static final Logger log = Logger.getLogger(RoleAuthorizationHandler.class); + + private ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager(); + + @Before("@annotation(permissions)") + public void authorizeRole(JoinPoint joinPoint, PermissionAllowed permissions) { + + if (isPermissionAuthenticationNeeded()) { + String methodName = joinPoint.getSignature().toShortString(); + HttpServletRequest request = ((BeGenericServlet) joinPoint.getThis()).getServletRequest(); + String[] perms = permissions.value(); + logAuth(methodName, perms, true, null); + for (String perm : perms) { + if (request.isUserInRole(getFullPermission(perm))) { + logAuth(methodName, perms, false, true); + return; + } + } + logAuth(methodName, perms, false, false); + throw new ByActionStatusComponentException(ActionStatus.AUTH_FAILED); + } + + } + + private void logAuth(String methodName, String[] perms, boolean beforeAuth, Boolean success) { + if (beforeAuth) + log.trace("#{} - authorizing before invoking endpoint {}", methodName); + else { + String status = success ? "SUCCESS" : "FAILED"; + log.trace("#{} - authorizing before invoking endpoint {}, Status: {}", methodName, status); + } + } + + private String getFullPermission(String role) { + return AafPermission.getEnumByString(role).getFullPermission(); + } + + private boolean isPermissionAuthenticationNeeded() { + if (configurationManager.getConfiguration().getAafAuthNeeded() && ThreadLocalsHolder.isExternalRequest()) { + return true; + } else return false; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByActionStatusComponentException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByActionStatusComponentException.java index 4a19fdaf06..788d63819e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByActionStatusComponentException.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByActionStatusComponentException.java @@ -19,17 +19,19 @@ */ package org.openecomp.sdc.be.components.impl.exceptions; -import java.util.Arrays; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.exception.ResponseFormat; +import java.util.Arrays; + public class ByActionStatusComponentException extends ComponentException { private final ActionStatus actionStatus; private final String[] params; public ByActionStatusComponentException(ActionStatus actionStatus, String... params) { + super(actionStatus, params); this.actionStatus = actionStatus; this.params = params.clone(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByResponseFormatComponentException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByResponseFormatComponentException.java index 0737c45d49..85fe3ec58a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByResponseFormatComponentException.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByResponseFormatComponentException.java @@ -19,14 +19,28 @@ */ package org.openecomp.sdc.be.components.impl.exceptions; +import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.exception.ResponseFormat; public class ByResponseFormatComponentException extends ComponentException { private final transient ResponseFormat responseFormat; + private final ActionStatus actionStatus; + private final String[] params; - public ByResponseFormatComponentException(ResponseFormat responseFormat) { + public ByResponseFormatComponentException(ResponseFormat responseFormat, String... params) { + super(responseFormat); this.responseFormat = responseFormat; + this.params = params.clone(); + this.actionStatus = ActionStatus.OK; + } + + public String[] getParams() { + return params.clone(); + } + + public ActionStatus getActionStatus(){ + return actionStatus; } @Override diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java index bedb299163..1d9809806c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * SDC * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,22 +16,64 @@ * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= - * Modifications copyright (c) 2019 Nokia - * ================================================================================ */ + package org.openecomp.sdc.be.components.impl.exceptions; +import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.exception.ResponseFormat; -/** - * This class will be initialized either by action status and params or by ResponseFormat - */ -public abstract class ComponentException extends RuntimeException { +import javax.annotation.Nullable; + +public class ComponentException extends RuntimeException { + + /** + * This class will be initialized either by action status and params or by ResponseFormat + */ + + private final transient ResponseFormat responseFormat; + private final ActionStatus actionStatus; + private final String[] params; + + public Resource getResource() { + return resource; + } + + private final Resource resource; + + public ComponentException(ResponseFormat responseFormat) { + this(responseFormat, ActionStatus.OK, null); + } - public abstract ResponseFormat getResponseFormat(); + public ComponentException(ActionStatus actionStatus, String... params) { + this(ResponseFormatManager.getInstance().getResponseFormat(actionStatus, params), actionStatus, null, params); + } + + public ComponentException(ActionStatus actionStatus, Resource resource, String... params) { + this(ResponseFormatManager.getInstance().getResponseFormat(actionStatus, params), actionStatus, resource, params); + } - @Override - public String getMessage() { - return this.toString(); + private ComponentException(ResponseFormat responseFormat, ActionStatus actionStatus, Resource resource, String... params) { + this.actionStatus = actionStatus; + this.params = params.clone(); + this.responseFormat = responseFormat; + this.resource = resource; } + + @Nullable + public ResponseFormat getResponseFormat() { + return responseFormat; + } + + public ActionStatus getActionStatus() { + return actionStatus; + } + + public String[] getParams() { + return params.clone(); + } + + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupVersionUpdater.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupVersionUpdater.java new file mode 100644 index 0000000000..bb4d884811 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupVersionUpdater.java @@ -0,0 +1,125 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl.group; + + +import org.openecomp.sdc.be.components.impl.version.OnChangeVersionCommand; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.GroupTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.model.utils.GroupUtils; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import java.util.stream.Collectors; + +import static org.apache.commons.collections.CollectionUtils.isEmpty; + + +/** + * A Helper class which handles altering the version of a group + */ +@org.springframework.stereotype.Component +public class GroupVersionUpdater implements OnChangeVersionCommand { + + private static final Logger log = Logger.getLogger(GroupVersionUpdater.class); + private final GroupsOperation groupsOperation; + private final ComponentsUtils componentsUtils; + + + public GroupVersionUpdater(GroupsOperation groupsOperation, ComponentsUtils componentsUtils) { + this.groupsOperation = groupsOperation; + this.componentsUtils = componentsUtils; + + } + + + @Override + public ActionStatus onChangeVersion(Component container) { + log.debug("#onChangeVersion - replacing all group members for component instance"); + Consumer<List<GroupDefinition>> replaceGroupMemberTask = (groups) -> increaseVersion(groups, container); + return updateGroupsVersion(container, replaceGroupMemberTask); + } + + public void increaseVersion(List<GroupDefinition> groups, Component container) { + groups.forEach(group -> increaseMajorVersion(group, container)); + } + + + private void increaseMajorVersion(GroupDefinition group, Component container) { + String version = group.getVersion(); + + String newVersion = GroupUtils.updateVersion(PromoteVersionEnum.MAJOR, group.getVersion()); + + if(!version.equals(newVersion) ){ + if(isGenerateGroupUUID(group, container)) { + String groupUUID = UniqueIdBuilder.generateUUID(); + group.setGroupUUID(groupUUID); + } + group.setVersion(String.valueOf(newVersion)); + } + + } + + private boolean isGenerateGroupUUID(GroupDefinition group, Component container) { + if(GroupTypeEnum.VF_MODULE.getGroupTypeName().equals(group.getType())){ + List<String> artifactsUuid = group.getArtifactsUuid(); + List<String> heatArtifactUniqueIDs = group.getArtifacts().stream().filter(a->!a.endsWith("env")).collect(Collectors.toList()); + Map<String, ArtifactDefinition> deploymentArtifacts = container.getDeploymentArtifacts(); + for (String heatArtifactUniqueID : heatArtifactUniqueIDs){ + ArtifactDefinition artifactDefinition = deploymentArtifacts.get(heatArtifactUniqueID.split("\\.", -1)[1]); + if((artifactDefinition == null || artifactDefinition.isEmpty()) + && !artifactsUuid.contains(artifactDefinition.getArtifactUUID()) ){ + return true; + } + } + return false; + } + return true; + } + + + private ActionStatus updateGroupsVersion(Component groupsContainer, Consumer<List<GroupDefinition>> updateGroupVersion) { + List<GroupDefinition> groups = groupsContainer.getGroups(); + if (isEmpty(groups)) { + return ActionStatus.OK; + } + updateGroupVersion.accept(groups); + return updateGroups(groupsContainer.getUniqueId(), groups); + } + + + private ActionStatus updateGroups(String componentId, List<GroupDefinition> groupsToUpdate) { + log.debug("#updateGroups - updating {} groups for container {}", groupsToUpdate.size(), componentId); + return componentsUtils.convertFromStorageResponse(groupsOperation.updateGroupsOnComponent(componentId, groupsToUpdate)); + + } + +} + diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperation.java index d3d78333a9..656dd2e6e3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperation.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperation.java @@ -22,6 +22,7 @@ package org.openecomp.sdc.be.components.impl.instance; import org.openecomp.sdc.be.components.impl.group.GroupMembersUpdater; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; @@ -73,7 +74,7 @@ public class GroupMembersUpdateOperation implements OnComponentInstanceChangeOpe private ActionStatus updateGroups(Component container, List<GroupDefinition> groupsToUpdate) { log.debug("#updateGroups - updating {} groups for container {}", groupsToUpdate.size(), container.getUniqueId()); - return groupsOperation.updateGroups(container, groupsToUpdate, false) + return groupsOperation.updateGroups(container, groupsToUpdate, PromoteVersionEnum.MINOR) .either(groupsUpdated -> ActionStatus.OK, err -> componentsUtils.convertFromStorageResponse(err, container.getComponentType())); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/LockingTransactional.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/LockingTransactional.java index f75f0b7022..44e49eb039 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/LockingTransactional.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/LockingTransactional.java @@ -22,7 +22,11 @@ package org.openecomp.sdc.be.components.impl.lock; import org.springframework.transaction.annotation.Transactional; -import java.lang.annotation.*; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdater.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdater.java index 74b39f9f29..adf927178f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdater.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdater.java @@ -22,7 +22,9 @@ package org.openecomp.sdc.be.components.impl.policy; import org.apache.commons.collections.MapUtils; import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; +import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum; import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.utils.GroupUtils; import org.springframework.stereotype.Component; import java.util.List; @@ -39,7 +41,7 @@ import static org.apache.commons.collections.CollectionUtils.isEmpty; public class PolicyTargetsUpdater { public void removeTarget(List<PolicyDefinition> policies, String targetId, PolicyTargetType targetType) { - policies.forEach(policy -> removePolicyTarget(policy, targetId, targetType)); + policies.forEach(policy ->removePolicyTarget(policy, targetId, targetType)); } public void replaceTarget(List<PolicyDefinition> policies, String oldTargetId, String newTargetId, PolicyTargetType targetType) { @@ -52,6 +54,7 @@ public class PolicyTargetsUpdater { return; } policyTargets.replaceAll(prevInstanceIdByNewInstanceId(oldTargetId, newTargetId)); + policyDefinition.setVersion(GroupUtils.updateVersion(PromoteVersionEnum.MINOR, policyDefinition.getVersion())); } private void removePolicyTarget(PolicyDefinition policy, String targetId, PolicyTargetType targetType) { @@ -59,7 +62,9 @@ public class PolicyTargetsUpdater { if (isEmpty(policyTargets)) { return; } + policyTargets.remove(targetId); + policy.setVersion(GroupUtils.updateVersion(PromoteVersionEnum.MINOR, policy.getVersion())); } private List<String> getTargetsList(PolicyDefinition policyDefinition, PolicyTargetType targetType) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyVersionUpdater.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyVersionUpdater.java new file mode 100644 index 0000000000..ef2f8cbad9 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyVersionUpdater.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl.policy; + + +import org.openecomp.sdc.be.components.impl.version.OnChangeVersionCommand; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.model.utils.GroupUtils; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import java.util.List; +import java.util.function.Consumer; + +import static org.apache.commons.collections.CollectionUtils.isEmpty; + + +/** + * A Helper class which handles altering the version of a group + */ +@org.springframework.stereotype.Component +public class PolicyVersionUpdater implements OnChangeVersionCommand { + + private static final Logger log = Logger.getLogger(PolicyVersionUpdater.class); + private final ToscaOperationFacade toscaOperationFacade; + private final ComponentsUtils componentsUtils; + + + public PolicyVersionUpdater(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils) { + this.toscaOperationFacade = toscaOperationFacade; + this.componentsUtils = componentsUtils; + + } + + + @Override + public ActionStatus onChangeVersion(Component container) { + log.debug("#onChangeVersion - replacing all group members for component instance"); + Consumer<List<PolicyDefinition>> replaceGroupMemberTask = (policies) -> increaseVesion(policies); + return updatePoliciesVersion(container, replaceGroupMemberTask); + } + + public void increaseVesion(List<PolicyDefinition> policies) { + policies.forEach(policy -> increaseMajorVersion(policy)); + } + + + private void increaseMajorVersion(PolicyDefinition policy) { + String version = policy.getVersion(); + + String newVersion = GroupUtils.updateVersion(PromoteVersionEnum.MAJOR, policy.getVersion()); + + if(!version.equals(newVersion) ){ + String groupUUID = UniqueIdBuilder.generateUUID(); + policy.setPolicyUUID(groupUUID); + policy.setVersion(String.valueOf(newVersion)); + } + + } + + + private ActionStatus updatePoliciesVersion(Component container, Consumer<List<PolicyDefinition>> updatePoliciesVersion) { + List<PolicyDefinition> policies = container.resolvePoliciesList(); + if (isEmpty(policies)) { + return ActionStatus.OK; + } + updatePoliciesVersion.accept(policies); + return updatePolicies(container, policies); + } + + + private ActionStatus updatePolicies(Component policiesContainer, List<PolicyDefinition> policiesToUpdate) { + log.debug("#updatePolicies - updating {} policies for container {}", policiesToUpdate.size(), policiesContainer.getUniqueId()); + StorageOperationStatus updatePolicyResult = toscaOperationFacade.updatePoliciesOfComponent(policiesContainer.getUniqueId(), policiesToUpdate); + return componentsUtils.convertFromStorageResponse(updatePolicyResult, policiesContainer.getComponentType()); + } + +} + + diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CINodeFilterUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CINodeFilterUtils.java index 73ec3352b3..36c1e585d8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CINodeFilterUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CINodeFilterUtils.java @@ -16,9 +16,6 @@ package org.openecomp.sdc.be.components.impl.utils; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; import org.openecomp.sdc.be.datatypes.elements.RequirementNodeFilterCapabilityDataDefinition; @@ -28,6 +25,10 @@ import org.openecomp.sdc.be.model.UploadNodeFilterInfo; import org.openecomp.sdc.be.model.UploadNodeFilterPropertyInfo; import org.openecomp.sdc.common.log.wrappers.Logger; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + public class CINodeFilterUtils { Logger log = Logger.getLogger(CINodeFilterUtils.class); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/DirectivesUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/DirectivesUtils.java index b19f0592c1..900e961359 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/DirectivesUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/DirectivesUtils.java @@ -17,11 +17,12 @@ package org.openecomp.sdc.be.components.impl.utils; import com.google.common.collect.Sets; -import java.util.List; -import java.util.Optional; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; +import java.util.List; +import java.util.Optional; + public class DirectivesUtils { public static final String SUBSTITUTABLE = "substitutable"; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ExceptionUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ExceptionUtils.java index e51caabd00..ec4192c966 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ExceptionUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ExceptionUtils.java @@ -24,8 +24,8 @@ package org.openecomp.sdc.be.components.impl.utils; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/OnChangeVersionCommand.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/OnChangeVersionCommand.java new file mode 100644 index 0000000000..de115b5099 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/OnChangeVersionCommand.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl.version; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Component; + + +@FunctionalInterface +public interface OnChangeVersionCommand { + + /** + * A side effect operation to execute when a component instance version was changed from {@code prevVersion} to {@code newVersion} + * @param container the container which contains the instance which is version was changed + * @param prevVersion the previous version of the component instance. + * @param newVersion the new version of the component instance. + * @return the status of the operation + */ + ActionStatus onChangeVersion(Component container); + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/VesionUpdateHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/VesionUpdateHandler.java new file mode 100644 index 0000000000..13086c7884 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/VesionUpdateHandler.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl.version; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import java.util.Iterator; +import java.util.List; +import java.util.function.Function; + + + + +@org.springframework.stereotype.Component +public class VesionUpdateHandler { + + private static final Logger log = Logger.getLogger(VesionUpdateHandler.class); + + private final List<OnChangeVersionCommand> onChangeVersionOperations; + + public VesionUpdateHandler( List<OnChangeVersionCommand> onChangeVersionOperations) { + + this.onChangeVersionOperations = onChangeVersionOperations; + } + + + public ActionStatus doPostChangeVersionCommand(Component container) { + log.debug("#doPostChangeVersionOperations - starting post change version operations for component {}. from instance {} to instance {}", container.getUniqueId()); + Function<OnChangeVersionCommand, ActionStatus> vesionChangeTaskRunner = operation -> operation.onChangeVersion(container); + return doOnChangeVesionOperations(vesionChangeTaskRunner); + } + + private ActionStatus doOnChangeVesionOperations(Function<OnChangeVersionCommand, ActionStatus> vesionChangeTaskRunner) { + ActionStatus onVesionChangeResult = ActionStatus.OK; + Iterator<OnChangeVersionCommand> onChangeVesionIter = onChangeVersionOperations.iterator(); + while(onChangeVesionIter.hasNext() && onVesionChangeResult == ActionStatus.OK) { + onVesionChangeResult = vesionChangeTaskRunner.apply(onChangeVesionIter.next()); + } + return onVesionChangeResult; + } + + + + + +} |