summaryrefslogtreecommitdiffstats
path: root/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java
diff options
context:
space:
mode:
Diffstat (limited to 'catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java')
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java3851
1 files changed, 1561 insertions, 2290 deletions
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;
}
+
}
+