summaryrefslogtreecommitdiffstats
path: root/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl
diff options
context:
space:
mode:
Diffstat (limited to 'catalog-be/src/main/java/org/openecomp/sdc/be/components/impl')
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AbstractTemplateBusinessLogic.java91
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ActivationRequestInformation.java6
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java227
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AnnotationBusinessLogic.java33
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogic.java116
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java40
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java2280
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java202
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java185
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CADIHealthCheck.java27
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilitiesBusinessLogic.java378
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java41
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java68
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java117
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java258
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java517
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogicProvider.java10
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java1548
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInterfaceOperationBusinessLogic.java95
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentLocker.java10
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentNodeFilterBusinessLogic.java225
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentSubstitutionFilterBusinessLogic.java126
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java263
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java47
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java176
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeBusinessLogic.java42
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java96
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypesService.java15
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java66
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java539
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java54
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GenericArtifactBrowserBusinessLogic.java35
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java616
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicNew.java120
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java22
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java86
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckInformer.java5
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java6
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java362
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java427
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceDefinitionHandler.java90
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java39
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java448
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/NodeFilterUploadCreator.java23
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OnDeleteEntityOperation.java9
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OutputsBusinessLogic.java80
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java313
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java26
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java71
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java245
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java286
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeBusinessLogic.java25
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeImportManager.java65
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementBusinessLogic.java359
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java10
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java10359
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java393
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java7
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java1245
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogic.java1336
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportManager.java117
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogic.java1025
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/SoftwareInformationBusinessLogic.java57
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/TogglingBusinessLogic.java18
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafPermission.java25
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafRoles.java21
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/PermissionAllowed.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/RoleAuthorizationHandler.java16
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/ArtifactOperationInfo.java4
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/ArtifactTypeToPayloadTypeSelector.java22
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/PayloadTypeEnum.java45
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/BusinessLogicException.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByActionStatusComponentException.java9
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByResponseFormatComponentException.java7
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java16
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/SdcResourceNotFoundException.java16
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java41
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupMembersUpdater.java18
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupVersionUpdater.java90
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/ComponentInstanceChangeOperationOrchestrator.java27
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperation.java24
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnChangeVersionOperation.java12
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnComponentInstanceChangeOperation.java6
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/PolicyTargetsUpdateOperation.java13
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/ComponentLockAspect.java10
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/LockingTransactional.java8
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/model/ToscaTypeImportData.java8
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandler.java24
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdater.java26
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyVersionUpdater.java32
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CINodeFilterUtils.java40
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CapabilityTypeImportUtils.java22
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ComponentUtils.java53
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CreateServiceFromYamlParameter.java6
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/DirectivesUtil.java6
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ExceptionUtils.java16
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtils.java55
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/validation/PMDictionaryValidator.java13
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/OnChangeVersionCommand.java10
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/VesionUpdateHandler.java34
100 files changed, 11471 insertions, 15531 deletions
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AbstractTemplateBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AbstractTemplateBusinessLogic.java
index 9206dcb52e..2fbcabe99a 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AbstractTemplateBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AbstractTemplateBusinessLogic.java
@@ -16,53 +16,55 @@
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.validation.ServiceDistributionValidation;
import org.openecomp.sdc.be.externalapi.servlet.representation.AbstractResourceInfo;
import org.openecomp.sdc.be.externalapi.servlet.representation.AbstractTemplateInfo;
-import org.openecomp.sdc.be.model.*;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
-import org.openecomp.sdc.be.model.operations.api.*;
+import org.openecomp.sdc.be.model.operations.api.IElementOperation;
+import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
+import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
+import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
@Getter
@Setter
@org.springframework.stereotype.Component("abstractTemplateBusinessLogic")
public class AbstractTemplateBusinessLogic extends BaseBusinessLogic {
private static final String INITIAL_VERSION = "0.1";
-
private static final Logger log = Logger.getLogger(AbstractTemplateBusinessLogic.class);
-
- @Autowired
- ServiceDistributionValidation serviceDistributionValidation;
-
@Autowired
protected ServiceImportManager serviceImportManager;
-
@Autowired
protected ServiceBusinessLogic serviceBusinessLogic;
+ @Autowired
+ ServiceDistributionValidation serviceDistributionValidation;
@Autowired
- public AbstractTemplateBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation,
- InterfaceOperation interfaceOperation,
+ public AbstractTemplateBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+ IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
- interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+ artifactToscaOperation);
}
public Either<AbstractTemplateInfo, ResponseFormat> getServiceAbstractStatus(List<? extends Component> componentList) {
@@ -70,48 +72,45 @@ public class AbstractTemplateBusinessLogic extends BaseBusinessLogic {
if (componentList == null || componentList.isEmpty()) {
return Either.left(abstractTemplateInfo);
}
-
for (Component curr : componentList) {
Service service = (Service) curr;
List<ComponentInstance> componentInstances = service.getComponentInstances();
List<RequirementCapabilityRelDef> componentInstancesRelations = service.getComponentInstancesRelations();
abstractTemplateInfo.setServiceUniqueId(service.getUniqueId());
String serviceUniqueId = abstractTemplateInfo.getServiceUniqueId();
- Either<Boolean, ResponseFormat> isAbstractResourceData = getEveryServiceAbstractStatus(componentInstances, abstractTemplateInfo, componentInstancesRelations, serviceUniqueId);
+ Either<Boolean, ResponseFormat> isAbstractResourceData = getEveryServiceAbstractStatus(componentInstances, abstractTemplateInfo,
+ componentInstancesRelations, serviceUniqueId);
if (isAbstractResourceData.isRight()) {
return Either.right(isAbstractResourceData.right().value());
}
}
-
return Either.left(abstractTemplateInfo);
}
- private Either<Boolean, ResponseFormat> getEveryServiceAbstractStatus(List<ComponentInstance> componentInstances, AbstractTemplateInfo abstractTemplateInfo,
- List<RequirementCapabilityRelDef> componentInstancesRelations, String serviceUniqueId) {
+ private Either<Boolean, ResponseFormat> getEveryServiceAbstractStatus(List<ComponentInstance> componentInstances,
+ AbstractTemplateInfo abstractTemplateInfo,
+ List<RequirementCapabilityRelDef> componentInstancesRelations,
+ String serviceUniqueId) {
Map<String, ImmutablePair<String, String>> uuidDuplicatesMap = new HashMap<>();
List<AbstractResourceInfo> abstractResourceInfoList = new ArrayList<>();
Boolean isContainAbstractResource = false;
-
for (ComponentInstance componentInstance : componentInstances) {
String componentUid = componentInstance.getComponentUid();
String invariantUUID, resourceUUID;
if (!uuidDuplicatesMap.containsKey(componentUid)) {
- Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade
- .getToscaElement(componentInstance.getComponentUid());
+ Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(componentInstance.getComponentUid());
if (eitherResource.isRight()) {
- log.debug("getEveryServiceAbstractStatus: Failed getting resource with UUid: {}",
- componentInstance.getComponentUid());
+ log.debug("getEveryServiceAbstractStatus: Failed getting resource with UUid: {}", componentInstance.getComponentUid());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(eitherResource.right().value());
return Either.right(responseFormat);
} else {
final Resource resource = eitherResource.left().value();
invariantUUID = resource.getInvariantUUID();
resourceUUID = resource.getUUID();
- ImmutablePair<String, String> uuidInvariantUUIDPair = new ImmutablePair<>(resourceUUID,
- invariantUUID);
+ ImmutablePair<String, String> uuidInvariantUUIDPair = new ImmutablePair<>(resourceUUID, invariantUUID);
uuidDuplicatesMap.put(componentUid, uuidInvariantUUIDPair);
-
- isContainAbstractResource = getResourceAbstractStatus(resource, isContainAbstractResource, componentInstancesRelations, serviceUniqueId,abstractResourceInfoList);
+ isContainAbstractResource = getResourceAbstractStatus(resource, isContainAbstractResource, componentInstancesRelations,
+ serviceUniqueId, abstractResourceInfoList);
}
}
}
@@ -120,40 +119,41 @@ public class AbstractTemplateBusinessLogic extends BaseBusinessLogic {
return Either.left(isContainAbstractResource);
}
- private boolean getResourceAbstractStatus(Resource resource,Boolean isContainAbstractResource, List<RequirementCapabilityRelDef> componentInstancesRelations,
- String serviceUniqueId,List<AbstractResourceInfo> abstractResourceInfoList) {
+ private boolean getResourceAbstractStatus(Resource resource, Boolean isContainAbstractResource,
+ List<RequirementCapabilityRelDef> componentInstancesRelations, String serviceUniqueId,
+ List<AbstractResourceInfo> abstractResourceInfoList) {
boolean isAbstract = getIsAbstract(resource.getCategories());
log.debug("before if isAbstract,get resource:{}", resource);
if (isAbstract) {
- log.debug("getResourceAbstractStatus: resource {} with id {} ,NormalizedName:{},isAbstract{} is abstract resource",
- resource.getName(), resource.getUUID(), resource.getNormalizedName(), true);
+ log.debug("getResourceAbstractStatus: resource {} with id {} ,NormalizedName:{},isAbstract{} is abstract resource", resource.getName(),
+ resource.getUUID(), resource.getNormalizedName(), true);
isContainAbstractResource = true;
AbstractResourceInfo abstractResourceInfo = getAbstractResourceInfo(resource, componentInstancesRelations, serviceUniqueId);
abstractResourceInfoList.add(abstractResourceInfo);
} else {
- log.debug("getResourceAbstractStatus:resource {} ,with id {} isAbstract{} is missing the isAbstract parameter",
- resource.getName(), resource.getUUID(),false);
+ log.debug("getResourceAbstractStatus:resource {} ,with id {} isAbstract{} is missing the isAbstract parameter", resource.getName(),
+ resource.getUUID(), false);
}
return isContainAbstractResource;
}
- private AbstractResourceInfo getAbstractResourceInfo(Resource resource,List<RequirementCapabilityRelDef> componentInstancesRelations,String serviceUniqueId){
+ private AbstractResourceInfo getAbstractResourceInfo(Resource resource, List<RequirementCapabilityRelDef> componentInstancesRelations,
+ String serviceUniqueId) {
AbstractResourceInfo abstractResourceInfo = new AbstractResourceInfo();
abstractResourceInfo.setAbstractResourceUUid(resource.getUUID());
abstractResourceInfo.setAbstractResourceName(resource.getName());
abstractResourceInfo.setAbstractResourceUniqueId(resource.getUniqueId());
String uniqueId = serviceUniqueId + "." + resource.getUniqueId() + "." + resource.getNormalizedName();
-
List<RequirementCapabilityRelDef> resourceComponentInstancesRelations = new ArrayList<>();
- log.debug("get serviceUniqueId:{},get UniqueId:{},get NormalizedName:{}",
- serviceUniqueId, resource.getUniqueId(), resource.getNormalizedName());
+ log.debug("get serviceUniqueId:{},get UniqueId:{},get NormalizedName:{}", serviceUniqueId, resource.getUniqueId(),
+ resource.getNormalizedName());
log.debug("get is Abstract,componentInstancesRelations:{}", componentInstancesRelations);
for (RequirementCapabilityRelDef componentInstancesRelation : componentInstancesRelations) {
log.debug("for componentInstancesRelation,get componentInstancesRelation:{}", componentInstancesRelation);
String toNode = componentInstancesRelation.getToNode();
String fromNode = componentInstancesRelation.getFromNode();
- log.debug("for componentInstancesRelation,get fromNode:{},uniqueId:{},ToNode:{},Relationships:{}",
- fromNode,uniqueId,toNode,componentInstancesRelation.getRelationships());
+ log.debug("for componentInstancesRelation,get fromNode:{},uniqueId:{},ToNode:{},Relationships:{}", fromNode, uniqueId, toNode,
+ componentInstancesRelation.getRelationships());
if (toNode.toUpperCase().contains(uniqueId.toUpperCase()) || fromNode.toUpperCase().contains(uniqueId.toUpperCase())) {
RequirementCapabilityRelDef resourceComponentInstancesRelation = new RequirementCapabilityRelDef();
log.debug("fromNode contains name,get componentInstancesRelation:{}", componentInstancesRelation);
@@ -173,8 +173,7 @@ public class AbstractTemplateBusinessLogic extends BaseBusinessLogic {
boolean anAbstract = false;
if (categories != null && !categories.isEmpty()) {
CategoryDefinition categoryDef = categories.get(0);
- if (categoryDef != null && categoryDef.getName() != null && categoryDef.getName()
- .equals(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME)) {
+ if (categoryDef != null && categoryDef.getName() != null && categoryDef.getName().equals(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME)) {
SubCategoryDefinition subCategoryDef = categoryDef.getSubcategories().get(0);
if (subCategoryDef != null && subCategoryDef.getName().equals(ImportUtils.Constants.ABSTRACT_SUBCATEGORY)) {
anAbstract = true;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ActivationRequestInformation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ActivationRequestInformation.java
index 70ec37ce48..87ef16f163 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ActivationRequestInformation.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ActivationRequestInformation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import org.openecomp.sdc.be.model.Service;
@@ -26,6 +25,7 @@ import org.openecomp.sdc.be.model.Service;
* Created by chaya on 10/22/2017.
*/
public class ActivationRequestInformation {
+
private Service serviceToActivate;
private String workloadContext;
private String tenant;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java
index ee6878e7d7..c3efa610fc 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,10 +17,10 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
+import java.util.List;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -48,57 +48,47 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import java.util.List;
-
@Component("additionalInformationBusinessLogic")
public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
private static final String CREATE_ADDITIONAL_INFORMATION = "CreateAdditionalInformation";
-
private static final String UPDATE_ADDITIONAL_INFORMATION = "UpdateAdditionalInformation";
-
private static final String DELETE_ADDITIONAL_INFORMATION = "DeleteAdditionalInformation";
-
private static final String GET_ADDITIONAL_INFORMATION = "GetAdditionalInformation";
-
private static final Logger log = Logger.getLogger(AdditionalInformationBusinessLogic.class.getName());
private static final String FAILED_TO_LOCK_COMPONENT_ERROR = "Failed to lock component {} error - {}";
-
private final AdditionalInformationOperation additionalInformationOperation;
@Autowired
- public AdditionalInformationBusinessLogic(IElementOperation elementDao,
- IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation,
- IGroupTypeOperation groupTypeOperation,
- InterfaceOperation interfaceOperation,
- InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
- AdditionalInformationOperation additionalInformationOperation,
- ArtifactsOperations artifactToscaOperation) {
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
- interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+ public AdditionalInformationBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
+ IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation,
+ InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+ AdditionalInformationOperation additionalInformationOperation,
+ ArtifactsOperations artifactToscaOperation) {
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+ artifactToscaOperation);
this.additionalInformationOperation = additionalInformationOperation;
}
/**
* Create new additional information on resource/service on graph
+ *
* @param nodeType
* @param resourceId
* @param additionalInfoParameterInfo
* @param userId
* @return Either<AdditionalInfoParameterInfo, ResponseFormat>
*/
- public Either<AdditionalInfoParameterInfo, ResponseFormat> createAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String userId) {
-
+ public Either<AdditionalInfoParameterInfo, ResponseFormat> createAdditionalInformation(NodeTypeEnum nodeType, String resourceId,
+ AdditionalInfoParameterInfo additionalInfoParameterInfo,
+ String userId) {
validateUserExists(userId);
Either<AdditionalInfoParameterInfo, ResponseFormat> result = null;
-
ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId);
if (responseFormat != null) {
result = Either.right(responseFormat);
return result;
}
-
// lock component
StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType);
if (lockResult != StorageOperationStatus.OK) {
@@ -113,45 +103,40 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
result = Either.right(responseFormat);
return result;
}
-
// validate label
responseFormat = validateAndConvertKey(additionalInfoParameterInfo, CREATE_ADDITIONAL_INFORMATION);
if (responseFormat != null) {
result = Either.right(responseFormat);
return result;
}
-
// validate value
responseFormat = validateAndConvertValue(additionalInfoParameterInfo, CREATE_ADDITIONAL_INFORMATION);
if (responseFormat != null) {
result = Either.right(responseFormat);
return result;
}
-
- Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation.createAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getKey(),
+ Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation
+ .createAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getKey(),
additionalInfoParameterInfo.getValue(), true);
-
if (addResult.isRight()) {
StorageOperationStatus status = addResult.right().value();
BeEcompErrorManager.getInstance().logBeSystemError(CREATE_ADDITIONAL_INFORMATION);
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
- result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.Label));
+ result = Either.right(componentsUtils
+ .getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.Label));
return result;
-
} else {
AdditionalInformationDefinition informationDefinition = addResult.left().value();
-
- AdditionalInfoParameterInfo createdAI = findAdditionInformationKey(informationDefinition.getParameters(), additionalInfoParameterInfo.getKey());
+ AdditionalInfoParameterInfo createdAI = findAdditionInformationKey(informationDefinition.getParameters(),
+ additionalInfoParameterInfo.getKey());
result = Either.left(createdAI);
return result;
}
-
} finally {
commitOrRollback(result);
// unlock component
graphLockOperation.unlockComponent(resourceId, nodeType);
}
-
}
/**
@@ -162,13 +147,12 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
*/
private ResponseFormat validateAndConvertValue(AdditionalInfoParameterInfo additionalInfoParameterInfo, String context) {
ResponseFormat result = null;
-
String value = additionalInfoParameterInfo.getValue();
log.debug("Going to validate additional information value {}", value);
-
Either<String, ResponseFormat> valueValidRes = validateValue(value);
if (valueValidRes.isRight()) {
- BeEcompErrorManager.getInstance().logBeInvalidValueError(context, additionalInfoParameterInfo.getValue(), "additional information value", "string");
+ BeEcompErrorManager.getInstance()
+ .logBeInvalidValueError(context, additionalInfoParameterInfo.getValue(), "additional information value", "string");
result = valueValidRes.right().value();
} else {
String newValue = valueValidRes.left().value();
@@ -187,21 +171,18 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
* @return
*/
private ResponseFormat validateAndConvertKey(AdditionalInfoParameterInfo additionalInfoParameterInfo, String context) {
-
String key = additionalInfoParameterInfo.getKey();
log.debug("Going to validate additional information key {}", key);
-
ResponseFormat result = null;
ResponseFormat responseFormat;
Either<String, ResponseFormat> validateKeyRes = validateAndNormalizeKey(key);
if (validateKeyRes.isRight()) {
responseFormat = validateKeyRes.right().value();
- BeEcompErrorManager.getInstance().logBeInvalidValueError(context, additionalInfoParameterInfo.getKey(), "additional information label", "string");
+ BeEcompErrorManager.getInstance()
+ .logBeInvalidValueError(context, additionalInfoParameterInfo.getKey(), "additional information label", "string");
result = responseFormat;
-
} else {
String convertedKey = validateKeyRes.left().value();
-
if (log.isTraceEnabled() && key != null && !key.equals(convertedKey)) {
log.trace("The additional information key {} was normalized to {}", key, convertedKey);
}
@@ -218,26 +199,29 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
* @param additionalInfoParameterInfo
* @return response format in case the maximal number has been reached.
*/
- private ResponseFormat validateMaxSizeNotReached(NodeTypeEnum nodeType, String componentId, AdditionalInfoParameterInfo additionalInfoParameterInfo) {
-
+ private ResponseFormat validateMaxSizeNotReached(NodeTypeEnum nodeType, String componentId,
+ AdditionalInfoParameterInfo additionalInfoParameterInfo) {
ResponseFormat result;
- Integer additionalInformationMaxNumberOfKeys = ConfigurationManager.getConfigurationManager().getConfiguration().getAdditionalInformationMaxNumberOfKeys();
-
- Either<Integer, StorageOperationStatus> checkRes = additionalInformationOperation.getNumberOfAdditionalInformationParameters(nodeType, componentId, true);
+ Integer additionalInformationMaxNumberOfKeys = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getAdditionalInformationMaxNumberOfKeys();
+ Either<Integer, StorageOperationStatus> checkRes = additionalInformationOperation
+ .getNumberOfAdditionalInformationParameters(nodeType, componentId, true);
if (checkRes.isRight()) {
StorageOperationStatus status = checkRes.right().value();
-
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
- result = componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None);
+ result = componentsUtils
+ .getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None);
return result;
}
Integer currentNumberOfProperties = checkRes.left().value();
if (currentNumberOfProperties >= additionalInformationMaxNumberOfKeys) {
- log.info("The current number of additional information properties is {}. The maximum allowed additional information properties is {}", currentNumberOfProperties, currentNumberOfProperties);
- result = componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None);
+ log.info("The current number of additional information properties is {}. The maximum allowed additional information properties is {}",
+ currentNumberOfProperties, currentNumberOfProperties);
+ result = componentsUtils
+ .getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED, additionalInfoParameterInfo, nodeType,
+ AdditionalInformationEnum.None);
return result;
}
-
return null;
}
@@ -248,24 +232,20 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
* @return
*/
private Either<String, ResponseFormat> validateValue(String value) {
-
boolean isNonEmptyString = ValidationUtils.validateStringNotEmpty(value);
if (!isNonEmptyString) {
return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED));
}
-
boolean valid = StringValidator.getInstance().isValid(value, null);
if (!valid) {
- return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS, new AdditionalInfoParameterInfo(null, value), null, AdditionalInformationEnum.Value));
+ return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS,
+ new AdditionalInfoParameterInfo(null, value), null, AdditionalInformationEnum.Value));
}
-
String converted = StringConvertor.getInstance().convert(value, null, null);
-
return Either.left(converted);
}
private AdditionalInfoParameterInfo findAdditionInformationKey(List<AdditionalInfoParameterInfo> parameters, String key) {
-
for (AdditionalInfoParameterInfo infoParameterInfo : parameters) {
if (infoParameterInfo.getKey().equals(key)) {
return infoParameterInfo;
@@ -276,27 +256,31 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
/**
* validate and normalize the key
+ *
* @param key
* @return Either<String, ResponseFormat>
*/
private Either<String, ResponseFormat> validateAndNormalizeKey(String key) {
-
AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo();
additionalInfoParameterInfo.setKey(key);
-
String normKey = ValidationUtils.normalizeAdditionalInformation(key);
boolean isNonEmptyString = ValidationUtils.validateStringNotEmpty(normKey);
if (!isNonEmptyString) {
- return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED, null, null, AdditionalInformationEnum.Label));
+ return Either.right(componentsUtils
+ .getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED, null, null,
+ AdditionalInformationEnum.Label));
}
boolean isValidString = ValidationUtils.validateAdditionalInformationKeyName(normKey);
if (!isValidString) {
if (!ValidationUtils.validateLength(normKey, ValidationUtils.ADDITIONAL_INFORMATION_KEY_MAX_LENGTH)) {
- return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EXCEEDS_LIMIT, additionalInfoParameterInfo, null, AdditionalInformationEnum.Label));
+ return Either.right(componentsUtils
+ .getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EXCEEDS_LIMIT, additionalInfoParameterInfo, null,
+ AdditionalInformationEnum.Label));
}
- return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS, additionalInfoParameterInfo, null, AdditionalInformationEnum.Label));
+ return Either.right(componentsUtils
+ .getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS, additionalInfoParameterInfo,
+ null, AdditionalInformationEnum.Label));
}
-
return Either.left(normKey);
}
@@ -309,11 +293,11 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
* @param userId
* @return
*/
- public Either<AdditionalInfoParameterInfo, ResponseFormat> updateAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String userId) {
-
+ public Either<AdditionalInfoParameterInfo, ResponseFormat> updateAdditionalInformation(NodeTypeEnum nodeType, String resourceId,
+ AdditionalInfoParameterInfo additionalInfoParameterInfo,
+ String userId) {
validateUserExists(userId);
Either<AdditionalInfoParameterInfo, ResponseFormat> result = null;
-
ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId);
if (responseFormat != null) {
result = Either.right(responseFormat);
@@ -328,42 +312,39 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
return result;
}
try {
-
// validate input
responseFormat = validateAndConvertKey(additionalInfoParameterInfo, UPDATE_ADDITIONAL_INFORMATION);
if (responseFormat != null) {
result = Either.right(responseFormat);
return result;
}
-
responseFormat = validateAndConvertValue(additionalInfoParameterInfo, UPDATE_ADDITIONAL_INFORMATION);
if (responseFormat != null) {
result = Either.right(responseFormat);
return result;
}
-
- Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation.updateAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(),
+ Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation
+ .updateAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(),
additionalInfoParameterInfo.getKey(), additionalInfoParameterInfo.getValue(), true);
-
if (addResult.isRight()) {
StorageOperationStatus status = addResult.right().value();
BeEcompErrorManager.getInstance().logBeSystemError(UPDATE_ADDITIONAL_INFORMATION);
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
- result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
+ result = Either.right(componentsUtils
+ .getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
return result;
} else {
AdditionalInformationDefinition informationDefinition = addResult.left().value();
- AdditionalInfoParameterInfo parameterInfo = findAdditionInformationKey(informationDefinition.getParameters(), additionalInfoParameterInfo.getKey());
+ AdditionalInfoParameterInfo parameterInfo = findAdditionInformationKey(informationDefinition.getParameters(),
+ additionalInfoParameterInfo.getKey());
result = Either.left(parameterInfo);
return result;
}
-
} finally {
commitOrRollback(result);
// unlock component
graphLockOperation.unlockComponent(resourceId, nodeType);
}
-
}
/**
@@ -375,11 +356,11 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
* @param userId
* @return
*/
- public Either<AdditionalInfoParameterInfo, ResponseFormat> deleteAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String userId) {
-
+ public Either<AdditionalInfoParameterInfo, ResponseFormat> deleteAdditionalInformation(NodeTypeEnum nodeType, String resourceId,
+ AdditionalInfoParameterInfo additionalInfoParameterInfo,
+ String userId) {
validateUserExists(userId);
Either<AdditionalInfoParameterInfo, ResponseFormat> result = null;
-
ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId);
if (responseFormat != null) {
return Either.right(responseFormat);
@@ -392,41 +373,38 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
return result;
}
-
try {
-
- Either<AdditionalInfoParameterInfo, StorageOperationStatus> findIdRes = additionalInformationOperation.getAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true);
+ Either<AdditionalInfoParameterInfo, StorageOperationStatus> findIdRes = additionalInformationOperation
+ .getAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true);
if (findIdRes.isRight()) {
StorageOperationStatus status = findIdRes.right().value();
if (status != StorageOperationStatus.NOT_FOUND) {
BeEcompErrorManager.getInstance().logBeSystemError(GET_ADDITIONAL_INFORMATION);
}
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
- result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
+ result = Either.right(componentsUtils
+ .getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
return result;
}
-
AdditionalInfoParameterInfo foundAdditionalInfo = findIdRes.left().value();
-
- Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation.deleteAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true);
-
+ Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation
+ .deleteAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true);
if (addResult.isRight()) {
StorageOperationStatus status = addResult.right().value();
BeEcompErrorManager.getInstance().logBeDaoSystemError(DELETE_ADDITIONAL_INFORMATION);
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
- result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
+ result = Either.right(componentsUtils
+ .getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
return result;
} else {
result = Either.left(foundAdditionalInfo);
return result;
}
-
} finally {
commitOrRollback(result);
// unlock component
graphLockOperation.unlockComponent(resourceId, nodeType);
}
-
}
/**
@@ -436,31 +414,26 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
* @param userId
* @return
*/
- public Either<AdditionalInfoParameterInfo, ResponseFormat> getAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String userId) {
-
+ public Either<AdditionalInfoParameterInfo, ResponseFormat> getAdditionalInformation(NodeTypeEnum nodeType, String resourceId,
+ AdditionalInfoParameterInfo additionalInfoParameterInfo,
+ String userId) {
validateUserExists(userId);
Either<AdditionalInfoParameterInfo, ResponseFormat> result = null;
-
try {
-
- Either<AdditionalInfoParameterInfo, StorageOperationStatus> findIdRes = additionalInformationOperation.getAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true);
-
+ Either<AdditionalInfoParameterInfo, StorageOperationStatus> findIdRes = additionalInformationOperation
+ .getAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true);
if (findIdRes.isRight()) {
StorageOperationStatus status = findIdRes.right().value();
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
- result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
+ result = Either.right(componentsUtils
+ .getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
}
-
AdditionalInfoParameterInfo foundAdditionalInfo = findIdRes.left().value();
-
result = Either.left(foundAdditionalInfo);
-
return result;
-
} finally {
commitOrRollback(result);
}
-
}
/**
@@ -471,15 +444,13 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
* @param userId
* @return
*/
- public Either<AdditionalInformationDefinition, ResponseFormat> getAllAdditionalInformation(NodeTypeEnum nodeType, String resourceId, String userId) {
-
+ public Either<AdditionalInformationDefinition, ResponseFormat> getAllAdditionalInformation(NodeTypeEnum nodeType, String resourceId,
+ String userId) {
validateUserExists(userId);
-
Either<AdditionalInformationDefinition, ResponseFormat> result = null;
-
try {
-
- Either<AdditionalInformationDefinition, JanusGraphOperationStatus> findIdRes = additionalInformationOperation.getAllAdditionalInformationParameters(nodeType, resourceId, false);
+ Either<AdditionalInformationDefinition, JanusGraphOperationStatus> findIdRes = additionalInformationOperation
+ .getAllAdditionalInformationParameters(nodeType, resourceId, false);
if (findIdRes.isRight()) {
StorageOperationStatus status = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(findIdRes.right().value());
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
@@ -488,39 +459,33 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
AdditionalInformationDefinition informationDefinition = findIdRes.left().value();
result = Either.left(informationDefinition);
}
-
return result;
-
} finally {
commitOrRollback(result);
}
-
}
private ResponseFormat verifyCanWorkOnComponent(NodeTypeEnum nodeType, String resourceId, String userId) {
-
switch (nodeType) {
- case Resource:
+ case Resource:
+ // verify that resource is checked-out and the user is the last
- // verify that resource is checked-out and the user is the last
- // updater
- if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) {
- return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- }
- break;
- case Service:
+ // updater
+ if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) {
+ return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+ }
+ break;
+ case Service:
+ // verify that resource is checked-out and the user is the last
- // verify that resource is checked-out and the user is the last
- // updater
- if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) {
- return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- }
- break;
- default:
- return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT, nodeType.getName());
+ // updater
+ if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) {
+ return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+ }
+ break;
+ default:
+ return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT, nodeType.getName());
}
-
return null;
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AnnotationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AnnotationBusinessLogic.java
index b0af789f28..f8d487169a 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AnnotationBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AnnotationBusinessLogic.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,9 +17,15 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
+import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import org.openecomp.sdc.be.components.validation.AnnotationValidator;
import org.openecomp.sdc.be.dao.utils.MapUtil;
import org.openecomp.sdc.be.datatypes.elements.Annotation;
@@ -30,29 +36,19 @@ import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.operations.impl.AnnotationTypeOperations;
import org.springframework.stereotype.Component;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
-
@Component
public class AnnotationBusinessLogic {
private final AnnotationTypeOperations annotationTypeOperations;
-
private final AnnotationValidator annotationValidator;
- public AnnotationBusinessLogic(AnnotationTypeOperations annotationTypeOperations,
- AnnotationValidator annotationValidator){
+ public AnnotationBusinessLogic(AnnotationTypeOperations annotationTypeOperations, AnnotationValidator annotationValidator) {
this.annotationTypeOperations = annotationTypeOperations;
this.annotationValidator = annotationValidator;
}
public void validateAndMergeAnnotationsAndAssignToInput(Map<String, InputDefinition> inputs) {
- if (!inputs.isEmpty()){
+ if (!inputs.isEmpty()) {
for (InputDefinition input : inputs.values()) {
List<Annotation> inputAnnotationList = input.getAnnotations();
if (isNotEmpty(inputAnnotationList)) {
@@ -72,11 +68,13 @@ public class AnnotationBusinessLogic {
private void validateMergeAndSetAnnoProps(Annotation annotation, AnnotationTypeDefinition dbAnnotationTypeDefinition) {
annotationValidator.validateAnnotationsProperties(annotation, dbAnnotationTypeDefinition);
- List<PropertyDataDefinition> mergedPropertiesList = mergePropsOfAnnoDataTypeWithParsedAnnoProps(annotation.getProperties(), dbAnnotationTypeDefinition.getProperties());
+ List<PropertyDataDefinition> mergedPropertiesList = mergePropsOfAnnoDataTypeWithParsedAnnoProps(annotation.getProperties(),
+ dbAnnotationTypeDefinition.getProperties());
annotation.setProperties(mergedPropertiesList);
}
- private List<PropertyDataDefinition> mergePropsOfAnnoDataTypeWithParsedAnnoProps(List<PropertyDataDefinition> annoProperties, List<PropertyDefinition> typePropertiesList) {
+ private List<PropertyDataDefinition> mergePropsOfAnnoDataTypeWithParsedAnnoProps(List<PropertyDataDefinition> annoProperties,
+ List<PropertyDefinition> typePropertiesList) {
Set<PropertyDataDefinition> mergedPropertiesSet = new HashSet<>(typePropertiesList);
Map<String, PropertyDefinition> typePropsMap = MapUtil.toMap(typePropertiesList, PropertyDefinition::getName);
for (PropertyDataDefinition propertyDataDefinitionObject : annoProperties) {
@@ -88,5 +86,4 @@ public class AnnotationBusinessLogic {
}
return new ArrayList<>(mergedPropertiesSet);
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogic.java
index 15e9a77b15..34b01c7fd0 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogic.java
@@ -21,8 +21,16 @@
*/
package org.openecomp.sdc.be.components.impl;
+import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.wrapWithTryCatch;
+
import com.google.common.annotations.VisibleForTesting;
import fj.data.Either;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum;
import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
import org.openecomp.sdc.be.components.validation.AccessValidations;
@@ -44,108 +52,88 @@ import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.wrapWithTryCatch;
-
-
@org.springframework.stereotype.Component
public class ArchiveBusinessLogic {
private static final Logger log = Logger.getLogger(ArchiveBusinessLogic.class.getName());
-
private final JanusGraphDao janusGraphDao;
private final AccessValidations accessValidations;
private final ArchiveOperation archiveOperation;
private final ToscaOperationFacade toscaOperationFacade;
private final ComponentsUtils componentUtils;
- private final CatalogOperation catalogOperations;
+ private final CatalogOperation catalogOperations;
- public ArchiveBusinessLogic(JanusGraphDao janusGraphDao, AccessValidations accessValidations, ArchiveOperation archiveOperation, ToscaOperationFacade tof, ComponentsUtils componentsUtils,
- CatalogOperation catalogOperations) {
+ public ArchiveBusinessLogic(JanusGraphDao janusGraphDao, AccessValidations accessValidations, ArchiveOperation archiveOperation,
+ ToscaOperationFacade tof, ComponentsUtils componentsUtils, CatalogOperation catalogOperations) {
this.janusGraphDao = janusGraphDao;
this.accessValidations = accessValidations;
this.archiveOperation = archiveOperation;
this.toscaOperationFacade = tof;
this.componentUtils = componentsUtils;
- this.catalogOperations = catalogOperations;
+ this.catalogOperations = catalogOperations;
}
public void archiveComponent(String containerComponentType, String userId, String componentId) {
User user = accessValidations.userIsAdminOrDesigner(userId, containerComponentType + "_ARCHIVE");
Either<List<String>, ActionStatus> result = this.archiveOperation.archiveComponent(componentId);
-
- if (result.isRight()){
+ if (result.isRight()) {
throw new ByActionStatusComponentException(result.right().value(), componentId);
}
this.auditAction(ArchiveOperation.Action.ARCHIVE, result.left().value(), user, containerComponentType);
- // Send Archive Notification To Facade
- wrapWithTryCatch(() -> sendNotificationToFacade(componentId, ChangeTypeEnum.ARCHIVE));
+ // Send Archive Notification To Facade
+ wrapWithTryCatch(() -> sendNotificationToFacade(componentId, ChangeTypeEnum.ARCHIVE));
}
public void restoreComponent(String containerComponentType, String userId, String componentId) {
User user = accessValidations.userIsAdminOrDesigner(userId, containerComponentType + "_RESTORE");
Either<List<String>, ActionStatus> result = this.archiveOperation.restoreComponent(componentId);
- if (result.isRight()){
+ if (result.isRight()) {
throw new ByActionStatusComponentException(result.right().value(), componentId);
}
this.auditAction(ArchiveOperation.Action.RESTORE, result.left().value(), user, containerComponentType);
- // Send Archive Notification To Facade
- wrapWithTryCatch(() -> sendNotificationToFacade(componentId, ChangeTypeEnum.RESTORE));
+ // Send Archive Notification To Facade
+ wrapWithTryCatch(() -> sendNotificationToFacade(componentId, ChangeTypeEnum.RESTORE));
}
- public List<String> onVspArchive(String userId, List<String> csarUuids){
+ public List<String> onVspArchive(String userId, List<String> csarUuids) {
return this.onVspArchiveOrRestore(userId, csarUuids, ArchiveOperation.Action.ARCHIVE);
}
- public List<String> onVspRestore(String userId, List<String> csarUuids){
+ public List<String> onVspRestore(String userId, List<String> csarUuids) {
return this.onVspArchiveOrRestore(userId, csarUuids, ArchiveOperation.Action.RESTORE);
}
private List<String> onVspArchiveOrRestore(String userId, List<String> csarUuids, ArchiveOperation.Action action) {
-
accessValidations.userIsAdminOrDesigner(userId, action.name() + "_VSP");
-
ActionStatus actionStatus;
List<String> failedCsarIDs = new LinkedList<>();
-
for (String csarUuid : csarUuids) {
try {
-
if (action == ArchiveOperation.Action.ARCHIVE) {
actionStatus = this.archiveOperation.onVspArchived(csarUuid);
} else {
actionStatus = this.archiveOperation.onVspRestored(csarUuid);
}
-
//If not found VFs with this CSAR ID we still want a success (nothing is actually done)
if (actionStatus == ActionStatus.RESOURCE_NOT_FOUND) {
actionStatus = ActionStatus.OK;
}
-
if (actionStatus != ActionStatus.OK) {
failedCsarIDs.add(csarUuid);
}
-
} catch (Exception e) {
log.error("Failed to handle notification: {} on VSP for csarUuid: {}", action.name(), csarUuid);
log.error("Exception Thrown:", e);
failedCsarIDs.add(csarUuid);
}
}
-
return failedCsarIDs;
}
public Map<String, List<CatalogComponent>> getArchiveComponents(String userId, List<OriginTypeEnum> excludeTypes) {
try {
-
- Either<List<CatalogComponent>, StorageOperationStatus> components = toscaOperationFacade.getCatalogOrArchiveComponents(false, excludeTypes);
+ Either<List<CatalogComponent>, StorageOperationStatus> components = toscaOperationFacade
+ .getCatalogOrArchiveComponents(false, excludeTypes);
if (components.isLeft()) {
List<CatalogComponent> comps = components.left().value();
return comps.stream().collect(Collectors.groupingBy(cmpt -> ComponentTypeEnum.findParamByType(cmpt.getComponentType())));
@@ -153,52 +141,54 @@ public class ArchiveBusinessLogic {
log.info("No components found");
return new HashMap();
}
- } catch (Exception e){
+ } catch (Exception e) {
log.error("Error fetching archived elements", e);
throw e;
- }
- finally {
+ } finally {
janusGraphDao.commit();
}
}
-
@VisibleForTesting
void auditAction(ArchiveOperation.Action action, List<String> affectedCompIds, User user, String containerComponentType) {
String comment = String.format("All versions of this component were %s", action == ArchiveOperation.Action.ARCHIVE ? "archived" : "restored");
HashSet<String> auditDoneUUIDs = new HashSet<>();
- for (String componentId : affectedCompIds){
+ for (String componentId : affectedCompIds) {
Either<Component, StorageOperationStatus> result = toscaOperationFacade.getToscaElement(componentId, new ComponentParametersView());
if (result.isRight()) {
- log.error(EcompLoggerErrorCode.DATA_ERROR, null, "GetToscaElement",
- result.right().value().name() + "for component with id {}", componentId);
+ log.error(EcompLoggerErrorCode.DATA_ERROR, null, "GetToscaElement", result.right().value().name() + "for component with id {}",
+ componentId);
continue;
}
if (auditDoneUUIDs.add(result.left().value().getUUID())) {
//a component with this UUID is not added to audit DB/log for current archive/restore operation yet - add to audit DB now
- AuditingActionEnum auditAction = action == ArchiveOperation.Action.ARCHIVE ? AuditingActionEnum.ARCHIVE_COMPONENT : AuditingActionEnum.RESTORE_COMPONENT; //The audit Action
- result.left().foreachDoEffect(
- c -> {
- // The archive/restore records have been retrieved from Cassandra using the separate queries.
- // Setting current version as null allows to avoid appearing same records in ActivityLog twice:
- // - first time as per current version query
- //- second type as per archive/restore query
- c.setVersion(null);
- componentUtils.auditComponentAdmin(componentUtils.getResponseFormat(ActionStatus.OK), user, c, auditAction, ComponentTypeEnum.findByParamName(containerComponentType), comment);
- });
+
+ AuditingActionEnum auditAction = action == ArchiveOperation.Action.ARCHIVE ? AuditingActionEnum.ARCHIVE_COMPONENT
+ : AuditingActionEnum.RESTORE_COMPONENT; //The audit Action
+ result.left().foreachDoEffect(c -> {
+ // The archive/restore records have been retrieved from Cassandra using the separate queries.
+
+ // Setting current version as null allows to avoid appearing same records in ActivityLog twice:
+
+ // - first time as per current version query
+
+ //- second type as per archive/restore query
+ c.setVersion(null);
+ componentUtils.auditComponentAdmin(componentUtils.getResponseFormat(ActionStatus.OK), user, c, auditAction,
+ ComponentTypeEnum.findByParamName(containerComponentType), comment);
+ });
}
}
}
- protected Either<Component, ResponseFormat> sendNotificationToFacade(String componentId,
- ChangeTypeEnum changeStatus) {
- log.debug("build {} notification for facade start", changeStatus.name());
- Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaElement(componentId);
- Component component = toscaElement.left()
- .value();
- ActionStatus status = catalogOperations.updateCatalog(changeStatus, component);
- if (status != ActionStatus.OK) {
- return Either.right(componentUtils.getResponseFormat(status));
- }
- return Either.left(component);
- }
+
+ protected Either<Component, ResponseFormat> sendNotificationToFacade(String componentId, ChangeTypeEnum changeStatus) {
+ log.debug("build {} notification for facade start", changeStatus.name());
+ Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaElement(componentId);
+ Component component = toscaElement.left().value();
+ ActionStatus status = catalogOperations.updateCatalog(changeStatus, component);
+ if (status != ActionStatus.OK) {
+ return Either.right(componentUtils.getResponseFormat(status));
+ }
+ return Either.left(component);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java
index 66dce60641..19eda82281 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,18 +17,8 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
-import org.apache.commons.collections.MapUtils;
-import org.openecomp.sdc.be.components.ArtifactsResolver;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.InterfaceDefinition;
-import org.openecomp.sdc.be.model.Service;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -37,6 +27,14 @@ import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
+import org.apache.commons.collections.MapUtils;
+import org.openecomp.sdc.be.components.ArtifactsResolver;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.InterfaceDefinition;
+import org.openecomp.sdc.be.model.Service;
@org.springframework.stereotype.Component("artifact-resolver")
public class ArtifactResolverImpl implements ArtifactsResolver {
@@ -45,7 +43,6 @@ public class ArtifactResolverImpl implements ArtifactsResolver {
public ArtifactDefinition findArtifactOnComponent(Component component, ComponentTypeEnum componentType, String artifactId) {
List<ArtifactDefinition> allComponentsArtifacts = getAllComponentsArtifacts(component, componentType);
return findById(allComponentsArtifacts, artifactId);
-
}
@Override
@@ -55,29 +52,23 @@ public class ArtifactResolverImpl implements ArtifactsResolver {
}
private ArtifactDefinition findById(List<ArtifactDefinition> artifacts, String artifactId) {
- return artifacts.stream()
- .filter(artifact -> artifact.getUniqueId().equals(artifactId))
- .findFirst().orElse(null);
+ return artifacts.stream().filter(artifact -> artifact.getUniqueId().equals(artifactId)).findFirst().orElse(null);
}
private List<ArtifactDefinition> getAllComponentsArtifacts(Component component, ComponentTypeEnum componentType) {
Map<String, ArtifactDefinition> deploymentArtifacts = Optional.ofNullable(component.getDeploymentArtifacts()).orElse(Collections.emptyMap());
Map<String, ArtifactDefinition> artifacts = Optional.ofNullable(component.getArtifacts()).orElse(Collections.emptyMap());
- Map<String, ArtifactDefinition> interfaceArtifacts= Collections.emptyMap();
+ Map<String, ArtifactDefinition> interfaceArtifacts = Collections.emptyMap();
Map<String, InterfaceDefinition> interfaces = component.getInterfaces();
if (MapUtils.isNotEmpty(interfaces)) {
- interfaceArtifacts = interfaces.values().stream()
- .flatMap(inte -> inte.getOperationsMap().values().stream())
- .map(operation -> operation.getImplementationArtifact()).filter(Objects::nonNull)
- .collect(Collectors.toMap(artifactDefinition -> artifactDefinition.getUniqueId(),
- artifactDefinition -> artifactDefinition, (a1, a2) -> a1));
+ interfaceArtifacts = interfaces.values().stream().flatMap(inte -> inte.getOperationsMap().values().stream())
+ .map(operation -> operation.getImplementationArtifact()).filter(Objects::nonNull).collect(Collectors
+ .toMap(artifactDefinition -> artifactDefinition.getUniqueId(), artifactDefinition -> artifactDefinition, (a1, a2) -> a1));
}
-
Map<String, ArtifactDefinition> serviceApiArtifacts = Collections.emptyMap();
if (componentType == ComponentTypeEnum.SERVICE) {
serviceApiArtifacts = Optional.ofNullable(((Service) component).getServiceApiArtifacts()).orElse(Collections.emptyMap());
}
-
return appendAllArtifacts(deploymentArtifacts, artifacts, interfaceArtifacts, serviceApiArtifacts);
}
@@ -93,5 +84,4 @@ public class ArtifactResolverImpl implements ArtifactsResolver {
Arrays.stream(artifacts).forEach(a -> allArtifacts.addAll(a.values()));
return allArtifacts;
}
-
}
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 046ad22159..849e3c8bdb 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
@@ -19,7 +19,6 @@
* Modifications copyright (c) 2020 Nokia
* ================================================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import static org.openecomp.sdc.be.dao.api.ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE;
@@ -143,6 +142,13 @@ import org.yaml.snakeyaml.Yaml;
@org.springframework.stereotype.Component("artifactBusinessLogic")
public class ArtifactsBusinessLogic extends BaseBusinessLogic {
+
+ public static final String HEAT_ENV_NAME = "heatEnv";
+ public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
+ public static final String HEAT_ENV_SUFFIX = "env";
+ public static final String ARTIFACT_ACTION_LOCK = "Artifact action - lock ";
+ public static final String FAILED_UPLOAD_ARTIFACT_TO_COMPONENT = "Failed to upload artifact to component with type {} and uuid {}. Status is {}. ";
+ public static final String COMPONENT_INSTANCE_NOT_FOUND = "Component instance {} was not found for component {}";
private static final String RESOURCE_INSTANCE = "resource instance";
private static final String ARTIFACT_TYPE_OTHER = "OTHER";
private static final String ARTIFACT_DESCRIPTION = "artifact description";
@@ -150,41 +156,28 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private static final String ARTIFACT_URL = "artifact url";
private static final String ARTIFACT_NAME = "artifact name";
private static final String ARTIFACT_PAYLOAD = "artifact payload";
-
private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
-
- public static final String HEAT_ENV_NAME = "heatEnv";
- public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
- 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.getName());
private static final String FAILED_UPDATE_GROUPS = "Failed to update groups of the component {}. ";
private static final String FAILED_SAVE_ARTIFACT = "Failed to save the artifact.";
- public static final String ARTIFACT_ACTION_LOCK = "Artifact action - lock ";
- 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_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";
- public static final String COMPONENT_INSTANCE_NOT_FOUND = "Component instance {} was not found for component {}";
private static final String ROLLBACK = "all changes rollback";
private static final String COMMIT = "all changes committed";
private static final String UPDATE_ARTIFACT = "Update Artifact";
private static final String FOUND_DEPLOYMENT_ARTIFACT = "Found deployment artifact {}";
private Gson gson = new GsonBuilder().setPrettyPrinting().create();
-
@javax.annotation.Resource
private IInterfaceLifecycleOperation interfaceLifecycleOperation;
@javax.annotation.Resource
private UserAdminOperation userOperaton;
-
@javax.annotation.Resource
private IElementOperation elementOperation;
-
@javax.annotation.Resource
private IHeatParametersOperation heatParametersOperation;
-
private ArtifactCassandraDao artifactCassandraDao;
private ToscaExportHandler toscaExportUtils;
private CsarUtils csarUtils;
@@ -194,13 +187,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private NodeTemplateOperation nodeTemplateOperation;
@Autowired
- public ArtifactsBusinessLogic(ArtifactCassandraDao artifactCassandraDao, ToscaExportHandler toscaExportUtils,
- CsarUtils csarUtils, LifecycleBusinessLogic lifecycleBusinessLogic, UserBusinessLogic userBusinessLogic,
+ public ArtifactsBusinessLogic(ArtifactCassandraDao artifactCassandraDao, ToscaExportHandler toscaExportUtils, 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);
+ IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation,
+ InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+ ArtifactsOperations artifactToscaOperation) {
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+ artifactToscaOperation);
this.artifactCassandraDao = artifactCassandraDao;
this.toscaExportUtils = toscaExportUtils;
this.csarUtils = csarUtils;
@@ -209,20 +203,27 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
this.artifactsResolver = artifactsResolver;
}
- public enum ArtifactOperationEnum {
- CREATE, UPDATE, DELETE, DOWNLOAD, LINK;
+ public static <R> Either<Boolean, R> ifTrue(boolean predicate, Supplier<Either<Boolean, R>> ifTrue) {
+ return predicate ? ifTrue.get() : Either.left(false);
+ }
- public static boolean isCreateOrLink(ArtifactOperationEnum operation) {
- return operation == CREATE || operation == LINK;
- }
+ public static <L, R> Either<L, R> forEach(Either<L, R> e, Consumer<L> c) {
+ return e.left().map(l -> {
+ c.accept(l);
+ return l;
+ });
+ }
+
+ private static Option<ComponentInstance> findFirstMatching(Component component, Predicate<ComponentInstance> filter) {
+ return Option.ofOptional(component.getComponentInstances().stream().filter(filter).findFirst());
}
// new flow US556184
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) {
-
+ 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);
// step 2 - check header
@@ -233,13 +234,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION);
}
// step 3 - check user existence
+
// step 4 - check user's role
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
Component component = null;
String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
@@ -249,45 +253,49 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
validateResourceInstanceById(component, componentId);
}
// step 8
-
- return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5,
- originData, interfaceName, operationName, 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);
+ 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);
}
/**
- * This Method validates only the Artifact and does not validate user / role / component ect...<br>
- * For regular usage use <br>
- * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
+ * This Method validates only the Artifact and does not validate user / role / component ect...<br> For regular usage use <br> {@link
+ * #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String,
+ * String, String)}
*
* @return
*/
- 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) {
+ 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, shouldLock, inTransaction);
-
+ 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);
+ origMd5, originData, interfaceName, operationName, auditingAction, user, component, shouldLock, inTransaction, needUpdateGroup);
//TODO: audit positive action
return result;
}
@VisibleForTesting
- ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user,
- Component component, boolean shouldLock, boolean inTransaction) {
+ 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) {
+ if (operationEnum == ArtifactOperationEnum.UPDATE || operationEnum == ArtifactOperationEnum.DELETE
+ || operationEnum == ArtifactOperationEnum.DOWNLOAD) {
ArtifactDefinition dbArtifact = getArtifactIfBelongsToComponent(componentId, componentType, artifactId, component);
if (operation.isDownload()) {
artifactInfoToReturn = dbArtifact;
@@ -300,28 +308,19 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
@VisibleForTesting
void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, Component component,
ArtifactDefinition artifactDefinition, boolean shouldLock, boolean inTransaction) {
-
- if (artifactDefinition.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())
- && ComponentTypeEnum.SERVICE == component.getComponentType()) {
- ComponentInstance componentInstance = component.getComponentInstances()
- .stream()
- .filter(p -> p.getUniqueId().equals(componentId))
- .findAny()
- .orElse(null);
+ if (artifactDefinition.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) && ComponentTypeEnum.SERVICE == component
+ .getComponentType()) {
+ ComponentInstance componentInstance = component.getComponentInstances().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());
+ 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(artifactDefinition.getUniqueId()))
- .findAny()
- .orElse(null);
- Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams,
- componentType, component, componentInstance.getName(), user, componentId, shouldLock, inTransaction);
+ ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values().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()) {
throw new ByResponseFormatComponentException((eitherGenerated.right().value()));
}
@@ -330,72 +329,62 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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)));
+ 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)));
return needGenerate;
}
private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
- return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo
- .getArtifactType()
- .equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
- }
-
- public Either<ArtifactDefinition, Operation> generateAndSaveToscaArtifact(
- ArtifactDefinition artifactDefinition, Component component,
- User user, boolean isInCertificationRequest, boolean shouldLock, boolean inTransaction,
- boolean fetchTemplatesFromDB) {
-
- return decodeToscaArtifactPayload(
- component, isInCertificationRequest, fetchTemplatesFromDB, artifactDefinition.getArtifactType()
- ).left().bind(payload -> {
- // TODO: Avoid output argument
- artifactDefinition.setPayload(payload);
- artifactDefinition.setEsId(artifactDefinition.getUniqueId());
- artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(payload));
- return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition,
- AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition.getUniqueId(),
- user, component.getComponentType(), component, payload, shouldLock, inTransaction
- );
- }).right().map(ex -> {
- // TODO: This should not be done but in order to keep this refactoring small enough, we stop here.
- // Bubble up this exception
- throw ex;
- });
+ return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo.getArtifactType()
+ .equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
+ }
+
+ public Either<ArtifactDefinition, Operation> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, Component component, User user,
+ boolean isInCertificationRequest, boolean shouldLock,
+ boolean inTransaction, boolean fetchTemplatesFromDB) {
+ return decodeToscaArtifactPayload(component, isInCertificationRequest, fetchTemplatesFromDB, artifactDefinition.getArtifactType()).left()
+ .bind(payload -> {
+ // TODO: Avoid output argument
+ artifactDefinition.setPayload(payload);
+ artifactDefinition.setEsId(artifactDefinition.getUniqueId());
+ artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(payload));
+ return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE,
+ artifactDefinition.getUniqueId(), user, component.getComponentType(), component, payload, shouldLock, inTransaction);
+ }).right().map(ex -> {
+ // TODO: This should not be done but in order to keep this refactoring small enough, we stop here.
+
+ // Bubble up this exception
+ throw ex;
+ });
}
- private Either<byte[], ComponentException> decodeToscaArtifactPayload(
- Component parent,
- boolean isInCertificationRequest,
- boolean fetchTemplatesFromDB,
- String artifactType
- ) {
+ private Either<byte[], ComponentException> decodeToscaArtifactPayload(Component parent, boolean isInCertificationRequest,
+ boolean fetchTemplatesFromDB, String artifactType) {
log.debug("tosca artifact generation");
if (ArtifactTypeEnum.TOSCA_CSAR.getType().equals(artifactType)) {
- return csarUtils
- .createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest)
- .right().map(error -> {
- log.debug("Failed to generate tosca csar for component {} error {}", parent.getUniqueId(), error);
- return new ByResponseFormatComponentException(error);
- });
+ return csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest).right().map(error -> {
+ log.debug("Failed to generate tosca csar for component {} error {}", parent.getUniqueId(), error);
+ return new ByResponseFormatComponentException(error);
+ });
} else {
- return toscaExportUtils
- .exportComponent(parent)
- .left().map(toscaRepresentation -> {
- log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
- return toscaRepresentation.getMainYaml();
- }).right().map(toscaError -> {
- log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), toscaError);
- return new ByActionStatusComponentException(componentsUtils.convertFromToscaError(toscaError));
- });
+ return toscaExportUtils.exportComponent(parent).left().map(toscaRepresentation -> {
+ log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
+ return toscaRepresentation.getMainYaml();
+ }).right().map(toscaError -> {
+ log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), toscaError);
+ return new ByActionStatusComponentException(componentsUtils.convertFromToscaError(toscaError));
+ });
}
}
- 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) {
+ 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();
@@ -418,23 +407,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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);
+ 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);
+ 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());
+ throw new UnsupportedOperationException(
+ "In ArtifactsBusinessLogic received illegal operation: " + operation.getArtifactOperationEnum());
}
operationSucceeded = true;
return result;
- }
- finally {
+ } finally {
handleLockingAndCommit(parent, shouldLock, inTransaction, operationSucceeded);
}
}
@@ -442,44 +431,41 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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);
+ } 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) {
+ 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;
validateArtifactType(artifactInfo);
final String artifactType = artifactInfo.getArtifactType();
- if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE &&
- (ArtifactTypeEnum.HEAT.getType().equals(artifactType) ||
- ArtifactTypeEnum.HEAT_VOL.getType().equals(artifactType) ||
- ArtifactTypeEnum.HEAT_NET.getType().equals(artifactType) ||
- ArtifactTypeEnum.HEAT_ENV.getType().equals(artifactType))) {
- result = handleUpdateHeatEnvAndHeatMeta(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation);
+ if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && (ArtifactTypeEnum.HEAT.getType().equals(artifactType) || ArtifactTypeEnum.HEAT_VOL
+ .getType().equals(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equals(artifactType) || ArtifactTypeEnum.HEAT_ENV.getType()
+ .equals(artifactType))) {
+ 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);
}
}
- }
- else if (componentType == ComponentTypeEnum.RESOURCE && ArtifactTypeEnum.HEAT_ENV.getType().equals(artifactType)) {
- result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, componentType, parent, originData, origMd5, operation, needUpdateGroup);
- }
- else {
+ } else if (componentType == ComponentTypeEnum.RESOURCE && ArtifactTypeEnum.HEAT_ENV.getType().equals(artifactType)) {
+ 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);
+ decodedPayload = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5,
+ originData, interfaceName, operationName);
}
- result = updateArtifactFlow(parent, componentId, artifactId, artifactInfo, decodedPayload, componentType, auditingAction
- );
+ result = updateArtifactFlow(parent, componentId, artifactId, artifactInfo, decodedPayload, componentType, auditingAction);
if (needUpdateGroup && result.isLeft()) {
ArtifactDefinition updatedArtifact = result.left().value();
updateGroupForHeat(artifactInfo, updatedArtifact, parent);
@@ -494,30 +480,25 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
- private void validateArtifactType(final ArtifactDefinition artifactInfo,
- final ComponentTypeEnum componentType) {
- final ArtifactConfiguration artifactConfiguration =
- loadArtifactTypeConfig(artifactInfo.getArtifactType()).orElse(null);
+ private void validateArtifactType(final ArtifactDefinition artifactInfo, final ComponentTypeEnum componentType) {
+ final ArtifactConfiguration artifactConfiguration = loadArtifactTypeConfig(artifactInfo.getArtifactType()).orElse(null);
if (artifactConfiguration == null) {
- BeEcompErrorManager.getInstance()
- .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
+ BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE);
throw new ByResponseFormatComponentException(responseFormat);
}
-
final ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
try {
validateArtifactType(componentType, artifactGroupType, artifactConfiguration);
} catch (final ComponentException e) {
log.debug("Artifact is invalid", e);
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());
final ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
- .getArtifactType());
+ .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
throw new ByResponseFormatComponentException(responseFormat);
}
}
@@ -525,22 +506,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private void validateArtifactType(final ComponentTypeEnum componentType, final ArtifactGroupTypeEnum groupType,
final ArtifactConfiguration artifactConfiguration) {
final boolean supportComponentType =
- CollectionUtils.isNotEmpty(artifactConfiguration.getComponentTypes()) &&
- artifactConfiguration.getComponentTypes().stream()
- .anyMatch(componentType1 -> componentType1.getValue().equalsIgnoreCase(componentType.getValue()));
+ CollectionUtils.isNotEmpty(artifactConfiguration.getComponentTypes()) && artifactConfiguration.getComponentTypes().stream()
+ .anyMatch(componentType1 -> componentType1.getValue().equalsIgnoreCase(componentType.getValue()));
if (!supportComponentType) {
- log.debug("Artifact Type '{}' not supported for Component Type '{}'",
- artifactConfiguration.getType(), componentType.getValue());
- throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED,
- artifactConfiguration.getType());
+ log.debug("Artifact Type '{}' not supported for Component Type '{}'", artifactConfiguration.getType(), componentType.getValue());
+ throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactConfiguration.getType());
}
-
final boolean supportResourceType = artifactConfiguration.hasSupport(groupType);
if (!supportResourceType) {
- log.debug("Artifact Type '{}' not supported for Component Type '{}' and Category '{}'",
- artifactConfiguration.getType(), componentType.getValue(), groupType.getType());
- throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED,
- artifactConfiguration.getType());
+ log.debug("Artifact Type '{}' not supported for Component Type '{}' and Category '{}'", artifactConfiguration.getType(),
+ componentType.getValue(), groupType.getType());
+ throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactConfiguration.getType());
}
}
@@ -550,8 +526,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (CollectionUtils.isEmpty(artifactConfigurationList)) {
return false;
}
- return artifactConfigurationList.stream()
- .anyMatch(artifactConfiguration -> artifactConfiguration.getType().equalsIgnoreCase(artifactType));
+ return artifactConfigurationList.stream().anyMatch(artifactConfiguration -> artifactConfiguration.getType().equalsIgnoreCase(artifactType));
}
@VisibleForTesting
@@ -559,17 +534,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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())){
+ if (!artifactInfo.getArtifactUUID().equals(artAfterUpdate.getArtifactUUID())) {
g.setGroupUUID(UniqueIdBuilder.generateUUID());
}
});
@@ -584,14 +556,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
@VisibleForTesting
- ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent) {
+ 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());
@@ -614,10 +584,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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();
+ Optional<ComponentInstance> componentInstOp = parent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(parentId))
+ .findFirst();
if (componentInstOp.isPresent()) {
groupInstances = componentInstOp.get().getGroupInstances();
}
@@ -626,15 +594,13 @@ 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;
@@ -644,7 +610,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
}
- Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances);
+ Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade
+ .updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances);
if (status.isRight()) {
log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
return componentsUtils.convertFromStorageResponse(status.right().value());
@@ -654,17 +621,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
ArtifactDefinition generateNotSavedArtifact(Component parent, ArtifactDefinition artifactDefinition) {
if (artifactDefinition.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
- Either<byte[], ComponentException> decodedPayload = decodeToscaArtifactPayload(parent, false,
- false, artifactDefinition.getArtifactType());
+ Either<byte[], ComponentException> decodedPayload = decodeToscaArtifactPayload(parent, false, false,
+ artifactDefinition.getArtifactType());
// TODO: This should not be done, but in order to keep this refactoring relatively small, we stop here
- if(decodedPayload.isRight())
+ if (decodedPayload.isRight()) {
throw decodedPayload.right().value();
- else {
+ } else {
artifactDefinition.setPayload(decodedPayload.left().value());
return artifactDefinition;
}
- }
- else {
+ } else {
String heatArtifactId = artifactDefinition.getGeneratedFromId();
Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
if (heatRes.isRight()) {
@@ -677,11 +643,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
- 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());
+ 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) {
validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
@@ -703,7 +671,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
} else {
log.debug(ROLLBACK);
if (!inTransaction) {
- janusGraphDao.rollback();
+ janusGraphDao.rollback();
}
}
if (shouldLock) {
@@ -714,10 +682,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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());
+ log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right().value());
throw new ByResponseFormatComponentException(generated.right().value());
}
return new ImmutablePair<>(csarArtifact.getArtifactName(), generated.left().value());
@@ -725,47 +691,54 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return downloadArtifact(csarArtifact);
}
- public ImmutablePair<String, byte[]> 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<ArtifactDefinition, Operation> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null,
- null, parentId, containerComponentType);
+ Either<ArtifactDefinition, Operation> result = handleArtifactRequest(componentId, userId, componentType,
+ new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null, null, parentId,
+ containerComponentType);
ArtifactDefinition artifactDefinition;
Either<ArtifactDefinition, Operation> insideValue = result;
if (insideValue.isLeft()) {
artifactDefinition = insideValue.left().value();
- }
- else {
+ } else {
artifactDefinition = insideValue.right().value().getImplementationArtifact();
}
// for tosca artifacts and heat env on VF level generated on download without saving
if (artifactDefinition.getPayloadData() != null) {
- return (new ImmutablePair<>(artifactDefinition.getArtifactName(), artifactDefinition
- .getPayloadData()));
+ return (new ImmutablePair<>(artifactDefinition.getArtifactName(), artifactDefinition.getPayloadData()));
}
return downloadArtifact(artifactDefinition);
}
- public Map<String, ArtifactDefinition> 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;
-
new Wrapper<>();
// step 2
+
// check header
if (userId == null) {
log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION);
}
// step 3
+
// check user existence
+
// step 4
- // check user's role
+ // check user's role
validateUserExists(userId);
// steps 5 - 6 - 7
+
// 5. check service/resource existence
+
// 6. check service/resource check out
+
// 7. user is owner of checkout state
String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
ComponentParametersView componentFilter = new ComponentParametersView();
@@ -774,14 +747,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
componentFilter.setIgnoreComponentInstances(false);
}
-
- Component component = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum
- .findByParamName(containerComponentType), componentFilter);
+ Component component = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum.findByParamName(containerComponentType),
+ componentFilter);
lockComponent(component, ARTIFACT_ACTION_LOCK);
boolean failed = false;
try {
ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
-
if (groupType == null) {
log.debug("handleGetArtifactsByType - not failed groupType {} , component id {}", artifactGroupType, componentId);
throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION);
@@ -790,30 +761,26 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentId);
if (list != null && !list.isEmpty()) {
resMap = list.stream().collect(Collectors.toMap(ArtifactDataDefinition::getArtifactLabel, Function.identity()));
- }
- else {
+ } else {
resMap = new HashMap<>();
}
return resMap;
} else {
-
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType
- .getNodeType(), groupType, componentId);
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId,
+ componentType.getNodeType(), groupType, componentId);
if (artifactsMapStatus.isRight()) {
if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
log.debug("handleGetArtifactsByType - not failed groupType {} , component id {}", artifactGroupType, componentId);
throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION);
- }
- else {
+ } else {
resMap = new HashMap<>();
}
- }
- else {
+ } else {
resMap = artifactsMapStatus.left().value();
}
return resMap;
}
- }catch (ComponentException e){
+ } catch (ComponentException e) {
failed = true;
throw e;
} finally {
@@ -821,23 +788,21 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (failed) {
log.debug(ROLLBACK);
janusGraphDao.rollback();
- }
- else {
+ } else {
log.debug(COMMIT);
janusGraphDao.commit();
}
-
componentType = component.getComponentType();
NodeTypeEnum nodeType = componentType.getNodeType();
graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
}
-
}
- private ArtifactDefinition getArtifactIfBelongsToComponent(String componentId, ComponentTypeEnum componentType, String artifactId, Component component) {
+ 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()) {
throw new ByActionStatusComponentException(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, artifactId, componentId);
}
@@ -860,22 +825,24 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return artifactResult.left().value();
}
- 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);
+ 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);
}
- private ArtifactDefinition handleLink(String componentId, ArtifactDefinition artifactInfo, ComponentTypeEnum componentType,
- Component parent) {
+ 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();
}
NodeTypeEnum nodeType = convertParentType(componentType);
- Either<ArtifactDefinition, StorageOperationStatus> artifactDefinitionEither = artifactToscaOperation.addArtifactToComponent(artifactInfo, parent,
- nodeType, true, instanceId);
+ Either<ArtifactDefinition, StorageOperationStatus> artifactDefinitionEither = artifactToscaOperation
+ .addArtifactToComponent(artifactInfo, parent, nodeType, true, instanceId);
if (artifactDefinitionEither.isRight()) {
throw new StorageException(artifactDefinitionEither.right().value(), artifactInfo.getArtifactDisplayName());
}
@@ -885,55 +852,52 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return artifactDefinitionEither.left().value();
}
- private <T> Either<ArtifactDefinition, T> lockComponentAndUpdateArtifact(
- String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId,
- User user, ComponentTypeEnum componentType, Component parent, byte[] decodedPayload,
- boolean shouldLock, boolean inTransaction) {
-
+ private <T> Either<ArtifactDefinition, T> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo,
+ AuditingActionEnum auditingAction, String artifactId, User user,
+ ComponentTypeEnum componentType, Component parent, byte[] decodedPayload,
+ boolean shouldLock, boolean inTransaction) {
boolean failed = false;
boolean writeAudit = true;
try {
lockComponent(parent, shouldLock, ARTIFACT_ACTION_LOCK);
writeAudit = false;
- return updateArtifactFlow(parent, parentId, artifactId, artifactInfo, decodedPayload, componentType,
- auditingAction);
- }
- catch (ComponentException ce) {
- if(writeAudit) {
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, ce.getResponseFormat(),
- componentType, null);
+ return updateArtifactFlow(parent, parentId, artifactId, artifactInfo, decodedPayload, componentType, auditingAction);
+ } catch (ComponentException ce) {
+ if (writeAudit) {
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, ce.getResponseFormat(), componentType, null);
}
failed = true;
throw ce;
- }
- catch (StorageException se) {
+ } catch (StorageException se) {
//TODO: audit
failed = true;
throw se;
- }
- finally {
+ } finally {
if (shouldLock) {
unlockComponent(failed, parent, 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) {
+ 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);
+ return getValidPayload(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, interfaceType,
+ operationName);
}
- private byte[] getValidPayload(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction,
- String artifactId, User user, ComponentTypeEnum componentType, Component parent, String interfaceType, String operationName) {
+ 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);
+ 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);
throw new ByResponseFormatComponentException(responseFormat);
}
-
Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
if (payloadEither.isRight()) {
ResponseFormat responseFormat = payloadEither.right().value();
@@ -942,9 +906,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
throw new ByResponseFormatComponentException(responseFormat);
}
// validate heat parameters. this part must be after the parameters are
+
// extracted in "handlePayload"
- Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParameters = validateAndConvertHeatParameters(artifactInfo, artifactInfo
- .getArtifactType());
+ Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParameters = validateAndConvertHeatParameters(artifactInfo,
+ artifactInfo.getArtifactType());
if (validateAndConvertHeatParameters.isRight()) {
ResponseFormat responseFormat = validateAndConvertHeatParameters.right().value();
handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
@@ -957,19 +922,20 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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;
}
-
if (user == null) {
user = new User();
user.setUserId("UNKNOWN");
}
- handleInternalAuditEvent(auditingActionEnum, component, componentId, user, artifactDefinition, prevArtifactUuid, currentArtifactUuid, responseFormat, componentTypeEnum, resourceInstanceName);
+ handleInternalAuditEvent(auditingActionEnum, component, componentId, user, artifactDefinition, prevArtifactUuid, currentArtifactUuid,
+ responseFormat, componentTypeEnum, resourceInstanceName);
}
- private void handleInternalAuditEvent(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat, ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
+ private void handleInternalAuditEvent(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user,
+ ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid,
+ ResponseFormat responseFormat, ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
switch (componentTypeEnum) {
case RESOURCE:
Resource resource = (Resource) component;
@@ -979,11 +945,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
resource.setName(componentId);
}
componentsUtils.auditResource(responseFormat, user, resource, resource.getName(), auditingActionEnum,
- ResourceVersionInfo.newBuilder()
- .artifactUuid(prevArtifactUuid)
- .build(), currentArtifactUuid, artifactDefinition);
+ ResourceVersionInfo.newBuilder().artifactUuid(prevArtifactUuid).build(), currentArtifactUuid, artifactDefinition);
break;
-
case SERVICE:
Service service = (Service) component;
if (service == null) {
@@ -991,29 +954,19 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
service = new Service();
service.setName(componentId);
}
- componentsUtils.auditComponent(responseFormat, user, service, auditingActionEnum, new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()),
- ResourceVersionInfo.newBuilder()
- .artifactUuid(prevArtifactUuid)
- .build(),
- ResourceVersionInfo.newBuilder()
- .artifactUuid(currentArtifactUuid)
- .build(),
- null, artifactDefinition, null);
+ componentsUtils
+ .auditComponent(responseFormat, user, service, auditingActionEnum, new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()),
+ ResourceVersionInfo.newBuilder().artifactUuid(prevArtifactUuid).build(),
+ ResourceVersionInfo.newBuilder().artifactUuid(currentArtifactUuid).build(), null, artifactDefinition, null);
break;
-
case RESOURCE_INSTANCE:
if (resourceInstanceName == null) {
resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
}
componentsUtils.auditComponent(responseFormat, user, component, auditingActionEnum,
- new ResourceCommonInfo(resourceInstanceName, ComponentTypeEnum.RESOURCE_INSTANCE.getValue()),
- ResourceVersionInfo.newBuilder()
- .artifactUuid(prevArtifactUuid)
- .build(),
- ResourceVersionInfo.newBuilder()
- .artifactUuid(currentArtifactUuid)
- .build(),
- null, artifactDefinition, null);
+ new ResourceCommonInfo(resourceInstanceName, ComponentTypeEnum.RESOURCE_INSTANCE.getValue()),
+ ResourceVersionInfo.newBuilder().artifactUuid(prevArtifactUuid).build(),
+ ResourceVersionInfo.newBuilder().artifactUuid(currentArtifactUuid).build(), null, artifactDefinition, null);
break;
default:
break;
@@ -1021,11 +974,8 @@ 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);
+ ComponentInstance resourceInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findFirst()
+ .orElse(null);
String resourceInstanceName = null;
if (resourceInstance != null) {
resourceInstanceName = resourceInstance.getName();
@@ -1053,19 +1003,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
- private Either<ArtifactDefinition, ResponseFormat> validateInput(final String componentId,
- final ArtifactDefinition artifactInfo,
- final ArtifactOperationInfo operation,
- final String artifactId, final User user,
- String interfaceName,
- String operationName,
- final ComponentTypeEnum componentType,
- final Component parentComponent) {
-
- final ArtifactDefinition existingArtifactInfo =
- findArtifact(parentComponent, componentType, componentId, operation, artifactId);
- final boolean isCreateOrLinkOperation =
- ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum());
+ private Either<ArtifactDefinition, ResponseFormat> validateInput(final String componentId, final ArtifactDefinition artifactInfo,
+ final ArtifactOperationInfo operation, final String artifactId, final User user,
+ String interfaceName, String operationName,
+ final ComponentTypeEnum componentType, final Component parentComponent) {
+ final ArtifactDefinition existingArtifactInfo = findArtifact(parentComponent, componentType, componentId, operation, artifactId);
+ final boolean isCreateOrLinkOperation = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum());
if (!isCreateOrLinkOperation && existingArtifactInfo == null) {
throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactId);
}
@@ -1094,13 +1037,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
operationName = operationName.toLowerCase();
interfaceName = interfaceName.toLowerCase();
}
- Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactInfo, operationName, componentType);
+ Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactInfo,
+ operationName, componentType);
if (logicalNameStatus.isRight()) {
return Either.right(logicalNameStatus.right().value());
}
// This is a patch to block possibility of updating service api fields
- // through other artifacts flow
+ // through other artifacts flow
final ArtifactGroupTypeEnum artifactGroupType =
operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL;
if (operation.isNotCreateOrLink()) {
@@ -1108,7 +1052,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
} else {
checkCreateFields(user, artifactInfo, artifactGroupType);
}
-
composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
if (existingArtifactInfo != null) {
artifactInfo.setMandatory(existingArtifactInfo.getMandatory());
@@ -1116,7 +1059,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
validateArtifactTypeNotChanged(artifactInfo, existingArtifactInfo);
}
}
-
// artifactGroupType is not allowed to be updated
if (operation.isNotCreateOrLink()) {
Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, existingArtifactInfo);
@@ -1124,7 +1066,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.right(validateGroupType.right().value());
}
}
-
setArtifactTimeout(artifactInfo, existingArtifactInfo);
if (isHeatArtifact(artifactInfo)) {
validateHeatArtifact(parentComponent, componentId, artifactInfo);
@@ -1132,34 +1073,26 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (isDeploymentArtifact(artifactInfo)) {
if (componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
final String artifactName = artifactInfo.getArtifactName();
- final String existingArtifactName =
- (existingArtifactInfo == null) ? null : existingArtifactInfo.getArtifactName();
-
- if (operation.isCreateOrLink()
- || ((artifactName != null) && !artifactName.equalsIgnoreCase(existingArtifactName))) {
+ final String existingArtifactName = (existingArtifactInfo == null) ? null : existingArtifactInfo.getArtifactName();
+ if (operation.isCreateOrLink() || ((artifactName != null) && !artifactName.equalsIgnoreCase(existingArtifactName))) {
validateSingleDeploymentArtifactName(artifactName, parentComponent);
}
}
validateDeploymentArtifact(artifactInfo, component);
}
-
Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
if (descriptionResult.isRight()) {
return Either.right(descriptionResult.right().value());
}
-
validateArtifactType(artifactInfo, component.getComponentType());
artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
if (existingArtifactInfo != null && existingArtifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.SERVICE_API) {
// Change of type is not allowed and should be ignored
-
artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
-
Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
if (validateUrl.isRight()) {
return Either.right(validateUrl.right().value());
}
-
Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, existingArtifactInfo);
if (validateUpdate.isRight()) {
log.debug("serviceApi first update cnnot be without payload.");
@@ -1170,13 +1103,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
artifactInfo.setApiUrl(null);
log.error("Artifact URL cannot be set through this API - ignoring");
}
-
if (Boolean.TRUE.equals(artifactInfo.getServiceApi())) {
artifactInfo.setServiceApi(false);
log.error("Artifact service API flag cannot be changed - ignoring");
}
}
-
return Either.left(artifactInfo);
}
@@ -1186,12 +1117,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
log.debug("Component '{}' not found ", componentId);
throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NOT_FOUND, componentId);
}
-
return component.left().value();
}
- private void ignoreUnupdateableFieldsInUpdate(final ArtifactOperationInfo operation,
- final ArtifactDefinition artifactInfo,
+ private void ignoreUnupdateableFieldsInUpdate(final ArtifactOperationInfo operation, final ArtifactDefinition artifactInfo,
final ArtifactDefinition currentArtifactInfo) {
if (operation.isUpdate()) {
artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
@@ -1200,9 +1129,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
- private ArtifactDefinition findArtifact(final Component parentComponent, final ComponentTypeEnum componentType,
- final String parentId, final ArtifactOperationInfo operation,
- final String artifactId) {
+ private ArtifactDefinition findArtifact(final Component parentComponent, final ComponentTypeEnum componentType, final String parentId,
+ final ArtifactOperationInfo operation, final String artifactId) {
ArtifactDefinition foundArtifact = null;
if (StringUtils.isNotEmpty(artifactId)) {
foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
@@ -1222,8 +1150,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
ArtifactDefinition foundArtifact;
if (parentComponent.getUniqueId().equals(parentId)) {
foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
- }
- else {
+ } else {
ComponentInstance instance = findComponentInstance(parentId, parentComponent);
foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
}
@@ -1242,10 +1169,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactType);
}
validateArtifactType(parentComponentType, artifactInfo.getArtifactGroupType(), artifactConfiguration);
-
- if (component.getComponentType() == ComponentTypeEnum.RESOURCE ||
- component.getComponentType() == ComponentTypeEnum.RESOURCE_INSTANCE) {
-
+ if (component.getComponentType() == ComponentTypeEnum.RESOURCE || component.getComponentType() == ComponentTypeEnum.RESOURCE_INSTANCE) {
final ResourceTypeEnum resourceType = ((Resource) component).getResourceType();
validateResourceType(resourceType, artifactInfo, artifactConfiguration.getResourceTypes());
}
@@ -1255,89 +1179,70 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
if (componentType == ComponentTypeEnum.RESOURCE) {
return NodeTypeEnum.Resource;
- }
- else if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
+ } else if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
return NodeTypeEnum.ResourceInstance;
- }
- else {
+ } else {
return NodeTypeEnum.Service;
}
}
// This method is here for backward compatibility - when other parts of the code are cleaned can change to use the internal version
- public Either<ArtifactDefinition, ResponseFormat> handleDelete(
- String parentId, String artifactId, User user, Component parent,
- boolean shouldLock, boolean inTransaction) {
-
+ public Either<ArtifactDefinition, ResponseFormat> handleDelete(String parentId, String artifactId, User user, Component parent,
+ boolean shouldLock, boolean inTransaction) {
ResponseFormat responseFormat;
boolean operationSucceeded = false;
if (shouldLock) {
lockComponent(ComponentTypeEnum.RESOURCE, artifactId, AuditingActionEnum.ARTIFACT_DELETE, user, parent);
}
try {
- ArtifactDefinition artifactDefinition = handleDeleteInternal(parentId, artifactId,
- ComponentTypeEnum.RESOURCE, parent);
+ ArtifactDefinition artifactDefinition = handleDeleteInternal(parentId, artifactId, ComponentTypeEnum.RESOURCE, parent);
operationSucceeded = true;
return Either.left(artifactDefinition);
- }
- catch (ComponentException ce) {
+ } catch (ComponentException ce) {
responseFormat = componentsUtils.getResponseFormat(ce);
- handleAuditing(AuditingActionEnum.ARTIFACT_DELETE, parent, parentId, user, null, null,
- artifactId, responseFormat, ComponentTypeEnum.RESOURCE, null);
+ handleAuditing(AuditingActionEnum.ARTIFACT_DELETE, parent, parentId, user, null, null, artifactId, responseFormat,
+ ComponentTypeEnum.RESOURCE, null);
return Either.right(responseFormat);
- }
- catch (StorageException se) {
+ } catch (StorageException se) {
responseFormat = componentsUtils.getResponseFormat(se);
- handleAuditing(AuditingActionEnum.ARTIFACT_DELETE, parent, parentId, user, null, null,
- artifactId, responseFormat, ComponentTypeEnum.RESOURCE, null);
+ handleAuditing(AuditingActionEnum.ARTIFACT_DELETE, parent, parentId, user, null, null, artifactId, responseFormat,
+ ComponentTypeEnum.RESOURCE, null);
return Either.right(responseFormat);
} finally {
handleLockingAndCommit(parent, shouldLock, inTransaction, operationSucceeded);
}
}
- private ArtifactDefinition handleDeleteInternal(
- String parentId, String artifactId,
- ComponentTypeEnum componentType, Component parent
- ) {
+ private ArtifactDefinition handleDeleteInternal(String parentId, String artifactId, ComponentTypeEnum componentType, Component parent) {
NodeTypeEnum parentType = convertParentType(componentType);
log.debug("Going to find the artifact {} on the component {}", artifactId, parent.getUniqueId());
-
- Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes =
- findArtifact(artifactId, parent, parentId, componentType);
+ Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = findArtifact(artifactId, parent, parentId,
+ componentType);
if (getArtifactRes.isRight()) {
- log.debug("Failed to find the artifact {} belonging to {} on the component {}",
- artifactId, parentId, parent.getUniqueId());
+ log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, parent.getUniqueId());
throw new ByActionStatusComponentException(getArtifactRes.right().value(), artifactId);
}
ArtifactDefinition foundArtifact = getArtifactRes.left().value().getLeft();
ComponentInstance foundInstance = getArtifactRes.left().value().getRight();
-
String esId = foundArtifact.getEsId();
- Either<Boolean, StorageOperationStatus> needClone = ifTrue(StringUtils.isNotEmpty(esId), () -> forEach(
- artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, parentType),
- b -> log.debug("handleDelete: clone is needed for deleting {} held by {} in component {} {}? {}",
- foundArtifact.getArtifactName(), parentType, parent.getUniqueId(), parent.getName(), b)
- ));
-
+ Either<Boolean, StorageOperationStatus> needClone = ifTrue(StringUtils.isNotEmpty(esId),
+ () -> forEach(artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, parentType), b -> log
+ .debug("handleDelete: clone is needed for deleting {} held by {} in component {} {}? {}", foundArtifact.getArtifactName(), parentType,
+ parent.getUniqueId(), parent.getName(), b)));
boolean needToClone = false;
// TODO: This should not be done, but in order to keep this refactoring small, we stop here.
+
// Remove this block once the above refactoring is merged.
- if(needClone.isLeft()) {
+ if (needClone.isLeft()) {
needToClone = needClone.left().value();
} else {
throw new StorageException(needClone.right().value(), foundArtifact.getArtifactDisplayName());
}
-
boolean isNeedToDeleteArtifactFromDB =
- componentType == ComponentTypeEnum.RESOURCE_INSTANCE &&
- isArtifactOnlyResourceInstanceArtifact(foundArtifact, parent, parentId);
-
+ componentType == ComponentTypeEnum.RESOURCE_INSTANCE && isArtifactOnlyResourceInstanceArtifact(foundArtifact, parent, parentId);
boolean isDuplicated = false;
-
ArtifactDataDefinition updatedArtifact = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needToClone);
isDuplicated = updatedArtifact.getDuplicated();
-
if (!needToClone && !isDuplicated && isNeedToDeleteArtifactFromDB) {
log.debug("Going to delete the artifact {} from the database. ", artifactId);
CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
@@ -1349,7 +1254,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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);
+ 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());
@@ -1373,17 +1279,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return foundArtifact;
}
- public static <R> Either<Boolean, R> ifTrue(boolean predicate, Supplier<Either<Boolean, R>> ifTrue) {
- return predicate ? ifTrue.get() : Either.left(false);
- }
-
- public static <L, R> Either<L, R> forEach(Either<L, R> e, Consumer<L> c) {
- return e.left().map(l -> {
- c.accept(l);
- return l;
- });
- }
-
private boolean isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) {
Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstanceById(instanceId);
if (!componentInstanceOpt.isPresent()) {
@@ -1399,20 +1294,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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();
+ 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 (MapUtils.isNotEmpty(artifacts)) {
- Optional<String> op = artifacts.keySet()
- .stream()
- .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
- .findAny();
+ Optional<String> op = artifacts.keySet().stream().filter(a -> a.equals(foundArtifact.getArtifactLabel())).findAny();
if (op.isPresent()) {
return false;
}
@@ -1430,8 +1319,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
group.getArtifacts().remove(artifactId);
isUpdated = true;
}
- if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid()
- .contains(foundArtifact.getArtifactUUID())) {
+ if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
isUpdated = true;
}
@@ -1443,29 +1331,27 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return updatedGroups;
}
- private List<GroupInstance> getUpdatedGroupInstances(
- String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances
- ) {
+ private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
if (CollectionUtils.isEmpty(groupInstances)) {
return new ArrayList<>();
}
// TODO: A defensive copy should be created here for groupInstances. Modifying
+
// arguments (aka output arguments) is overall a bad practice as explained in
+
// Clean Code by Robert Martin.
- // A better approach would be to use Lenses.
+ // A better approach would be to use Lenses.
return groupInstances.stream().filter(gi -> {
- boolean groupInstanceArtifactRemoved = gi.getGroupInstanceArtifacts() != null &&
- gi.getGroupInstanceArtifacts().remove(artifactId);
- boolean groupInstanceArtifactUUIDRemoved = gi.getGroupInstanceArtifactsUuid() != null &&
- gi.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
-
+ boolean groupInstanceArtifactRemoved = gi.getGroupInstanceArtifacts() != null && gi.getGroupInstanceArtifacts().remove(artifactId);
+ boolean groupInstanceArtifactUUIDRemoved =
+ gi.getGroupInstanceArtifactsUuid() != null && gi.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
return groupInstanceArtifactRemoved || groupInstanceArtifactUUIDRemoved;
}).collect(Collectors.toList());
}
- private ArtifactDataDefinition deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
-
+ 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();
String componentId = component.getUniqueId();
@@ -1474,12 +1360,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
resetMandatoryArtifactFields(foundArtifact);
result = artifactToscaOperation.updateArtifactOnGraph(component, foundArtifact, parentType, artifactId, instanceId, true, true);
- }
- else if (cloneIsNeeded) {
+ } else if (cloneIsNeeded) {
log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
result = artifactToscaOperation.deleteArtifactWithCloningOnGraph(componentId, foundArtifact, parentType, instanceId, false);
- }
- else {
+ } else {
log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
}
@@ -1489,33 +1373,29 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return result.left().value();
}
- private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
-
+ private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId,
+ Component fetchedContainerComponent,
+ String parentId,
+ ComponentTypeEnum componentType) {
Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
Map<String, ArtifactDefinition> artifacts = new HashMap<>();
ComponentInstance foundInstance = null;
if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
- Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances()
- .stream()
- .filter(i -> i.getUniqueId()
- .equals(parentId))
- .findFirst();
+ Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances().stream()
+ .filter(i -> i.getUniqueId().equals(parentId)).findFirst();
if (!componentInstanceOpt.isPresent()) {
result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
- }
- else {
+ } else {
foundInstance = componentInstanceOpt.get();
fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
}
- }
- else {
+ } else {
fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
}
if (result == null) {
if (artifacts.containsKey(artifactId)) {
result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
- }
- else {
+ } else {
result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
}
}
@@ -1525,28 +1405,22 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
Map<String, ArtifactDefinition> currArtifacts;
if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
- currArtifacts = component.getDeploymentArtifacts()
- .values()
- .stream()
- .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, i -> i));
+ currArtifacts = component.getDeploymentArtifacts().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(ArtifactDataDefinition::getUniqueId, Function.identity()));
+ currArtifacts = component.getArtifacts().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(ArtifactDataDefinition::getUniqueId, Function.identity()));
+ currArtifacts = component.getToscaArtifacts().values().stream()
+ .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity()));
if (MapUtils.isNotEmpty(currArtifacts)) {
artifacts.putAll(currArtifacts);
}
@@ -1556,19 +1430,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
Map<String, ArtifactDefinition> currArtifacts;
if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
- currArtifacts = instance.getDeploymentArtifacts()
- .values()
- .stream()
- .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity()));
+ currArtifacts = instance.getDeploymentArtifacts().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(ArtifactDataDefinition::getUniqueId, Function.identity()));
+ currArtifacts = instance.getArtifacts().values().stream()
+ .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity()));
if (MapUtils.isNotEmpty(currArtifacts)) {
artifacts.putAll(currArtifacts);
}
@@ -1621,10 +1491,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return error;
}
- private ArtifactDefinition handleDownload(String componentId, String artifactId, 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()) {
throw new StorageException(artifactById.right().value());
}
@@ -1635,25 +1504,21 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return artifactDefinition;
}
- private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, String operationName,
+ private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation,
+ ArtifactDefinition artifactInfo, String operationName,
ComponentTypeEnum componentType) {
-
String artifactLabel = artifactInfo.getArtifactLabel();
- if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel()
- .isEmpty())) {
- BeEcompErrorManager.getInstance()
- .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
+ if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) {
+ BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
log.debug("missing artifact logical name for component {}", componentId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
}
if (operation.isCreateOrLink() && !artifactInfo.getMandatory()) {
-
if (operationName != null) {
if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
log.debug("artifact label cannot be set {}", artifactLabel);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
- }
- else {
+ } else {
artifactLabel = operationName;
}
}
@@ -1663,22 +1528,19 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
artifactInfo.setArtifactDisplayName(displayName);
-
if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
log.debug("Invalid format form Artifact label : {}", artifactLabel);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
-
if (artifactLabel.isEmpty()) {
log.debug("missing normalized artifact logical name for component {}", componentId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
}
-
if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String
- .valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
+ return Either.right(componentsUtils
+ .getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
}
if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
log.debug("Non unique Artifact label : {}", artifactLabel);
@@ -1686,7 +1548,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
artifactInfo.setArtifactLabel(artifactLabel);
-
return Either.left(ActionStatus.OK);
}
@@ -1695,11 +1556,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
- }
- else {
+ } else {
artifacts = artifactToscaOperation.getArtifacts(componentId);
}
-
if (artifacts.isLeft()) {
for (String label : artifacts.left().value().keySet()) {
if (label.equals(artifactLabel)) {
@@ -1716,14 +1575,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
boolean validateArtifactNameUniqueness(String componentId, Component parentComponent, ArtifactDefinition artifactInfo,
ComponentTypeEnum componentType) {
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = getArtifacts(componentType,
- parentComponent, componentId, artifactInfo.getArtifactGroupType());
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = getArtifacts(componentType, parentComponent, componentId,
+ artifactInfo.getArtifactGroupType());
String artifactName = artifactInfo.getArtifactName();
- if (artifacts.isLeft() && Objects.nonNull(artifacts.left().value())){
- if (artifacts.left().value().values().stream()
- .anyMatch(ad -> artifactName.equals(ad.getArtifactName())
- //check whether it is the same artifact we hold (by label)
- && !artifactInfo.getArtifactLabel().equals(ad.getArtifactLabel()))){
+ if (artifacts.isLeft() && Objects.nonNull(artifacts.left().value())) {
+ if (artifacts.left().value().values().stream().anyMatch(ad -> artifactName.equals(ad.getArtifactName())
+ //check whether it is the same artifact we hold (by label)
+ && !artifactInfo.getArtifactLabel().equals(ad.getArtifactLabel()))) {
return false;
}
}
@@ -1735,61 +1593,47 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private boolean isUniqueArtifactNameInResourceInterfaces(String componentId, String artifactName, String artifactLabel) {
Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
- .getAllInterfacesOfResource(componentId, true, true);
-
- if (allInterfacesOfResource.isLeft()){
- return allInterfacesOfResource.left().value()
- .values()
- .stream().map(InterfaceDefinition :: getOperationsMap)
- .flatMap(map -> map.values().stream())
- .map(OperationDataDefinition::getImplementation)
- .filter(Objects::nonNull)
- .noneMatch(add -> artifactName.equals(add.getArtifactName())
- && !artifactLabel.equals(add.getArtifactLabel()));
+ .getAllInterfacesOfResource(componentId, true, true);
+ if (allInterfacesOfResource.isLeft()) {
+ return allInterfacesOfResource.left().value().values().stream().map(InterfaceDefinition::getOperationsMap)
+ .flatMap(map -> map.values().stream()).map(OperationDataDefinition::getImplementation).filter(Objects::nonNull)
+ .noneMatch(add -> artifactName.equals(add.getArtifactName()) && !artifactLabel.equals(add.getArtifactLabel()));
}
return true;
}
private boolean isUniqueLabelInResourceInterfaces(String componentId, String artifactLabel) {
Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
- .getAllInterfacesOfResource(componentId, true, true);
-
- if (allInterfacesOfResource.isLeft()){
- return allInterfacesOfResource.left().value()
- .values()
- .stream().map(InterfaceDefinition :: getOperationsMap)
- .flatMap(map -> map.values().stream())
- .map(OperationDataDefinition::getImplementation)
- .filter(Objects::nonNull)
- .noneMatch(add -> artifactLabel.equals(add.getArtifactLabel()));
+ .getAllInterfacesOfResource(componentId, true, true);
+ if (allInterfacesOfResource.isLeft()) {
+ return allInterfacesOfResource.left().value().values().stream().map(InterfaceDefinition::getOperationsMap)
+ .flatMap(map -> map.values().stream()).map(OperationDataDefinition::getImplementation).filter(Objects::nonNull)
+ .noneMatch(add -> artifactLabel.equals(add.getArtifactLabel()));
}
return true;
}
private Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(ComponentTypeEnum componentType, Component parentComponent,
- String componentId, ArtifactGroupTypeEnum artifactGroupType) {
+ String componentId,
+ ArtifactGroupTypeEnum artifactGroupType) {
Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse;
if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
artifactsResponse = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
- }
- else {
+ } else {
artifactsResponse = artifactToscaOperation.getArtifacts(componentId);
}
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 == x.getValue().getArtifactGroupType())
- .collect(Collectors.toMap(Entry::getKey, Entry::getValue)));
+ return Either.left(artifactsResponse.left().value().entrySet().stream().filter(x -> artifactGroupType == x.getValue().getArtifactGroupType())
+ .collect(Collectors.toMap(Entry::getKey, Entry::getValue)));
}
// ***************************************************************
-
- private Either<ArtifactDefinition, Operation> createArtifact(Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload,
- ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
-
+ 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");
@@ -1807,29 +1651,27 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
// set on graph object id of artifact in ES!
artifactInfo.setEsId(artifactData.getId());
-
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);
+ Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation
+ .updateInterfaceOperation(parentId, interfaceType, operationName, operation);
if (result.isRight()) {
throw new StorageException(result.right().value());
}
operationResult = Either.right(result.left().value());
- }
- else {
+ } else {
// information/deployment/api artifacts
NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
- Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArtifactToComponent(
- artifactInfo, parent, nodeType, true, instanceId);
+ Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation
+ .addArtifactToComponent(artifactInfo, parent, nodeType, true, instanceId);
if (result.isRight()) {
throw new StorageException(result.right().value());
}
ArtifactDefinition artifactDefinition = result.left().value();
artifactData.setId(artifactDefinition.getEsId());
operationResult = Either.left(artifactDefinition);
-
if (generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum) != StorageOperationStatus.OK) {
throw new StorageException(generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum));
}
@@ -1841,24 +1683,19 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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);
+ foundInstance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst()
+ .orElse(null);
}
return foundInstance;
}
private void validateDeploymentArtifact(final ArtifactDefinition artifactInfo, final Component component) {
final ComponentTypeEnum componentType = component.getComponentType();
- if (componentType != ComponentTypeEnum.RESOURCE &&
- componentType != ComponentTypeEnum.SERVICE &&
- componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
- log.debug("Invalid component type '{}' for artifact. "
- + "Expected Resource, Component or Resource Instance", componentType.getValue());
- throw new ByActionStatusComponentException(MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE,
- componentType.getValue(), "Service, Resource or ResourceInstance", componentType.getValue());
+ if (componentType != ComponentTypeEnum.RESOURCE && componentType != ComponentTypeEnum.SERVICE
+ && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
+ log.debug("Invalid component type '{}' for artifact. " + "Expected Resource, Component or Resource Instance", componentType.getValue());
+ throw new ByActionStatusComponentException(MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, componentType.getValue(),
+ "Service, Resource or ResourceInstance", componentType.getValue());
}
final String artifactType = artifactInfo.getArtifactType();
final ArtifactConfiguration artifactConfiguration = loadArtifactTypeConfig(artifactType).orElse(null);
@@ -1869,21 +1706,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (componentType == ComponentTypeEnum.RESOURCE || componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
final Resource resource = (Resource) component;
final ResourceTypeEnum resourceType = resource.getResourceType();
-
validateResourceType(resourceType, artifactInfo, artifactConfiguration.getResourceTypes());
}
-
validateArtifactExtension(artifactConfiguration, artifactInfo);
}
- private void validateHeatArtifact(final Component parentComponent, final String componentId,
- final ArtifactDefinition artifactDefinition) {
+ private void validateHeatArtifact(final Component parentComponent, final String componentId, final ArtifactDefinition artifactDefinition) {
final String artifactType = artifactDefinition.getArtifactType();
final ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.parse(artifactType);
if (artifactTypeEnum == null) {
return;
}
-
switch (artifactTypeEnum) {
case HEAT:
case HEAT_VOL:
@@ -1898,9 +1731,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
- private void setArtifactTimeout(final ArtifactDefinition newArtifactInfo,
- final ArtifactDefinition existingArtifactInfo) {
-
+ private void setArtifactTimeout(final ArtifactDefinition newArtifactInfo, final ArtifactDefinition existingArtifactInfo) {
final String artifactType = newArtifactInfo.getArtifactType();
final ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.parse(artifactType);
if (artifactTypeEnum == null) {
@@ -1926,7 +1757,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
@VisibleForTesting
- void validateDeploymentArtifactTypeIsLegalForParent(ArtifactDefinition artifactInfo, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
+ void validateDeploymentArtifactTypeIsLegalForParent(ArtifactDefinition artifactInfo, ArtifactTypeEnum artifactType,
+ Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
@@ -1937,14 +1769,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (artifactType == null) {
return Optional.empty();
}
- final List<ArtifactConfiguration> artifactConfigurationList =
- ConfigurationManager.getConfigurationManager().getConfiguration().getArtifacts();
+ final List<ArtifactConfiguration> artifactConfigurationList = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getArtifacts();
if (CollectionUtils.isEmpty(artifactConfigurationList)) {
return Optional.empty();
}
-
- return artifactConfigurationList.stream()
- .filter(artifactConfiguration -> artifactConfiguration.getType().equalsIgnoreCase(artifactType))
+ return artifactConfigurationList.stream().filter(artifactConfiguration -> artifactConfiguration.getType().equalsIgnoreCase(artifactType))
.findFirst();
}
@@ -1952,25 +1782,22 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
// extract heat parameters
if (artifactInfo.getPayloadData() != null) {
String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
- Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo
- .getArtifactType());
+ Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils
+ .getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo.getArtifactType());
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());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactType());
return Either.right(responseFormat);
- }
- else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
+ } else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
artifactInfo.setListHeatParameters(heatParameters.left().value());
}
}
return Either.left(true);
-
}
@VisibleForTesting
- void validateArtifactExtension(final ArtifactConfiguration artifactConfiguration,
- final ArtifactDefinition artifactDefinition) {
+ void validateArtifactExtension(final ArtifactConfiguration artifactConfiguration, final ArtifactDefinition artifactDefinition) {
final List<String> acceptedTypes = artifactConfiguration.getAcceptedTypes();
/*
* No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
@@ -1980,7 +1807,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
final String artifactName = artifactDefinition.getArtifactName();
final String fileExtension = FilenameUtils.getExtension(artifactName);
-
if (fileExtension == null || !acceptedTypes.contains(fileExtension.toLowerCase())) {
final String artifactType = artifactDefinition.getArtifactType();
log.debug("File extension \"{}\" is not allowed for artifact type \"{}\"", fileExtension, artifactType);
@@ -1989,18 +1815,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
@VisibleForTesting
- void validateHeatEnvDeploymentArtifact(final Component parentComponent, final String parentId,
- final ArtifactDefinition artifactInfo) {
+ void validateHeatEnvDeploymentArtifact(final Component parentComponent, final String parentId, final ArtifactDefinition artifactInfo) {
final Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<>();
final Wrapper<byte[]> payloadWrapper = new Wrapper<>();
-
validateYaml(artifactInfo);
validateHeatExist(parentComponent.getUniqueId(), parentId, heatMDWrapper, artifactInfo, parentComponent.getComponentType());
-
if (!heatMDWrapper.isEmpty()) {
fillArtifactPayload(payloadWrapper, heatMDWrapper.getInnerElement());
}
-
if (!heatMDWrapper.isEmpty()) {
validateEnvVsHeat(artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
}
@@ -2012,13 +1834,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (eitherArtifactData.isLeft()) {
byte[] data = eitherArtifactData.left().value().getDataAsArray();
payloadWrapper.setInnerElement(Base64.encodeBase64(data));
- }
- else {
+ } else {
log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
throw new StorageException(DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData.right().value()));
}
- }
- else {
+ } else {
payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
}
}
@@ -2028,13 +1848,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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> eitherHeatEnvProperties = ImportUtils
+ .findFirstToscaMapElement(heatEnvToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
if (eitherHeatEnvProperties.isRight()) {
log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
throw new ByActionStatusComponentException(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
}
- Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
+ 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");
@@ -2043,8 +1864,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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());
+ 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());
}
}
@@ -2059,28 +1882,25 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private void validateSingleDeploymentArtifactName(final String artifactName, final Component parentComponent) {
boolean artifactNameFound = false;
- final Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
- getDeploymentArtifacts(parentComponent, null).iterator();
-
+ final Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, null).iterator();
while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
artifactNameFound = artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName());
}
if (artifactNameFound) {
final ComponentTypeEnum componentType = parentComponent.getComponentType();
log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
- throw new ByActionStatusComponentException(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS,
- componentType.getValue(), parentComponent.getName(), artifactName);
+ throw new ByActionStatusComponentException(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, componentType.getValue(),
+ parentComponent.getName(), artifactName);
}
}
- private void validateHeatExist(String componentId, String parentRiId, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact,
- ComponentTypeEnum componentType) {
+ private void validateHeatExist(String componentId, String parentRiId, Wrapper<ArtifactDefinition> heatArtifactMDWrapper,
+ ArtifactDefinition heatEnvArtifact, ComponentTypeEnum componentType) {
final Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation
.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, componentId, componentType);
if (res.isRight()) {
throw new ByActionStatusComponentException(ActionStatus.MISSING_HEAT);
}
-
heatArtifactMDWrapper.setInnerElement(res.left().value());
}
@@ -2096,14 +1916,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
@VisibleForTesting
- void validateResourceType(final ResourceTypeEnum resourceType, final ArtifactDefinition artifactInfo,
- final List<String> typeList) {
+ void validateResourceType(final ResourceTypeEnum resourceType, final ArtifactDefinition artifactInfo, final List<String> typeList) {
if (CollectionUtils.isEmpty(typeList) || typeList.contains(resourceType.getValue())) {
return;
}
final String listToString = typeList.stream().collect(Collectors.joining(", "));
- throw new ByActionStatusComponentException(MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE,
- artifactInfo.getArtifactGroupType().getType(), listToString, resourceType.getValue());
+ throw new ByActionStatusComponentException(MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo.getArtifactGroupType().getType(),
+ listToString, resourceType.getValue());
}
@VisibleForTesting
@@ -2114,17 +1933,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
if (heatParameterType == null) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam
- .getType());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam.getType());
return Either.right(responseFormat);
}
-
StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
if (validateAndUpdateProperty != StorageOperationStatus.OK) {
log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam
- .getType(), heatParam.getName());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(status, artifactTypeStr, heatParam.getType(), heatParam.getName());
return Either.right(responseFormat);
}
}
@@ -2139,8 +1957,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
final List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
if (ComponentTypeEnum.RESOURCE == componentType && ciId != null) {
- final Either<ComponentInstance, ResponseFormat> getRI =
- getRIFromComponent(component, ciId, null, null, null);
+ final Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(component, ciId, null, null, null);
if (getRI.isRight()) {
return Collections.emptyList();
}
@@ -2163,73 +1980,61 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
log.error("artifact uniqid cannot be set ignoring");
}
artifactInfo.setUniqueId(null);
-
if (artifactInfo.getArtifactRef() != null) {
log.error("artifact ref cannot be set ignoring");
}
artifactInfo.setArtifactRef(null);
-
if (artifactInfo.getArtifactRepository() != null) {
log.error("artifact repository cannot be set ignoring");
}
artifactInfo.setArtifactRepository(null);
-
if (artifactInfo.getUserIdCreator() != null) {
log.error("creator uuid cannot be set ignoring");
}
artifactInfo.setArtifactCreator(user.getUserId());
-
if (artifactInfo.getUserIdLastUpdater() != null) {
log.error("userId of last updater cannot be set ignoring");
}
artifactInfo.setUserIdLastUpdater(user.getUserId());
-
if (artifactInfo.getCreatorFullName() != null) {
log.error("creator Full name cannot be set ignoring");
}
String fullName = user.getFirstName() + " " + user.getLastName();
artifactInfo.setUpdaterFullName(fullName);
-
if (artifactInfo.getUpdaterFullName() != null) {
log.error("updater Full name cannot be set ignoring");
}
artifactInfo.setUpdaterFullName(fullName);
-
if (artifactInfo.getCreationDate() != null) {
log.error("Creation Date cannot be set ignoring");
}
long time = System.currentTimeMillis();
artifactInfo.setCreationDate(time);
-
if (artifactInfo.getLastUpdateDate() != null) {
log.error("Last Update Date cannot be set ignoring");
}
artifactInfo.setLastUpdateDate(time);
-
if (artifactInfo.getEsId() != null) {
log.error("es id cannot be set ignoring");
}
artifactInfo.setEsId(null);
-
}
-
- private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
+ private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName,
+ String operationName) {
String id = artifactId;
if (artifactId == null || artifactId.isEmpty()) {
String uniqueId = null;
if (interfaceName != null && operationName != null) {
- uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo
- .getArtifactLabel());
- }
- else {
+ uniqueId = UniqueIdBuilder
+ .buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo.getArtifactLabel());
+ } else {
uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
}
artifactInfo.setUniqueId(uniqueId);
artifactInfo.setEsId(uniqueId);
id = uniqueId;
- }
- else {
+ } else {
artifactInfo.setUniqueId(artifactId);
artifactInfo.setEsId(artifactId);
}
@@ -2241,7 +2046,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
}
return Either.left(true);
-
}
@VisibleForTesting
@@ -2254,11 +2058,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
}
artifactInfo.setArtifactName(normalizeFileName);
-
if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
+ return Either.right(
+ componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
}
-
return Either.left(true);
}
@@ -2267,21 +2070,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
log.info("artifact type is missing operation ignored");
throw new ByActionStatusComponentException(ActionStatus.MISSING_ARTIFACT_TYPE);
}
-
if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
log.info("artifact type cannot be changed operation ignored");
throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
}
}
- private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
-
+ private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo,
+ ArtifactDefinition currentArtifact) {
if (Objects.nonNull(artifactInfo) && Objects.nonNull(currentArtifact)) {
if (artifactInfo.getArtifactGroupType() == null) {
artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
- } else if (!currentArtifact.getArtifactGroupType()
- .getType()
- .equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
+ } 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));
}
@@ -2289,126 +2089,93 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(artifactInfo);
}
- private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
-
+ private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact,
+ ArtifactGroupTypeEnum type) {
// on update if null add informational to current
if (currentArtifact.getArtifactGroupType() == null && type != null) {
currentArtifact.setArtifactGroupType(type);
}
-
if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
log.error("artifact uniqid cannot be set ignoring");
}
artifactInfo.setUniqueId(currentArtifact.getUniqueId());
-
- if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef()
- .equals(artifactInfo.getArtifactRef())) {
+ if (artifactInfo.getArtifactRef() != null && !currentArtifact.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())) {
+ if (artifactInfo.getArtifactRepository() != null && !currentArtifact.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())) {
+ if (artifactInfo.getUserIdCreator() != null && !currentArtifact.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())) {
+ if (artifactInfo.getArtifactCreator() != null && !currentArtifact.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())) {
+ if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.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())) {
+ if (artifactInfo.getCreatorFullName() != null && !currentArtifact.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())) {
+ if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.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())) {
+ if (artifactInfo.getCreationDate() != null && !currentArtifact.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())) {
+ if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate().equals(artifactInfo.getLastUpdateDate())) {
log.error("Last Update Date cannot be set ignoring");
}
long time = System.currentTimeMillis();
artifactInfo.setLastUpdateDate(time);
-
if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
log.error("es id cannot be set ignoring");
}
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())) {
+ if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi().equals(artifactInfo.getServiceApi())) {
log.debug("serviceApi cannot be set. ignoring.");
}
artifactInfo.setServiceApi(currentArtifact.getServiceApi());
-
if (artifactInfo.getArtifactGroupType() != null && currentArtifact.getArtifactGroupType() != artifactInfo.getArtifactGroupType()) {
log.debug("artifact group cannot be set. ignoring.");
}
artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
-
artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
-
- if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID()
- .isEmpty() && !currentArtifact.getArtifactUUID()
- .equals(artifactInfo.getArtifactUUID())) {
+ if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID().isEmpty() && !currentArtifact.getArtifactUUID()
+ .equals(artifactInfo.getArtifactUUID())) {
log.debug("artifact UUID cannot be set. ignoring.");
}
artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
-
- if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo
- .getHeatParameters()
- .isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
+ if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo.getHeatParameters().isEmpty()
+ && !currentArtifact.getHeatParameters().isEmpty()) {
checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
}
}
private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
-
Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
for (HeatParameterDefinition parameter : heatParameters) {
HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
-
if (currentParam != null) {
-
if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
parameter.setName(currentParam.getName());
}
- if (parameter.getDefaultValue() != null && !parameter.getDefaultValue()
- .equalsIgnoreCase(currentParam.getDefaultValue())) {
+ if (parameter.getDefaultValue() != null && !parameter.getDefaultValue().equalsIgnoreCase(currentParam.getDefaultValue())) {
log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
parameter.setDefaultValue(currentParam.getDefaultValue());
}
@@ -2416,12 +2183,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
parameter.setType(currentParam.getType());
}
- if (parameter.getDescription() != null && !parameter.getDescription()
- .equalsIgnoreCase(currentParam.getDescription())) {
+ if (parameter.getDescription() != null && !parameter.getDescription().equalsIgnoreCase(currentParam.getDescription())) {
log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
parameter.setDescription(currentParam.getDescription());
}
-
// check and set current value
if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
@@ -2432,7 +2197,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
-
Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<>();
for (HeatParameterDefinition param : currentParameters) {
currentParamsMap.put(param.getUniqueId(), param);
@@ -2446,14 +2210,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
}
artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
-
if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
}
if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
+ return Either
+ .right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
}
-
return Either.left(true);
}
@@ -2471,16 +2234,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String
- .valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION,
+ String.valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
}
artifactInfo.setDescription(description);
return Either.left(true);
}
private <T> Either<ArtifactDefinition, T> updateArtifactFlow(Component parent, String parentId, String artifactId,
- ArtifactDefinition artifactInfo, byte[] decodedPayload,
- ComponentTypeEnum componentType, AuditingActionEnum auditingAction) {
+ ArtifactDefinition artifactInfo, byte[] decodedPayload,
+ ComponentTypeEnum componentType, AuditingActionEnum auditingAction) {
DAOArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
if (artifactData == null) {
BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
@@ -2490,9 +2253,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
log.debug("Entry on graph is updated. Update artifact in ES");
// Changing previous and current artifactId for auditing
String currArtifactId = artifactInfo.getUniqueId();
-
NodeTypeEnum parentType = convertParentType(componentType);
-
if (decodedPayload == null) {
if (!artifactInfo.getMandatory() || artifactInfo.getEsId() != null) {
Either<DAOArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactInfo.getEsId());
@@ -2507,15 +2268,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
artifactInfo.setEsId(artifactInfo.getUniqueId());
artifactData.setId(artifactInfo.getUniqueId());
}
-
- Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArtifactOnResource(artifactInfo,
- parent, artifactId, parentType, parentId, true);
+ Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation
+ .updateArtifactOnResource(artifactInfo, parent, artifactId, parentType, parentId, true);
if (result.isRight()) {
throw new StorageException(result.right().value());
}
ArtifactDefinition artifactDefinition = result.left().value();
updateGeneratedIdInHeatEnv(parent, parentId, artifactId, artifactInfo, artifactDefinition, parentType);
-
StorageOperationStatus storageOperationStatus = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
if (storageOperationStatus != StorageOperationStatus.OK) {
throw new StorageException(storageOperationStatus);
@@ -2529,42 +2288,47 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(artifactDefinition);
}
- private String updateGeneratedIdInHeatEnv(Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, ArtifactDefinition artifactDefinition, NodeTypeEnum parentType) {
+ 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 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) {
+ 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)) {
+ 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();
+ 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);
+ artifactToscaOperation
+ .updateHeatEnvArtifactOnInstance(parentComponent, artifactEnvInfo, artifactId, artifactUniqueId, parentType, parentId);
} else {
- artifactToscaOperation.updateHeatEnvArtifact(parentComponent, artifactEnvInfo, artifactId, artifactUniqueId, parentType, parentId);
+ 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);
+ 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
@@ -2572,7 +2336,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
log.trace("Starting payload handling");
byte[] payload = artifactInfo.getPayloadData();
byte[] decodedPayload = null;
-
if (payload != null && payload.length != 0) {
// the generated artifacts were already decoded by the handler
decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
@@ -2581,11 +2344,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
return Either.right(responseFormat);
}
-
String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload);
artifactInfo.setArtifactChecksum(checkSum);
log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
-
// Specific payload validations of different types
Either<Boolean, ResponseFormat> result = Either.left(true);
if (isDeploymentArtifact(artifactInfo)) {
@@ -2593,18 +2354,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
String artifactType = artifactInfo.getArtifactType();
String fileExtension = GeneralUtility.getFilenameExtension(artifactInfo.getArtifactName());
PayloadTypeEnum payloadType = ArtifactTypeToPayloadTypeSelector.getPayloadType(artifactType, fileExtension);
-
final Optional<ResponseFormat> pmDictionaryError = validateIfPmDictionary(artifactType, decodedPayload);
if (pmDictionaryError.isPresent()) {
return Either.right(pmDictionaryError.get());
}
-
Either<Boolean, ActionStatus> isPayloadValid = payloadType.isValid(decodedPayload);
if (isPayloadValid.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(isPayloadValid.right().value(), artifactType);
return Either.right(responseFormat);
}
-
if (payloadType.isHeatRelated()) {
log.trace("Payload is heat related so going to extract heat parameters for artifact type {}", artifactType);
result = extractHeatParameters(artifactInfo);
@@ -2613,13 +2371,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (result.isRight()) {
return Either.right(result.right().value());
}
-
} // null/empty payload is normal if called from metadata update ONLY.
+
// The validation of whether this is metadata/payload update case is
+
// currently done separately
else {
if (!isArtifactMetadataUpdate) {
- log.debug("In artifact: {} Payload is missing.",artifactInfo.getArtifactName());
+ log.debug("In artifact: {} Payload is missing.", artifactInfo.getArtifactName());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
return Either.right(responseFormat);
}
@@ -2629,26 +2388,19 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
private Optional<ResponseFormat> validateIfPmDictionary(String artifactType, byte[] decodedPayload) {
- return new PMDictionaryValidator()
- .validateIfPmDictionary(artifactType, decodedPayload)
- .map(this::preparePmDictionaryResponse);
+ return new PMDictionaryValidator().validateIfPmDictionary(artifactType, decodedPayload).map(this::preparePmDictionaryResponse);
}
private ResponseFormat preparePmDictionaryResponse(String errorMessage) {
return componentsUtils.getResponseFormat(ActionStatus.INVALID_PM_DICTIONARY_FILE, errorMessage);
}
- public Either<ArtifactDefinition, ResponseFormat> deleteArtifactByInterface(
- String resourceId, String userUserId, String artifactId, boolean inTransaction) {
-
- return toscaOperationFacade
- .getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata)
- .right().map(componentsUtils.toResponseFormat())
+ public Either<ArtifactDefinition, ResponseFormat> deleteArtifactByInterface(String resourceId, String userUserId, String artifactId,
+ boolean inTransaction) {
+ return toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata).right().map(componentsUtils.toResponseFormat())
.left().bind(parentComponent -> {
User user = new User(userUserId);
- return handleDelete(resourceId, artifactId, user,
- parentComponent,
- false, inTransaction);
+ return handleDelete(resourceId, artifactId, user, parentComponent, false, inTransaction);
});
}
@@ -2656,10 +2408,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
Operation op = new Operation();
long time = System.currentTimeMillis();
op.setCreationDate(time);
-
String artifactName = artifactInfo.getArtifactName();
artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
-
op.setImplementation(artifactInfo);
op.setLastUpdateDate(time);
return op;
@@ -2672,46 +2422,37 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
// download by MSO
- public byte[] 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);
throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
}
-
// Normalizing artifact name
artifactName = ValidationUtils.normalizeFileName(artifactName);
-
// Resource validation
Resource resource = validateResourceNameAndVersion(resourceName, resourceVersion);
String resourceId = resource.getUniqueId();
-
// Service validation
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);
throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactName);
}
-
ArtifactDefinition deploymentArtifact = null;
-
for (ArtifactDefinition artifactDefinition : artifacts.values()) {
- if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName()
- .equals(artifactName)) {
+ if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName().equals(artifactName)) {
log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
deploymentArtifact = artifactDefinition;
break;
}
}
-
if (deploymentArtifact == null) {
log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactName);
}
-
// Downloading the artifact
ImmutablePair<String, byte[]> downloadArtifactEither = downloadArtifact(deploymentArtifact);
log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
@@ -2720,47 +2461,33 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
// download by MSO
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);
throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
}
-
// Normalizing artifact name
artifactName = ValidationUtils.normalizeFileName(artifactName);
-
// Service validation
Service service = validateServiceNameAndVersion(serviceName, serviceVersion);
-
// ResourceInstance validation
ComponentInstance resourceInstance = validateResourceInstance(service, resourceInstanceName);
-
Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
-
final String finalArtifactName = artifactName;
Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
-
- ArtifactDefinition deployableArtifact = artifacts==null ? null :
- artifacts.values().stream()
- .filter(filterArtifactByName)
- .findFirst()
- .orElse(null);
-
+ ArtifactDefinition deployableArtifact =
+ artifacts == null ? null : artifacts.values().stream().filter(filterArtifactByName).findFirst().orElse(null);
if (deployableArtifact == null) {
log.debug("Deployment artifact with name {} not found", artifactName);
throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
}
-
log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
ImmutablePair<String, byte[]> downloadArtifactEither = downloadArtifact(deployableArtifact);
-
log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
return downloadArtifactEither.getRight();
}
private ComponentInstance validateResourceInstance(Service service, String resourceInstanceName) {
-
List<ComponentInstance> riList = service.getComponentInstances();
for (ComponentInstance ri : riList) {
if (ri.getNormalizedName().equals(resourceInstanceName)) {
@@ -2771,7 +2498,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
private ComponentInstance validateResourceInstanceById(Component component, String resourceInstanceId) {
-
List<ComponentInstance> riList = component.getComponentInstances();
for (ComponentInstance ri : riList) {
if (ri.getUniqueId().equals(resourceInstanceId)) {
@@ -2782,20 +2508,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
private Service validateServiceNameAndVersion(String serviceName, String serviceVersion) {
-
- Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
+ Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade
+ .getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
if (serviceListBySystemName.isRight()) {
log.debug("Couldn't fetch any service with name {}", serviceName);
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceListBySystemName
- .right()
- .value(), ComponentTypeEnum.SERVICE), serviceName);
+ throw new ByActionStatusComponentException(
+ componentsUtils.convertFromStorageResponse(serviceListBySystemName.right().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);
throw new ByActionStatusComponentException(ActionStatus.SERVICE_NOT_FOUND, serviceName);
}
-
Service foundService = null;
for (Service service : serviceList) {
if (service.getVersion().equals(serviceVersion)) {
@@ -2804,59 +2528,53 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
break;
}
}
-
if (foundService == null) {
log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
- throw new ByActionStatusComponentException(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);
+ 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);
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(resourceListBySystemName.right().value()),
+ resourceName);
}
return resourceListBySystemName.left().value();
}
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);
+ 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);
throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
}
-
// Normalizing artifact name
final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
-
// Service validation
Service service = validateServiceNameAndVersion(serviceName, serviceVersion);
// Looking for deployment or tosca artifacts
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);
throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName);
}
-
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.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);
@@ -2864,8 +2582,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
log.debug(FOUND_DEPLOYMENT_ARTIFACT, normalizedArtifactName);
// Downloading the artifact
- ImmutablePair<String, byte[]> downloadArtifactEither = downloadArtifact(foundArtifactOptl
- .get());
+ ImmutablePair<String, byte[]> downloadArtifactEither = downloadArtifact(foundArtifactOptl.get());
log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
return downloadArtifactEither.getRight();
}
@@ -2883,21 +2600,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
}
-
return downloadArtifact(artifactDefinition);
}
- private Component validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
- String containerComponentType) {
-
- ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(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 Component, StorageOperationStatus> componentResult = toscaOperationFacade
- .getToscaFullElement(componentId);
-
+ Either<? extends Component, StorageOperationStatus> componentResult = toscaOperationFacade.getToscaFullElement(componentId);
if (componentResult.isRight()) {
- ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentForAudit == 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);
@@ -2906,22 +2620,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return componentResult.left().value();
}
- private void validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation) {
+ private void validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId,
+ ArtifactOperationInfo operation) {
if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD && !operation.ignoreLifecycleState()) {
try {
validateCanWorkOnComponent(component, userId);
- }catch (ComponentException e) {
+ } 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, e.getResponseFormat(),
- component.getComponentType(), null);
+ handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, e.getResponseFormat(), component.getComponentType(),
+ null);
throw e;
}
}
}
- private void 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.isNotDownload()) {
String role = user.getRole();
if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
@@ -2933,15 +2648,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
- private User 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{
+ try {
user = validateUserExists(userId);
- } catch(ByResponseFormatComponentException e){
+ } catch (ByResponseFormatComponentException e) {
ResponseFormat responseFormat = e.getResponseFormat();
handleComponentException(auditingAction, componentId, artifactId, responseFormat, componentType, userId);
throw e;
- } catch(ByActionStatusComponentException e){
+ } catch (ByActionStatusComponentException e) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
handleComponentException(auditingAction, componentId, artifactId, responseFormat, componentType, userId);
throw e;
@@ -2949,8 +2665,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return user;
}
- private void handleComponentException(AuditingActionEnum auditingAction, String componentId, String artifactId,
- ResponseFormat responseFormat, ComponentTypeEnum componentType, String userId){
+ private void handleComponentException(AuditingActionEnum auditingAction, String componentId, String artifactId, ResponseFormat responseFormat,
+ ComponentTypeEnum componentType, String userId) {
User user = new User();
user.setUserId(userId);
handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
@@ -2963,7 +2679,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
break;
case UPDATE:
- auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
+ auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API
+ : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
break;
case DELETE:
auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
@@ -2987,7 +2704,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
log.debug("Error when getting artifact from ES, error: {}", actionStatus);
throw new ByActionStatusComponentException(actionStatus, artifactDefinition.getArtifactDisplayName());
}
-
DAOArtifactData DAOArtifactData = artifactfromES.left().value();
byte[] data = DAOArtifactData.getDataAsArray();
if (data == null) {
@@ -3003,21 +2719,20 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return new DAOArtifactData(artifactInfo.getEsId(), artifactPayload);
}
- private void saveArtifactInCassandra(DAOArtifactData artifactData, Component parent, ArtifactDefinition artifactInfo,
- String currArtifactId, String prevArtifactId, AuditingActionEnum auditingAction, ComponentTypeEnum componentType) {
+ private void saveArtifactInCassandra(DAOArtifactData artifactData, Component parent, ArtifactDefinition artifactInfo, String currArtifactId,
+ String prevArtifactId, AuditingActionEnum auditingAction, ComponentTypeEnum componentType) {
CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
-
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 {
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), null, artifactInfo, prevArtifactId, currArtifactId, responseFormat,
+ componentType, null);
+ } else {
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);
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), null, artifactInfo, prevArtifactId, currArtifactId, responseFormat,
+ componentType, null);
throw new StorageException(resourceUploadStatus);
}
}
@@ -3052,66 +2767,57 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
-
- public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
+ 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) {
+ public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user,
+ ArtifactGroupTypeEnum groupType) {
ArtifactDefinition artifactInfo = new ArtifactDefinition();
-
String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
-
artifactInfo.setArtifactDisplayName(artifactName);
artifactInfo.setArtifactLabel(logicalName.toLowerCase());
artifactInfo.setArtifactType(artifactType);
artifactInfo.setDescription(artifactDescription);
artifactInfo.setArtifactGroupType(groupType);
nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
-
setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
-
return artifactInfo;
}
private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
String uniqueId = null;
-
if (resourceId != null) {
- uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel()
- .toLowerCase());
+ uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel().toLowerCase());
artifactInfo.setUniqueId(uniqueId);
}
artifactInfo.setUserIdCreator(user.getUserId());
String fullName = user.getFullName();
artifactInfo.setUpdaterFullName(fullName);
-
long time = System.currentTimeMillis();
-
artifactInfo.setCreatorFullName(fullName);
artifactInfo.setCreationDate(time);
-
artifactInfo.setLastUpdateDate(time);
artifactInfo.setUserIdLastUpdater(user.getUserId());
-
artifactInfo.setMandatory(true);
}
- public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) {
+ public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType,
+ ArtifactGroupTypeEnum groupType, String instanceId) {
return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
}
- public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, Component component, NodeTypeEnum parentType, String 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<DAOArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
-
byte[] payload = payloadStr.getBytes();
-
DAOArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
return Either.left(artifactData);
}
@@ -3120,51 +2826,53 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param artifactDefinition
* @return
*/
- public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, 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(component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
+ return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId,
+ shouldLock, inTransaction).left()
+ .bind(artifactDef -> updateArtifactOnGroupInstance(component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
}
- public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, Component component, String resourceInstanceName, User modifier,
- boolean shouldLock, boolean inTransaction, String instanceId) {
+ 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(component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
+ return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId,
+ shouldLock, inTransaction).left()
+ .bind(artifactDef -> updateArtifactOnGroupInstance(component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
}
@VisibleForTesting
- Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) {
+ 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();
+ Optional<ComponentInstance> findFirst = componentInstances.stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findFirst();
if (findFirst.isPresent()) {
ComponentInstance relevantInst = findFirst.get();
- List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst
- .getGroupInstances());
-
+ List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate,
+ relevantInst.getGroupInstances());
if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
updatedGroupInstances.forEach(gi -> {
gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
});
- Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, instanceId, updatedGroupInstances);
+ Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade
+ .updateGroupInstancesOnComponent(component, instanceId, updatedGroupInstances);
if (status.isRight()) {
log.debug(FAILED_UPDATE_GROUPS, component.getUniqueId());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils
- .convertFromStorageResponse(status.right()
- .value()), clonedBeforeGenerate.getArtifactDisplayName());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()),
+ clonedBeforeGenerate.getArtifactDisplayName());
return Either.right(responseFormat);
}
}
@@ -3181,11 +2889,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
sb.append("parameters:\n");
if (heatParameters != null) {
heatParameters.sort(Comparator.comparing(HeatParameterDataDefinition::getName));
-
List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
-
for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
-
String heatValue = heatParameterDefinition.getCurrentValue();
if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
heatValue = heatParameterDefinition.getDefaultValue();
@@ -3198,29 +2903,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (type != null) {
switch (type) {
case BOOLEAN:
- sb.append(" ")
- .append(heatParameterDefinition.getName())
- .append(":")
- .append(" ")
- .append(Boolean.parseBoolean(heatValue))
- .append("\n");
+ sb.append(" ").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");
+ sb.append(" ").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");
+ sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(heatValue).append("\n");
break;
default:
String value = heatValue;
@@ -3233,14 +2925,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
value = "\"" + value + "\"";
}
}
- sb.append(" ")
- .append(heatParameterDefinition.getName())
- .append(":")
- .append(" ")
- .append(value);
+ sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(value);
sb.append("\n");
break;
-
}
}
}
@@ -3249,18 +2936,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
empltyHeatValues.forEach(hv -> {
sb.append(" ").append(hv.getName()).append(":");
HeatParameterType type = HeatParameterType.isValidType(hv.getType());
- if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv
- .getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
+ if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv.getCurrentValue())
+ || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
sb.append(" \"\"").append("\n");
- }
- else {
+ } else {
sb.append(" ").append("\n");
}
});
}
}
sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
-
// DE265919 fix
return sb.toString().replaceAll("\\\\n", "\n");
}
@@ -3270,41 +2955,42 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param payload
* @return
*/
- 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,
- () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
-
- }
-
- 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, 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());
- if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition
- .getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
-
+ 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, () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
+ }
+
+ 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, 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());
+ if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0
+ || artifactDefinition.getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
Either<DAOArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
DAOArtifactData artifactData = null;
-
if (artifactDataRes.isLeft()) {
artifactData = artifactDataRes.left().value();
- }
- else {
+ } else {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
- .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
- ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
-
+ handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition,
+ artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE,
+ resourceInstanceName);
return Either.right(artifactDataRes.right().value());
}
String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray());
@@ -3324,127 +3010,111 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
DAOArtifactData = artifactfromES.left().value();
oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(DAOArtifactData.getDataAsArray());
- }
- else {
+ } else {
oldCheckSum = artifactDefinition.getArtifactChecksum();
-
}
Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
-
if (shouldLock) {
try {
lockComponent(component, "Update Artifact - lock resource: ");
- }catch (ComponentException e){
- handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition
- .getUniqueId(), e.getResponseFormat(), component.getComponentType(), null);
+ } catch (ComponentException e) {
+ handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null,
+ artifactDefinition.getUniqueId(), e.getResponseFormat(), component.getComponentType(), null);
throw e;
}
}
try {
if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
-
artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
- updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
- ,artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId, true);
- log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
- .getArtifactType(), artifactDefinition.getEsId());
+ updateArifactDefinitionStatus = artifactToscaOperation
+ .updateArtifactOnResource(artifactDefinition, component, 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()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
- .right()
- .value()), artifactDefinition.getArtifactDisplayName());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()),
+ artifactDefinition.getArtifactDisplayName());
log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
- handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
- .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
- ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
-
+ handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition,
+ artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE,
+ resourceInstanceName);
return Either.right(responseFormat);
}
- }
- else {
+ } else {
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,
- artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId, true);
-
+ log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(),
+ artifactDefinition.getEsId());
+ updateArifactDefinitionStatus = artifactToscaOperation
+ .updateArtifactOnResource(artifactDefinition, component, artifactDefinition.getUniqueId(), componentType.getNodeType(),
+ instanceId, true);
log.trace("Update Payload {}", artifactDefinition.getEsId());
}
if (updateArifactDefinitionStatus.isLeft()) {
-
artifactDefinition = updateArifactDefinitionStatus.left().value();
artifactData.setId(artifactDefinition.getUniqueId());
CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
-
if (saveArtifactStatus == CassandraOperationStatus.OK) {
if (!inTransaction) {
janusGraphDao.commit();
}
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,
- ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
-
- }
- else {
+ handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition,
+ artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE,
+ resourceInstanceName);
+ } else {
if (!inTransaction) {
janusGraphDao.rollback();
}
log.info("Failed to save artifact {}.", artifactData.getId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
- .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
- ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
-
+ handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition,
+ artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE,
+ resourceInstanceName);
return Either.right(responseFormat);
}
- }
- else {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
- .right()
- .value()), artifactDefinition.getArtifactDisplayName());
+ } else {
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()),
+ artifactDefinition.getArtifactDisplayName());
log.debug("Failed To update artifact {}", artifactData.getId());
- handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
- .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
- ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
-
+ handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition,
+ artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE,
+ resourceInstanceName);
return Either.right(responseFormat);
-
}
- }
- finally {
+ } finally {
if (shouldLock) {
- graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType()
- .getNodeType());
+ graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
}
}
}
-
return Either.left(artifactDefinition);
}
-
- public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
- return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef
- .getArtifactLabel(), artifactDef.getArtifactDisplayName(),
- artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters());
-
+ public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType,
+ List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
+ return this
+ .buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType,
+ artifactDef.getArtifactLabel(), artifactDef.getArtifactDisplayName(), artifactDef.getDescription(), artifactDef.getPayloadData(),
+ updatedRequiredArtifacts, artifactDef.getListHeatParameters());
}
- public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent,
- List<ArtifactTemplateInfo> updatedRequiredArtifacts, List<HeatParameterDefinition> heatParameters) {
-
+ public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType,
+ ArtifactGroupTypeEnum artifactGroupType, String label, String displayName,
+ String description, byte[] artifactContent,
+ List<ArtifactTemplateInfo> updatedRequiredArtifacts,
+ List<HeatParameterDefinition> heatParameters) {
Map<String, Object> json = new HashMap<>();
if (artifactId != null && !artifactId.isEmpty()) {
json.put(Constants.ARTIFACT_ID, artifactId);
}
-
json.put(Constants.ARTIFACT_NAME, artifactName);
json.put(Constants.ARTIFACT_TYPE, artifactType);
json.put(Constants.ARTIFACT_DESCRIPTION, description);
-
if (artifactContent != null) {
log.debug("payload is encoded. perform decode");
String encodedPayload = Base64.encodeBase64String(artifactContent);
@@ -3454,30 +3124,29 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
json.put(Constants.ARTIFACT_LABEL, label);
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(ArtifactTemplateInfo::getFileName)
- .collect(Collectors.toList()));
- json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>()
- : heatParameters);
+ : updatedRequiredArtifacts.stream().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<ArtifactDefinition, Operation> 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, false) : artifactInfo;
+ ArtifactDefinition artifactDefinitionFromJson =
+ artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class, false) : artifactInfo;
String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
- Either<ArtifactDefinition, Operation> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId,
- artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true);
-
+ Either<ArtifactDefinition, Operation> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE,
+ operation, artifactUniqueId, artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true);
return Either.left(uploadArtifactToService.left().value());
}
- 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) {
+ 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) {
validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
if (ArrayUtils.isNotEmpty(artifactInfo.getPayloadData())) {
@@ -3490,7 +3159,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return updateHeatEnvParamsAndMetadata(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5);
}
- private Either<ArtifactDefinition, Operation> updateHeatEnvParamsAndMetadata(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
+ 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()) {
@@ -3502,61 +3173,59 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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())) {
+ 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();
-
// 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()) {
throw new ByResponseFormatComponentException(uploadParamsValidationResult.right().value());
}
artifactInfo.setListHeatParameters(updatedHeatEnvParams);
}
-
- Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParameters(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType());
+ Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParameters(artifactInfo,
+ ArtifactTypeEnum.HEAT_ENV.getType());
if (validateAndConvertHeatParamers.isRight()) {
throw new ByResponseFormatComponentException(validateAndConvertHeatParamers.right().value());
}
-
if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
// fill reduced heat env parameters List for updating
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);
+ 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());
+ 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);
+ updateHeatMetaDataIfNeeded(componentId, user, auditingAction, componentType, parent, ri, artifactInfo);
StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
if (error != StorageOperationStatus.OK) {
throw new StorageException(error);
}
-
return Either.left(currArtifact);
}
- private void
- updateHeatMetaDataIfNeeded(String componentId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent, ComponentInstance resourceInstance, ArtifactDefinition updatedHeatEnvArtifact) {
+ 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);
+ Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, resourceInstance, componentId, heatArtifactId,
+ auditingAction, user);
if (getArtifactRes.isRight()) {
throw new ByResponseFormatComponentException(getArtifactRes.right().value());
}
@@ -3564,16 +3233,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (isUpdateHeatMetaDataNeeded(updatedHeatEnvArtifact, heatArtifactToUpdate)) {
validateHeatMetaData(updatedHeatEnvArtifact);
updateHeatMetadataFromHeatEnv(updatedHeatEnvArtifact, heatArtifactToUpdate);
- Either<ArtifactDefinition, StorageOperationStatus> updateArtifactRes = artifactToscaOperation.updateArtifactOnResource(heatArtifactToUpdate, parent,
- heatArtifactToUpdate.getUniqueId(), componentType.getNodeType(), componentId, false);
-
+ 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());
+ updateGeneratedIdInHeatEnvOnInstance(resourceInstance, parent, heatArtifactId, heatArtifactToUpdate, artifactDefinition,
+ componentType.getNodeType());
+ StorageOperationStatus error = generateCustomizationUUIDOnGroupInstance(resourceInstance, artifactDefinition.getUniqueId(),
+ parent.getUniqueId());
if (error != StorageOperationStatus.OK) {
throw new StorageException(error);
}
@@ -3599,7 +3270,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
origHeat.setTimeout(updatedHeatEnv.getTimeout());
}
- private boolean replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) {
+ 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) {
@@ -3624,24 +3296,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
- private Either<ArtifactDefinition, Operation> updateHeatParams(String componentId, ArtifactDefinition artifactEnvInfo, AuditingActionEnum auditingAction, Component parent,
- ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, boolean needToUpdateGroup) {
+ 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<DAOArtifactData, CassandraOperationStatus> artifactFromES = artifactCassandraDao.getArtifact(esArtifactId);
if (artifactFromES.isRight()) {
StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromES.right().value());
throw new StorageException(storageResponse, currHeatArtifact.getArtifactDisplayName());
}
-
DAOArtifactData DAOArtifactData = artifactFromES.left().value();
ArtifactDefinition updatedHeatArt = currHeatArtifact;
List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<>();
-
if (CollectionUtils.isNotEmpty(updatedHeatEnvParams) && CollectionUtils.isNotEmpty(currentHeatEnvParams)) {
//TODO: improve complexity - currently N^2
String paramName;
@@ -3655,8 +3326,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
if (!paramType.getValidator().isValid(updatedParamValue, null)) {
- throw new ByActionStatusComponentException(ActionStatus.INVALID_HEAT_PARAMETER_VALUE,
- ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
+ 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);
@@ -3666,9 +3337,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
if (!newHeatEnvParams.isEmpty()) {
currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
- Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArtifactOnResource(
- currHeatArtifact, parent, currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId, true);
-
+ 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());
throw new StorageException(operationStatus.right().value());
@@ -3677,26 +3348,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (!updatedHeatArt.getDuplicated() || DAOArtifactData.getId() == null) {
DAOArtifactData.setId(updatedHeatArt.getEsId());
}
- saveArtifactInCassandra(DAOArtifactData, parent, artifactEnvInfo, currentHeatId, updatedHeatArt
- .getUniqueId(), auditingAction, componentType);
+ 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, artifactEnvInfo, currentHeatId, updatedHeatArt
- .getUniqueId(), componentType.getNodeType(), componentId);
- }
- else {
+ updateHeatEnvArtifact = artifactToscaOperation
+ .updateHeatEnvArtifact(parent, artifactEnvInfo, currentHeatId, updatedHeatArt.getUniqueId(), componentType.getNodeType(),
+ componentId);
+ } else {
//TODO Andrey check if componentId = parent.getUniqeId
- updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, parent, componentType
- .getNodeType());
-
+ updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, parent, componentType.getNodeType());
}
if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
- ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo,
- updateHeatEnvArtifact.left().value(), parent);
+ ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact.left().value(), parent);
if (result != ActionStatus.OK) {
throw new ByActionStatusComponentException(result);
}
@@ -3707,7 +3375,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return insideEither;
}
-
private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
StorageOperationStatus error = StorageOperationStatus.OK;
log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
@@ -3715,34 +3382,33 @@ 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);
}
return error;
-
}
- public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
- String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
-
+ public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent,
+ User user, ArtifactDefinition artifactInfo,
+ String artifactId, ComponentTypeEnum componentType,
+ String riName,
+ List<HeatParameterDefinition> currentHeatEnvParams,
+ List<HeatParameterDefinition> updatedHeatEnvParams,
+ String currArtifactName) {
if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
- .getArtifactName(), currArtifactName);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactName(), currArtifactName);
handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
return Either.right(responseFormat);
}
-
for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
String paramName = uploadedHeatParam.getName();
boolean isExistsInHeat = false;
for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
-
isExistsInHeat = true;
uploadedHeatParam.setType(currHeatParam.getType());
uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
@@ -3753,14 +3419,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
if (!isExistsInHeat) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
- handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType,
+ riName);
return Either.right(responseFormat);
}
}
return Either.left(updatedHeatEnvParams);
}
- private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
+ private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId,
+ AuditingActionEnum auditingAction, User user) {
ResponseFormat responseFormat = null;
List<ComponentInstance> ris = component.getComponentInstances();
for (ComponentInstance ri : ris) {
@@ -3774,7 +3442,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.right(responseFormat);
}
- private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
+ private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId,
+ AuditingActionEnum auditingAction, User user) {
ResponseFormat responseFormat = null;
Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
for (ArtifactDefinition artifact : rtifactsMap.values()) {
@@ -3783,8 +3452,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
- handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri
- .getName());
+ handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE,
+ ri.getName());
return Either.right(responseFormat);
}
@@ -3792,14 +3461,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
ArtifactDefinition ret;
if (eitherArtifact.isLeft()) {
ret = eitherArtifact.left().value();
- }
- else {
+ } else {
ret = eitherArtifact.right().value().getImplementationArtifact();
}
return ret;
}
- public byte[] downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo) {
+ 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());
@@ -3814,10 +3483,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param artifactUUID
* @return
*/
- public byte[] downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid,
- String resourceInstanceName, String artifactUUID) {
+ public byte[] downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
+ String artifactUUID) {
ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName);
-
if (resourceInstance != null) {
return downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, resourceInstance.getName());
} else {
@@ -3837,24 +3505,19 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @return
*/
public ArtifactDefinition uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType,
- String componentUuid, ResourceCommonInfo resourceCommonInfo, ArtifactOperationInfo operation) {
+ 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, ActionStatus> getComponentRes =
- fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
-
+ Either<ComponentMetadataData, ActionStatus> getComponentRes = fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
ComponentMetadataDataDefinition componentMetadataDataDefinition = getComponentRes.left().value().getMetadataDataDefinition();
componentId = componentMetadataDataDefinition.getUniqueId();
String componentName = componentMetadataDataDefinition.getName();
-
- if (!componentMetadataDataDefinition
- .getState()
- .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ if (!componentMetadataDataDefinition.getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
component = checkoutParentComponent(componentType, componentId, userId);
if (component != null) {
componentId = component.getUniqueId();
@@ -3862,9 +3525,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
resourceCommonInfo.setResourceName(componentName);
-
- actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo,
- origMd5, data, null, null, null, null);
+ actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null,
+ null);
return actionResult.left().value();
}
@@ -3879,43 +3541,30 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param operation
* @return
*/
- public ArtifactDefinition uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
- ArtifactOperationInfo operation) {
+ 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;
String origMd5 = request.getHeader(Constants.MD5_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
-
ImmutablePair<Component, ComponentInstance> componentRiPair = null;
-
- Either<ComponentMetadataData, ActionStatus> getComponentRes =
- fetchLatestComponentMetadataOrThrow(componentType, componentUuid, resourceInstanceName);
- if (!getComponentRes.left()
- .value()
- .getMetadataDataDefinition()
- .getState()
- .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
- component = checkoutParentComponent(componentType, getComponentRes.left()
- .value()
- .getMetadataDataDefinition()
- .getUniqueId(), userId);
+ Either<ComponentMetadataData, ActionStatus> getComponentRes = fetchLatestComponentMetadataOrThrow(componentType, componentUuid,
+ resourceInstanceName);
+ if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId);
}
if (component == null) {
componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName);
- }
- else {
+ } else {
componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName);
}
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));
-
+ actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5,
+ data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
return actionResult.left().value();
}
@@ -3928,29 +3577,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param componentUuid
* @param artifactUUID
* @param resourceCommonInfo
- * @param operation TODO
+ * @param operation TODO
* @return
*/
- public ArtifactDefinition updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
- ResourceCommonInfo resourceCommonInfo, ArtifactOperationInfo operation) {
+ 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 ;
+ String artifactId;
ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
String origMd5 = request.getHeader(Constants.MD5_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
-
- Either<ComponentMetadataData, ActionStatus> getComponentRes =
- fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
+ Either<ComponentMetadataData, ActionStatus> getComponentRes = fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
-
- if (!getComponentRes.left()
- .value()
- .getMetadataDataDefinition()
- .getState()
- .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
component = checkoutParentComponent(componentType, componentId, userId);
if (component != null) {
componentId = component.getUniqueId();
@@ -3959,14 +3602,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
resourceCommonInfo.setResourceName(componentName);
artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, componentId, componentType);
- actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo,
- origMd5, data, null, null, null, null);
+ 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());
+ log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult.right().value());
}
-
return actionResult.left().value();
}
@@ -3982,9 +3622,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param operation TODO
* @return
*/
- public ArtifactDefinition 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) {
Either<ArtifactDefinition, Operation> actionResult;
Component component = null;
String componentInstanceId;
@@ -3992,37 +3631,27 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
String artifactId;
String origMd5 = request.getHeader(Constants.MD5_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
-
ImmutablePair<Component, ComponentInstance> componentRiPair = null;
- Either<ComponentMetadataData, ActionStatus> getComponentRes =
- fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
- if (!getComponentRes.left()
- .value()
- .getMetadataDataDefinition()
- .getState()
- .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
- component = checkoutParentComponent(componentType, getComponentRes.left()
- .value()
- .getMetadataDataDefinition()
- .getUniqueId(), userId);
+ Either<ComponentMetadataData, ActionStatus> getComponentRes = fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
+ if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId);
}
if (component == null) {
componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName);
- }
- else {
+ } else {
componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName);
}
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));
+ 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){
+ private Either<ArtifactDefinition, ResponseFormat> updateOperationArtifact(String componentId, String interfaceType, String operationUuid,
+ ArtifactDefinition artifactInfo) {
Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId);
if (componentStorageOperationStatusEither.isRight()) {
StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
@@ -4030,28 +3659,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
}
Component storedComponent = componentStorageOperationStatusEither.left().value();
-
- Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceType(storedComponent, interfaceType);
- if(!optionalInterface.isPresent()) {
+ Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils
+ .getInterfaceDefinitionFromComponentByInterfaceType(storedComponent, interfaceType);
+ if (!optionalInterface.isPresent()) {
log.debug("Failed to get resource interface for resource Id {}", componentId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceType));
}
-
//fetch the operation from storage
InterfaceDefinition gotInterface = optionalInterface.get();
Map<String, Operation> operationsMap = gotInterface.getOperationsMap();
- Optional<Operation> optionalOperation = operationsMap.values()
- .stream()
- .filter(o -> o.getUniqueId().equals(operationUuid))
- .findFirst();
+ Optional<Operation> optionalOperation = operationsMap.values().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);
return Either.right(responseFormat);
}
-
Operation operation = optionalOperation.get();
- ArtifactDefinition implementationArtifact = operation.getImplementationArtifact();
+ ArtifactDefinition implementationArtifact = operation.getImplementationArtifact();
implementationArtifact.setArtifactUUID(artifactInfo.getArtifactUUID());
implementationArtifact.setUniqueId(artifactInfo.getUniqueId());
implementationArtifact.setArtifactName(artifactInfo.getArtifactName());
@@ -4062,15 +3686,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
implementationArtifact.setEsId(artifactInfo.getEsId());
operation.setImplementation(implementationArtifact);
gotInterface.setOperationsMap(operationsMap);
- Either<List<InterfaceDefinition>, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither =
- interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), Collections.singletonList(gotInterface));
- if (interfaceDefinitionStorageOperationStatusEither.isRight()){
+ Either<List<InterfaceDefinition>, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither = interfaceOperation
+ .updateInterfaces(storedComponent.getUniqueId(), Collections.singletonList(gotInterface));
+ if (interfaceDefinitionStorageOperationStatusEither.isRight()) {
StorageOperationStatus storageOperationStatus = interfaceDefinitionStorageOperationStatusEither.right().value();
- ActionStatus actionStatus =
- componentsUtils.convertFromStorageResponseForDataType(storageOperationStatus);
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForDataType(storageOperationStatus);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
}
-
return Either.left(artifactInfo);
}
@@ -4085,129 +3707,107 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param operation
* @return
*/
- public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnInterfaceOperationByResourceUUID(
- String data, HttpServletRequest request, ComponentTypeEnum componentType,
- String componentUuid, String interfaceUUID, String operationUUID, String artifactUUID,
- ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
+ public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnInterfaceOperationByResourceUUID(String data, HttpServletRequest request,
+ ComponentTypeEnum componentType,
+ String componentUuid, String interfaceUUID,
+ String operationUUID, String artifactUUID,
+ ResourceCommonInfo resourceCommonInfo,
+ ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
String componentId = null;
ArtifactDefinition existingArtifactInfo = null;
String interfaceName = null;
-
ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
String origMd5 = request.getHeader(Constants.MD5_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
-
- Either<ComponentMetadataData, ActionStatus> getComponentRes =
- fetchLatestComponentMetadata(componentType, componentUuid)
- .right().map(as -> {
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(as));
- return as;
- });
-
+ Either<ComponentMetadataData, ActionStatus> getComponentRes = fetchLatestComponentMetadata(componentType, componentUuid).right().map(as -> {
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(as));
+ return as;
+ });
if (errorWrapper.isEmpty()) {
componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
- if (!getComponentRes.left()
- .value()
- .getMetadataDataDefinition()
- .getState()
- .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
Component component = checkoutParentComponent(componentType, componentId, userId);
if (component != null) {
componentId = component.getUniqueId();
componentName = component.getName();
}
-
}
resourceCommonInfo.setResourceName(componentName);
}
-
- if(errorWrapper.isEmpty()){
+ if (errorWrapper.isEmpty()) {
Either<String, ResponseFormat> interfaceNameEither = fetchInterfaceName(componentId, interfaceUUID);
if (interfaceNameEither.isRight()) {
errorWrapper.setInnerElement(interfaceNameEither.right().value());
- }
- else {
+ } else {
interfaceName = interfaceNameEither.left().value();
}
-
- if(errorWrapper.isEmpty()){
+ if (errorWrapper.isEmpty()) {
Either<Component, StorageOperationStatus> toscaComponentEither = toscaOperationFacade.getToscaElement(componentId);
if (toscaComponentEither.isRight()) {
StorageOperationStatus status = toscaComponentEither.right().value();
log.debug("Could not fetch component with type {} and id {}. Status is {}. ", componentType, componentId, status);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
}
-
if (errorWrapper.isEmpty()) {
NodeTypeEnum parentType = convertParentType(componentType);
- final List<ArtifactDefinition> existingDeploymentArtifacts =
- getDeploymentArtifacts(toscaComponentEither.left().value(),null);
- for (ArtifactDefinition artifactDefinition: existingDeploymentArtifacts){
- if(artifactInfo.getArtifactName().equalsIgnoreCase(artifactDefinition.getArtifactName())){
+ final List<ArtifactDefinition> existingDeploymentArtifacts = getDeploymentArtifacts(toscaComponentEither.left().value(), null);
+ for (ArtifactDefinition artifactDefinition : existingDeploymentArtifacts) {
+ if (artifactInfo.getArtifactName().equalsIgnoreCase(artifactDefinition.getArtifactName())) {
existingArtifactInfo = artifactDefinition;
break;
}
}
- if(existingArtifactInfo != null){
+ if (existingArtifactInfo != null) {
return updateOperationArtifact(componentId, interfaceName, operationUUID, existingArtifactInfo);
}
}
}
}
-
if (errorWrapper.isEmpty()) {
- updateArtifactResult = handleArtifactRequestAndFlatten(componentId, userId, componentType, operation,
- artifactUUID, artifactInfo, origMd5, data, interfaceName, operationUUID);
+ updateArtifactResult = handleArtifactRequestAndFlatten(componentId, userId, componentType, operation, artifactUUID, artifactInfo, origMd5,
+ data, interfaceName, operationUUID);
} else {
updateArtifactResult = Either.right(errorWrapper.getInnerElement());
}
-
return updateArtifactResult;
}
- private Either<ArtifactDefinition, ResponseFormat> handleArtifactRequestAndFlatten(
- String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation,
- String artifactId, ArtifactDefinition artifactInfo, String origMd5, String originData, String interfaceName,
- String operationName) {
+ private Either<ArtifactDefinition, ResponseFormat> handleArtifactRequestAndFlatten(String componentId, String userId,
+ ComponentTypeEnum componentType,
+ ArtifactOperationInfo operation, String artifactId,
+ ArtifactDefinition artifactInfo, String origMd5,
+ String originData, String interfaceName,
+ String operationName) {
try {
- return handleArtifactRequest(componentId, userId, componentType, operation,
- artifactId, artifactInfo, origMd5, originData, interfaceName,
- operationName, null, null)
- .right().map(op -> {
- log.debug("Unexpected value returned while calling handleArtifactRequest: {}", op);
- return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- });
+ return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName,
+ operationName, null, null).right().map(op -> {
+ log.debug("Unexpected value returned while calling handleArtifactRequest: {}", op);
+ return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ });
} catch (ComponentException e) {
return Either.right(e.getResponseFormat());
}
}
- private Either<ComponentMetadataData, ActionStatus> fetchLatestComponentMetadataOrThrow(
- ComponentTypeEnum componentType, String componentUuid
- ) {
+ private Either<ComponentMetadataData, ActionStatus> fetchLatestComponentMetadataOrThrow(ComponentTypeEnum componentType, String componentUuid) {
return fetchLatestComponentMetadataOrThrow(componentType, componentUuid, componentUuid);
}
- private Either<ComponentMetadataData, ActionStatus> fetchLatestComponentMetadataOrThrow(
- ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName
- ) {
+ private Either<ComponentMetadataData, ActionStatus> fetchLatestComponentMetadataOrThrow(ComponentTypeEnum componentType, String componentUuid,
+ String resourceInstanceName) {
return fetchLatestComponentMetadata(componentType, componentUuid).right().map(as -> {
throw new ByActionStatusComponentException(as, resourceInstanceName);
});
}
- private Either<ComponentMetadataData, ActionStatus> fetchLatestComponentMetadata(
- ComponentTypeEnum componentType, String componentUuid
- ) {
- return toscaOperationFacade
- .getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true)
- .right().map(sos -> {
- log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, sos);
- return componentsUtils.convertFromStorageResponse(sos, componentType);
- });
+ private Either<ComponentMetadataData, ActionStatus> fetchLatestComponentMetadata(ComponentTypeEnum componentType, String componentUuid) {
+ return toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true).right().map(sos -> {
+ log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, sos);
+ return componentsUtils.convertFromStorageResponse(sos, componentType);
+ });
}
private Either<String, ResponseFormat> fetchInterfaceName(String componentId, String interfaceUUID) {
@@ -4218,10 +3818,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
}
Component storedComponent = componentStorageOperationStatusEither.left().value();
-
Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils
.getInterfaceDefinitionFromComponentByInterfaceId(storedComponent, interfaceUUID);
- if(!optionalInterface.isPresent()) {
+ if (!optionalInterface.isPresent()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceUUID));
}
return Either.left(optionalInterface.get().getType());
@@ -4235,28 +3834,22 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param componentUuid
* @param artifactUUID
* @param resourceCommonInfo
- * @param operation TODO
+ * @param operation TODO
* @return
*/
- public ArtifactDefinition deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo,
+ public ArtifactDefinition deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid,
+ String artifactUUID, ResourceCommonInfo resourceCommonInfo,
ArtifactOperationInfo operation) {
-
Either<ArtifactDefinition, Operation> actionResult;
Component component;
- String componentId ;
+ String componentId;
String artifactId;
String origMd5 = request.getHeader(Constants.MD5_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
-
- Either<ComponentMetadataData, ActionStatus> getComponentRes =
- fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
+ Either<ComponentMetadataData, ActionStatus> getComponentRes = fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
- if (!getComponentRes.left()
- .value()
- .getMetadataDataDefinition()
- .getState()
- .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
component = checkoutParentComponent(componentType, componentId, userId);
if (component != null) {
componentId = component.getUniqueId();
@@ -4280,10 +3873,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param operation TODO
* @return
*/
- public ArtifactDefinition 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) {
Either<ArtifactDefinition, Operation> actionResult;
Component component = null;
String componentInstanceId;
@@ -4292,30 +3883,20 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
String origMd5 = request.getHeader(Constants.MD5_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
ImmutablePair<Component, ComponentInstance> componentRiPair = null;
- Either<ComponentMetadataData, ActionStatus> getComponentRes =
- fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
- if (!getComponentRes.left()
- .value()
- .getMetadataDataDefinition()
- .getState()
- .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
- component = checkoutParentComponent(componentType, getComponentRes.left()
- .value()
- .getMetadataDataDefinition()
- .getUniqueId(), userId);
+ Either<ComponentMetadataData, ActionStatus> getComponentRes = fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
+ if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId);
}
if (component == null) {
componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName);
- }
- else {
+ } else {
componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName);
}
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));
+ actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5,
+ null, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
return actionResult.left().value();
}
@@ -4323,41 +3904,28 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
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);
+ foundArtifact = instance.getDeploymentArtifacts().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);
+ foundArtifact = instance.getArtifacts().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());
throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID);
- }
- else {
+ } else {
artifactId = foundArtifact.getUniqueId();
}
return artifactId;
}
@SuppressWarnings("unchecked")
- public ArtifactDefinition createHeatEnvPlaceHolder(List<ArtifactDefinition> createdArtifacts, ArtifactDefinition heatArtifact,
- String envType, String parentId, NodeTypeEnum parentType,
- String parentName, User user, Component component,
+ 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();
+ Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getDeploymentResourceInstanceArtifacts();
if (deploymentResourceArtifacts == null) {
log.debug("no deployment artifacts are configured for generated artifacts");
throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
@@ -4367,10 +3935,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
log.debug("no env type {} are configured for generated artifacts", envType);
throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
}
-
String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
- ArtifactDefinition createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user
- .getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
+ ArtifactDefinition createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user.getUserId(),
+ ArtifactGroupTypeEnum.DEPLOYMENT, true);
ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder;
artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId());
artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
@@ -4384,16 +3951,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (parentType != NodeTypeEnum.ResourceInstance) {
String checkSum = artifactToscaOperation.sortAndCalculateChecksumForHeatParameters(heatArtifact.getHeatParameters());
artifactHeatEnv.setArtifactChecksum(checkSum);
- Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component, parentType, parentId);
+ Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component,
+ parentType, parentId);
if (addHeatEnvArtifact.isRight()) {
log.debug("failed to create heat env artifact on resource instance");
- throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact
- .right()
- .value(), false), "", null));
+ throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(
+ componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact.right().value(), false), "", null));
}
heatEnvPlaceholder = createArtifactPlaceHolder;
- }
- else {
+ } else {
heatEnvPlaceholder = artifactHeatEnv;
artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion());
setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder);
@@ -4404,10 +3970,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
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);
+ new ResourceCommonInfo(parentName, componentType.getValue()), ResourceVersionInfo.newBuilder().build(),
+ ResourceVersionInfo.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(), null, heatEnvPlaceholder, null);
return heatEnvPlaceholder;
}
@@ -4433,8 +3997,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (name == null) {
name = heatArtifact.getArtifactLabel();
fileName = name + "." + envExtension;
- }
- else {
+ } else {
fileName = name.replaceAll("." + heatExtension, "." + envExtension);
}
heatEnvArtifact.setArtifactName(fileName);
@@ -4449,7 +4012,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
- public List<ArtifactDefinition> handleArtifactsForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
+ 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<>();
@@ -4460,8 +4024,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
uploadedArtifacts.add(result.left().value());
}
} catch (ComponentException e) {
- log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, component
- .getName(), e.getResponseFormat());
+ log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, component.getName(), e.getResponseFormat());
if (operation.isCreateOrLink()) {
vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
}
@@ -4470,27 +4033,28 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return uploadedArtifacts;
}
- public Either<ArtifactDefinition, Operation> handleLoadedArtifact(Component component, User user, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction,
- ComponentTypeEnum componentType, ArtifactDefinition artifactDefinition) {
+ public Either<ArtifactDefinition, Operation> handleLoadedArtifact(Component component, User user, ArtifactOperationInfo operation,
+ boolean shouldLock, boolean inTransaction, ComponentTypeEnum componentType,
+ ArtifactDefinition artifactDefinition) {
AuditingActionEnum auditingAction = detectAuditingType(operation, "");
String componentId = component.getUniqueId();
String artifactId = artifactDefinition.getUniqueId();
Either<ArtifactDefinition, Operation> result;
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
//artifact validation
- artifactDefinition = validateArtifact(componentId, componentType, operation,
- artifactId, artifactDefinition, auditingAction, user,
- component, shouldLock, inTransaction);
+ 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);
+ 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);
+ 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);
+ auditingAction, user, component, true);
break;
case DELETE:
result = Either.left(handleDeleteInternal(componentId, artifactId, componentType, component));
@@ -4506,14 +4070,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
result = Either.left(handleLink(componentId, artifactDefinition, componentType, component));
break;
default:
- throw new UnsupportedOperationException("In ArtifactsBusinessLogic received illegal operation: " + operation.getArtifactOperationEnum());
+ 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) {
-
+ 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<>();
@@ -4524,12 +4090,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
for (ArtifactDefinition artifact : artifactsToHandle) {
originData = ArtifactUtils.buildJsonStringForCsarVfcArtifact(artifact);
origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData);
- actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact
- .getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
+ actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact.getUniqueId(),
+ artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
uploadedArtifacts.add(actionResult.left().value());
}
handleArtifactsResult = uploadedArtifacts;
- }catch (ComponentException e){
+ } catch (ComponentException e) {
if (operation.isCreateOrLink()) {
vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
}
@@ -4538,36 +4104,27 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return handleArtifactsResult;
}
- private ComponentInstance getRelatedComponentInstance(
- ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName
- ) {
+ private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName) {
String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
Option<Component> oComponent = Option.of(getComponentByUuid(componentType, componentUuid));
- return oComponent
- .toTry(componentNotFound(componentType, componentUuid))
- .flatMap(component -> findFirstMatching(component,
- ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)
- ).toTry(componentInstanceNotFound(componentType, resourceInstanceName, component))
- ).get();
+ return oComponent.toTry(componentNotFound(componentType, componentUuid)).flatMap(
+ component -> findFirstMatching(component, ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName))
+ .toTry(componentInstanceNotFound(componentType, resourceInstanceName, component))).get();
}
- private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(
- Component component, String resourceInstanceName
- ) {
+ private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName) {
String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
ComponentInstance componentInstance = findFirstMatching(component,
- ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)
- ).toTry(componentInstanceNotFound(component.getComponentType(), resourceInstanceName, component)).get();
+ ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName))
+ .toTry(componentInstanceNotFound(component.getComponentType(), resourceInstanceName, component)).get();
return new ImmutablePair<>(component, componentInstance);
}
- private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(
- ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName
- ) {
+ private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid,
+ String resourceInstanceName) {
Component component = getLatestComponentByUuid(componentType, componentUuid);
- ComponentInstance componentInstance = findFirstMatching(component,
- ci -> ci.getNormalizedName().equals(resourceInstanceName)
- ).toTry(componentInstanceNotFound(component.getComponentType(), resourceInstanceName, component)).get();
+ ComponentInstance componentInstance = findFirstMatching(component, ci -> ci.getNormalizedName().equals(resourceInstanceName))
+ .toTry(componentInstanceNotFound(component.getComponentType(), resourceInstanceName, component)).get();
return new ImmutablePair<>(component, componentInstance);
}
@@ -4578,35 +4135,21 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
};
}
- private Supplier<Throwable> componentInstanceNotFound(
- ComponentTypeEnum componentType, String resourceInstanceName, Component component
- ) {
+ private Supplier<Throwable> componentInstanceNotFound(ComponentTypeEnum componentType, String resourceInstanceName, Component component) {
return () -> {
log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
- return new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
- resourceInstanceName,
+ return new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName,
RESOURCE_INSTANCE, componentType.getValue(), component.getName());
};
}
- private static Option<ComponentInstance> findFirstMatching(Component component, Predicate<ComponentInstance> filter) {
- return Option.ofOptional(component.getComponentInstances()
- .stream()
- .filter(filter)
- .findFirst());
- }
-
private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, String componentName) {
-
ImmutablePair<String, byte[]> downloadArtifact;
List<ArtifactDefinition> artifactsList = null;
ArtifactDefinition deploymentArtifact;
if (artifacts != null && !artifacts.isEmpty()) {
- artifactsList = artifacts.values()
- .stream()
- .filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID()
- .equals(artifactUUID))
- .collect(Collectors.toList());
+ artifactsList = artifacts.values().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);
@@ -4625,8 +4168,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
StorageOperationStatus status = getComponentRes.right().value();
log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status));
- }
- else {
+ } else {
component = getComponentRes.left().value();
}
return component;
@@ -4639,15 +4181,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
StorageOperationStatus status = getComponentRes.right().value();
log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status));
- }
- else {
+ } 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;
throw new ByActionStatusComponentException(status);
- }
- else {
+ } else {
component = value.get(0);
}
}
@@ -4668,41 +4208,39 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
throw new ByActionStatusComponentException(actionStatus, artifactUUID);
}
- artifacts = getArtifactsRes.left()
- .value()
- .values()
- .stream()
- .filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID()
- .equals(artifactUUID))
- .collect(Collectors.toList());
+ 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);
+ log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType,
+ parentId, actionStatus);
throw new ByActionStatusComponentException(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());
+ 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);
+ 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);
}
return latestArtifact.getUniqueId();
}
private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId) {
-
Component component = null;
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);
+ 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());
+ 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());
}
return checkoutRes.left().value();
@@ -4716,4 +4254,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
public List<ArtifactConfiguration> getConfiguration() {
return ConfigurationManager.getConfigurationManager().getConfiguration().getArtifacts();
}
+
+ public enum ArtifactOperationEnum {
+ CREATE, UPDATE, DELETE, DOWNLOAD, LINK;
+
+ public static boolean isCreateOrLink(ArtifactOperationEnum operation) {
+ return operation == CREATE || operation == LINK;
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java
index a44ed3c8c7..3c06e8b818 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
@@ -25,7 +24,6 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
-import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -36,7 +34,6 @@ import org.openecomp.sdc.be.model.AttributeDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentParametersView;
import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.InterfaceDefinition;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
@@ -64,20 +61,15 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
private static final String CREATE_ATTRIBUTE = "CreateAttribute";
private static final String UPDATE_ATTRIBUTE = "UpdateAttribute";
private static final String DELETE_ATTRIBUTE = "DeleteAttribute";
-
private static final Logger log = Logger.getLogger(AttributeBusinessLogic.class);
private static final String FAILED_TO_LOCK_COMPONENT_ERROR = "Failed to lock component {}. Error - {}";
@Autowired
- public AttributeBusinessLogic(IElementOperation elementDao,
- IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation,
- IGroupTypeOperation groupTypeOperation,
- InterfaceOperation interfaceOperation,
- InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
- ArtifactsOperations artifactToscaOperation) {
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
- interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+ public AttributeBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+ IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
+ InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+ artifactToscaOperation);
}
/**
@@ -88,20 +80,15 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
* @param userId
* @return AttributeDefinition if created successfully Or ResponseFormat
*/
- public Either<AttributeDefinition, ResponseFormat> createAttribute(String resourceId,
- AttributeDefinition newAttributeDef,
- String userId) {
+ public Either<AttributeDefinition, ResponseFormat> createAttribute(String resourceId, AttributeDefinition newAttributeDef, String userId) {
Either<AttributeDefinition, ResponseFormat> result = null;
validateUserExists(userId);
-
StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
if (lockResult != StorageOperationStatus.OK) {
- BeEcompErrorManager.getInstance()
- .logBeFailedLockObjectError(CREATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
+ BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
log.info(FAILED_TO_LOCK_COMPONENT_ERROR, resourceId, lockResult);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
-
try {
// Get the resource from DB
Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
@@ -109,40 +96,33 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
}
Resource resource = status.left().value();
-
// verify that resource is checked-out and the user is the last updater
if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
-
// verify attribute does not exist in resource
if (isAttributeExist(resource.getAttributes(), resourceId, newAttributeDef.getName())) {
- return Either.right(
- componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_ALREADY_EXIST, newAttributeDef.getName()));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_ALREADY_EXIST, newAttributeDef.getName()));
}
Map<String, DataTypeDefinition> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache);
// validate property default values
- Either<Boolean, ResponseFormat> defaultValuesValidation = validateAttributeDefaultValue(newAttributeDef,
- eitherAllDataTypes);
+ Either<Boolean, ResponseFormat> defaultValuesValidation = validateAttributeDefaultValue(newAttributeDef, eitherAllDataTypes);
if (defaultValuesValidation.isRight()) {
return Either.right(defaultValuesValidation.right().value());
}
-
handleAttributeDefaultValue(newAttributeDef, eitherAllDataTypes);
-
// add the new attribute to resource on graph
+
// need to get StorageOperationStatus and convert to ActionStatus from
+
// componentsUtils
- Either<AttributeDefinition, StorageOperationStatus> either = toscaOperationFacade
- .addAttributeOfResource(resource, newAttributeDef);
+ Either<AttributeDefinition, StorageOperationStatus> either = toscaOperationFacade.addAttributeOfResource(resource, newAttributeDef);
if (either.isRight()) {
- result = Either.right(componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()),
- resource.getName()));
+ result = Either
+ .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName()));
return result;
}
result = Either.left(either.left().value());
-
return result;
} finally {
commitOrRollback(result);
@@ -152,50 +132,43 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
private Either<Boolean, ResponseFormat> validateAttributeDefaultValue(final AttributeDefinition attributeDefinition,
final Map<String, DataTypeDefinition> dataTypes) {
-
if (!attributeOperation.isAttributeTypeValid(attributeDefinition)) {
- log.info("Invalid type for attribute '{}' type '{}'", attributeDefinition.getName(),
- attributeDefinition.getType());
+ log.info("Invalid type for attribute '{}' type '{}'", attributeDefinition.getName(), attributeDefinition.getType());
final ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, attributeDefinition
- .getType(), attributeDefinition.getName());
+ .getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, attributeDefinition.getType(), attributeDefinition.getName());
return Either.right(responseFormat);
}
String type = attributeDefinition.getType();
String innerType = null;
if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
- final ImmutablePair<String, Boolean> propertyInnerTypeValid = attributeOperation.isAttributeInnerTypeValid(
- attributeDefinition, dataTypes);
+ final ImmutablePair<String, Boolean> propertyInnerTypeValid = attributeOperation
+ .isAttributeInnerTypeValid(attributeDefinition, dataTypes);
innerType = propertyInnerTypeValid.getLeft();
if (!Boolean.TRUE.equals(propertyInnerTypeValid.getRight())) {
- log.info("Invalid inner type for attribute '{}' type '{}', dataTypeCount '{}'",
- attributeDefinition.getName(), attributeDefinition.getType(), dataTypes.size());
+ log.info("Invalid inner type for attribute '{}' type '{}', dataTypeCount '{}'", attributeDefinition.getName(),
+ attributeDefinition.getType(), dataTypes.size());
final ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType,
- attributeDefinition.getName());
+ .getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, attributeDefinition.getName());
return Either.right(responseFormat);
}
}
if (!attributeOperation.isAttributeDefaultValueValid(attributeDefinition, dataTypes)) {
- log.info("Invalid default value for attribute '{}' type '{}'", attributeDefinition.getName(),
- attributeDefinition.getType());
+ log.info("Invalid default value for attribute '{}' type '{}'", attributeDefinition.getName(), attributeDefinition.getType());
ResponseFormat responseFormat;
if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
- attributeDefinition.getName(), type, innerType,
- (String) attributeDefinition.get_default());
+ responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, attributeDefinition.getName(), type, innerType,
+ (String) attributeDefinition.get_default());
} else {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE,
- attributeDefinition.getName(), type, (String) attributeDefinition.get_default());
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, attributeDefinition.getName(), type,
+ (String) attributeDefinition.get_default());
}
return Either.right(responseFormat);
-
}
return Either.left(true);
}
- private void handleAttributeDefaultValue(final AttributeDefinition newAttributeDefinition,
- final Map<String, DataTypeDefinition> dataTypes) {
+ private void handleAttributeDefaultValue(final AttributeDefinition newAttributeDefinition, final Map<String, DataTypeDefinition> dataTypes) {
final ToscaPropertyType type = ToscaPropertyType.isValidType(newAttributeDefinition.getType());
final PropertyValueConverter converter = type.getConverter();
// get inner type
@@ -208,19 +181,16 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
}
}
if (newAttributeDefinition.get_default() != null) {
- newAttributeDefinition.set_default(converter
- .convert((String) newAttributeDefinition.get_default(), innerType, dataTypes));
+ newAttributeDefinition.set_default(converter.convert((String) newAttributeDefinition.get_default(), innerType, dataTypes));
}
}
private boolean isAttributeExist(List<AttributeDefinition> attributes, String resourceUid, String propertyName) {
boolean isExist = false;
if (attributes != null) {
- isExist = attributes.stream().anyMatch(
- p -> Objects.equals(p.getName(), propertyName) && Objects.equals(p.getOwnerId(), resourceUid));
+ isExist = attributes.stream().anyMatch(p -> Objects.equals(p.getName(), propertyName) && Objects.equals(p.getOwnerId(), resourceUid));
}
return isExist;
-
}
/**
@@ -229,27 +199,22 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
* @param userId
* @return
*/
- public Either<AttributeDefinition, ResponseFormat> getAttribute(String resourceId, String attributeId,
- String userId) {
-
+ public Either<AttributeDefinition, ResponseFormat> getAttribute(String resourceId, String attributeId, String userId) {
validateUserExists(userId);
-
// Get the resource from DB
Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
if (status.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
}
Resource resource = status.left().value();
-
List<AttributeDefinition> attributes = resource.getAttributes();
if (attributes == null) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, ""));
} else {
// verify attribute exist in resource
- Optional<AttributeDefinition> optionalAtt = attributes.stream().filter(att ->
- att.getUniqueId().equals(attributeId)).findAny();
- return optionalAtt.<Either<AttributeDefinition, ResponseFormat>>map(Either::left).orElseGet(() ->
- Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, "")));
+ Optional<AttributeDefinition> optionalAtt = attributes.stream().filter(att -> att.getUniqueId().equals(attributeId)).findAny();
+ return optionalAtt.<Either<AttributeDefinition, ResponseFormat>>map(Either::left)
+ .orElseGet(() -> Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, "")));
}
}
@@ -262,14 +227,12 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
* @param userId
* @return
*/
- public Either<AttributeDefinition, ResponseFormat> updateAttribute(String resourceId, String attributeId,
- AttributeDefinition newAttDef, String userId) {
+ public Either<AttributeDefinition, ResponseFormat> updateAttribute(String resourceId, String attributeId, AttributeDefinition newAttDef,
+ String userId) {
Either<AttributeDefinition, ResponseFormat> result = null;
-
StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
if (lockResult != StorageOperationStatus.OK) {
- BeEcompErrorManager.getInstance()
- .logBeFailedLockObjectError(UPDATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
+ BeEcompErrorManager.getInstance().logBeFailedLockObjectError(UPDATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
log.info(FAILED_TO_LOCK_COMPONENT_ERROR, resourceId, lockResult);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
@@ -280,55 +243,41 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
}
Resource resource = eitherResource.left().value();
-
// verify that resource is checked-out and the user is the last updater
if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
-
// verify attribute exist in resource
Either<AttributeDefinition, ResponseFormat> eitherAttribute = getAttribute(resourceId, attributeId, userId);
if (eitherAttribute.isRight()) {
return Either.right(eitherAttribute.right().value());
}
Map<String, DataTypeDefinition> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache);
-
// validate attribute default values
- Either<Boolean, ResponseFormat> defaultValuesValidation = validateAttributeDefaultValue(newAttDef,
- eitherAllDataTypes);
+ Either<Boolean, ResponseFormat> defaultValuesValidation = validateAttributeDefaultValue(newAttDef, eitherAllDataTypes);
if (defaultValuesValidation.isRight()) {
return Either.right(defaultValuesValidation.right().value());
}
-
// add the new property to resource on graph
- StorageOperationStatus validateAndUpdateAttribute = attributeOperation
- .validateAndUpdateAttribute(newAttDef, eitherAllDataTypes);
+ StorageOperationStatus validateAndUpdateAttribute = attributeOperation.validateAndUpdateAttribute(newAttDef, eitherAllDataTypes);
if (validateAndUpdateAttribute != StorageOperationStatus.OK) {
- log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId,
- validateAndUpdateAttribute);
+ log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, validateAndUpdateAttribute);
result = Either.right(componentsUtils
- .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(validateAndUpdateAttribute),
- resource.getName()));
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(validateAndUpdateAttribute), resource.getName()));
}
-
- Either<AttributeDefinition, StorageOperationStatus> eitherAttUpdate = toscaOperationFacade
- .updateAttributeOfResource(resource, newAttDef);
-
+ Either<AttributeDefinition, StorageOperationStatus> eitherAttUpdate = toscaOperationFacade.updateAttributeOfResource(resource, newAttDef);
if (eitherAttUpdate.isRight()) {
- log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId,
- eitherAttUpdate.right().value());
- result = Either.right(componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(eitherAttUpdate.right().value()), resource.getName()));
+ log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, eitherAttUpdate.right().value());
+ result = Either.right(componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherAttUpdate.right().value()), resource.getName()));
return result;
}
-
result = Either.left(eitherAttUpdate.left().value());
return result;
} finally {
commitOrRollback(result);
graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
}
-
}
/**
@@ -339,21 +288,15 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
* @param userId
* @return
*/
- public Either<AttributeDefinition, ResponseFormat> deleteAttribute(String resourceId, String attributeId,
- String userId) {
-
+ public Either<AttributeDefinition, ResponseFormat> deleteAttribute(String resourceId, String attributeId, String userId) {
Either<AttributeDefinition, ResponseFormat> result = null;
-
validateUserExists(userId);
-
StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
if (lockResult != StorageOperationStatus.OK) {
- BeEcompErrorManager.getInstance()
- .logBeFailedLockObjectError(DELETE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
+ BeEcompErrorManager.getInstance().logBeFailedLockObjectError(DELETE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
log.info(FAILED_TO_LOCK_COMPONENT_ERROR, resourceId, lockResult);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
-
try {
// Get the resource from DB
Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(resourceId);
@@ -361,30 +304,23 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
}
Resource resource = eitherResource.left().value();
-
// verify that resource is checked-out and the user is the last updater
if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
-
// verify attribute exist in resource
- Either<AttributeDefinition, ResponseFormat> eitherAttributeExist = getAttribute(resourceId, attributeId,
- userId);
+ Either<AttributeDefinition, ResponseFormat> eitherAttributeExist = getAttribute(resourceId, attributeId, userId);
if (eitherAttributeExist.isRight()) {
return Either.right(eitherAttributeExist.right().value());
}
String attributeName = eitherAttributeExist.left().value().getName();
-
// delete attribute of resource from graph
- StorageOperationStatus eitherAttributeDelete = toscaOperationFacade
- .deleteAttributeOfResource(resource, attributeName);
+ StorageOperationStatus eitherAttributeDelete = toscaOperationFacade.deleteAttributeOfResource(resource, attributeName);
if (eitherAttributeDelete != StorageOperationStatus.OK) {
- result = Either.right(componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherAttributeDelete),
- resource.getName()));
+ result = Either
+ .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherAttributeDelete), resource.getName()));
return result;
}
-
result = Either.left(eitherAttributeExist.left().value());
return result;
} finally {
@@ -393,10 +329,8 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
}
}
- public Either<List<AttributeDefinition>, ResponseFormat> getAttributesList(final String componentId,
- final String userId) {
+ public Either<List<AttributeDefinition>, ResponseFormat> getAttributesList(final String componentId, final String userId) {
validateUserExists(userId);
-
// Get the resource from DB
final ComponentParametersView filter = new ComponentParametersView(true);
filter.setIgnoreAttributes(false);
@@ -404,42 +338,62 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
if (status.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
}
-
return Either.left(status.left().value().getAttributes());
}
- public boolean isAttributeUsedByOperation(Component component,
- AttributeDefinition propertyDefinitionEntry) {
+ public boolean isAttributeUsedByOperation(Component component, AttributeDefinition propertyDefinitionEntry) {
// TODO - do we need this one
return false;
-
// // Component's own interfaces
+
// Map<String, InterfaceDefinition> interfaces = component.getInterfaces();
+
// if(MapUtils.isNotEmpty(interfaces)){
+
// for(Map.Entry<String, InterfaceDefinition> interfaceEntry : interfaces.entrySet()) {
+
// if (isPropertyExistInOperationInterface(propertyDefinitionEntry, interfaceEntry.getValue())) {
+
// return true;
+
// }
+
// }
+
// }
+
//
+
// // Component's child's component interfaces
+
// if(isPropertyUsedInCIInterfaces(component.getComponentInstancesInterfaces(), propertyDefinitionEntry)){
+
// return true;
+
// }
+
//
+
// // Component's parent's component interfaces
+
// Either<List<Component>, StorageOperationStatus> componentList = toscaOperationFacade.getParentComponents(component.getUniqueId());
+
// if(componentList.isLeft()){
+
// for (Component parentComponent : componentList.left().value()) {
+
// if(isPropertyUsedInCIInterfaces(parentComponent.getComponentInstancesInterfaces(), propertyDefinitionEntry)){
+
// return true;
+
// }
+
// }
+
// }
+
//
+
// return false;
}
-
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java
index a640de0be7..fbfeaa5320 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java
@@ -19,7 +19,6 @@
* Modifications copyright (c) 2019 Nokia
* ================================================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import static org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR;
@@ -101,7 +100,6 @@ import org.springframework.beans.factory.annotation.Autowired;
public abstract class BaseBusinessLogic {
private static final String FAILED_TO_LOCK_COMPONENT_ERROR = "Failed to lock component {} error - {}";
-
private static final Logger log = Logger.getLogger(BaseBusinessLogic.class);
private static final String EMPTY_VALUE = null;
private static final String SCHEMA_DOESN_T_EXISTS_FOR_PROPERTY_OF_TYPE = "Schema doesn't exists for property of type {}";
@@ -127,12 +125,11 @@ public abstract class BaseBusinessLogic {
protected PolicyTypeOperation policyTypeOperation;
protected ArtifactsOperations artifactToscaOperation;
protected UserValidations userValidations;
-
DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
- protected BaseBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
- InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
+ protected BaseBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+ IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
+ InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
this.elementDao = elementDao;
this.groupOperation = groupOperation;
this.groupInstanceOperation = groupInstanceOperation;
@@ -142,6 +139,12 @@ public abstract class BaseBusinessLogic {
this.artifactToscaOperation = artifactToscaOperation;
}
+ @SafeVarargs
+ static <T extends Enum<T>> boolean enumHasValueFilter(String name, Function<String, T> enumGetter, T... enumValues) {
+ T enumFound = enumGetter.apply(name);
+ return Arrays.asList(enumValues).contains(enumFound);
+ }
+
@Autowired
public void setUserAdmin(UserBusinessLogic userAdmin) {
this.userAdmin = userAdmin;
@@ -226,11 +229,10 @@ public abstract class BaseBusinessLogic {
lockComponent(component.getUniqueId(), component, ecompErrorContext);
}
- protected boolean isVolumeGroup(List<String> artifactsInGroup,List <ArtifactDefinition> deploymentArtifacts) {
+ protected boolean isVolumeGroup(List<String> artifactsInGroup, List<ArtifactDefinition> deploymentArtifacts) {
for (String artifactId : artifactsInGroup) {
ArtifactDefinition artifactDef = ArtifactUtils.findArtifactInList(deploymentArtifacts, artifactId);
- if (artifactDef != null
- && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
+ if (artifactDef != null && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
return true;
}
}
@@ -238,14 +240,14 @@ public abstract class BaseBusinessLogic {
}
protected void lockComponent(Component component, boolean shouldLock, String ecompErrorContext) {
- if(shouldLock){
+ if (shouldLock) {
lockComponent(component.getUniqueId(), component, ecompErrorContext);
}
}
protected void lockComponent(String componentId, Component component, String ecompErrorContext) {
ActionStatus lock = lockElement(componentId, component, ecompErrorContext);
- if (lock!= ActionStatus.OK) {
+ if (lock != ActionStatus.OK) {
logAndThrowComponentException(lock, component.getUniqueId(), component.getName());
}
}
@@ -256,7 +258,7 @@ public abstract class BaseBusinessLogic {
}
}
- private ResponseFormat logAndThrowComponentException(ActionStatus status, String componentId, String name){
+ private ResponseFormat logAndThrowComponentException(ActionStatus status, String componentId, String name) {
log.debug(FAILED_TO_LOCK_COMPONENT_ERROR, componentId, status);
throw new ByActionStatusComponentException(status, name);
}
@@ -265,7 +267,6 @@ public abstract class BaseBusinessLogic {
ComponentTypeEnum componentType = component.getComponentType();
NodeTypeEnum nodeType = componentType.getNodeType();
StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponent(componentId, nodeType);
-
if (lockResourceStatus == StorageOperationStatus.OK) {
return ActionStatus.OK;
} else {
@@ -287,16 +288,18 @@ public abstract class BaseBusinessLogic {
}
// unlock resource
graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
+ } else {
+ log.debug("component is NULL");
}
- else log.debug("component is NULL");
}
protected void unlockComponent(boolean failed, Component component) {
unlockComponent(failed, component, false);
}
+
void unlockComponentById(boolean failed, String componentId) {
Either<Component, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(componentId);
- if(component.isLeft()) {
+ if (component.isLeft()) {
unlockComponent(failed, component.left().value(), false);
}
}
@@ -310,7 +313,6 @@ public abstract class BaseBusinessLogic {
}
}
-
ComponentTypeEnum validateComponentType(String componentType) {
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
if (componentTypeEnum == null) {
@@ -322,9 +324,9 @@ public abstract class BaseBusinessLogic {
}
Component validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView filter) {
-
- Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaElement(componentId, filter == null ? new ComponentParametersView() : filter);
- if(toscaElement.isRight()){
+ Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade
+ .getToscaElement(componentId, filter == null ? new ComponentParametersView() : filter);
+ if (toscaElement.isRight()) {
handleGetComponentError(componentId, componentType, toscaElement.right().value());
}
return validateComponentType(toscaElement.left().value(), componentType);
@@ -342,21 +344,24 @@ public abstract class BaseBusinessLogic {
Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll();
if (allDataTypesEither.isRight()) {
JanusGraphOperationStatus status = allDataTypesEither.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)));
+ BeEcompErrorManager.getInstance()
+ .logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status,
+ ErrorSeverity.ERROR);
+ throw new ByActionStatusComponentException(
+ componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)));
}
Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
String propertyType = property.getType();
String innerType = getInnerType(property);
// Specific Update Logic
- Either<Object, Boolean> isValid =
- propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true,
- innerType, allDataTypes);
+ Either<Object, Boolean> isValid = propertyOperation
+ .validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
String newValue = property.getValue();
if (isValid.isRight()) {
Boolean res = isValid.right().value();
if (Boolean.FALSE.equals(res)) {
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
+ DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
}
} else {
Object object = isValid.left().value();
@@ -367,7 +372,7 @@ public abstract class BaseBusinessLogic {
return newValue;
}
- <T extends PropertyDataDefinition> String getInnerType(T property){
+ <T extends PropertyDataDefinition> String getInnerType(T property) {
ToscaPropertyType type = ToscaPropertyType.isValidType(property.getType());
log.debug("#getInnerType - The type of the property {} is {}", property.getUniqueId(), property.getType());
String innerType = null;
@@ -389,35 +394,30 @@ public abstract class BaseBusinessLogic {
public void validateCanWorkOnComponent(Component component, String userId) {
ActionStatus actionStatus = ActionStatus.RESTRICTED_OPERATION;
// verify resource is not archived
- if (Boolean.TRUE.equals(component.isArchived())){
+ if (Boolean.TRUE.equals(component.isArchived())) {
actionStatus = ActionStatus.COMPONENT_IS_ARCHIVED;
throw new ByActionStatusComponentException(actionStatus, component.getName());
}
-
if (component.getLifecycleState() != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
log.debug("Component {} is not checked-out", component.getName());
throw new ByActionStatusComponentException(actionStatus);
}
-
// verify userId is not null
if (userId == null) {
log.debug("Current user userId is null");
throw new ByActionStatusComponentException(actionStatus);
}
-
// verify component last update user is the current user
String lastUpdaterUserId = component.getLastUpdaterUserId();
if (!userId.equals(lastUpdaterUserId)) {
log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}", lastUpdaterUserId, userId);
throw new ByActionStatusComponentException(actionStatus);
}
-
// verify resource is not deleted
if (Boolean.TRUE.equals(component.getIsDeleted())) {
log.debug("Component {} is marked as deleted", component.getUniqueId());
throw new ByActionStatusComponentException(actionStatus);
}
-
}
ComponentTypeEnum getComponentTypeByParentComponentType(ComponentTypeEnum parentComponentType) {
@@ -453,7 +453,8 @@ public abstract class BaseBusinessLogic {
String innerType = null;
if (!propertyOperation.isPropertyTypeValid(property)) {
log.info("Invalid type for property '{}' type '{}'", property.getName(), property.getType());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
return Either.right(responseFormat);
}
type = property.getType();
@@ -461,8 +462,10 @@ public abstract class BaseBusinessLogic {
ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, dataTypes);
innerType = propertyInnerTypeValid.getLeft();
if (Boolean.FALSE.equals(propertyInnerTypeValid.getRight())) {
- log.info("Invalid inner type for property '{}' type '{}', dataTypeCount '{}'", property.getName(), property.getType(), dataTypes.size());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
+ log.info("Invalid inner type for property '{}' type '{}', dataTypeCount '{}'", property.getName(), property.getType(),
+ dataTypes.size());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
return Either.right(responseFormat);
}
}
@@ -470,14 +473,13 @@ public abstract class BaseBusinessLogic {
log.info("Invalid default value for property '{}' type '{}'", property.getName(), property.getType());
ResponseFormat responseFormat;
if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType,
- property.getDefaultValue());
+ responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue());
} else {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type,
- property.getDefaultValue());
+ responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue());
}
return Either.right(responseFormat);
-
}
return Either.left(true);
}
@@ -487,15 +489,14 @@ public abstract class BaseBusinessLogic {
BeEcompErrorManager.getInstance().logInvalidInputError(errorContext, "invalid component type", ErrorSeverity.INFO);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
}
-
}
- protected void validateCanWorkOnComponent(String componentId, ComponentTypeEnum componentTypeEnum, String userId, Wrapper<ResponseFormat> errorWrapper) {
+ protected void validateCanWorkOnComponent(String componentId, ComponentTypeEnum componentTypeEnum, String userId,
+ Wrapper<ResponseFormat> errorWrapper) {
if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
log.info("Restricted operation for user {} on {} {}", userId, componentTypeEnum.getValue(), componentId);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
-
}
void validateComponentLock(String componentId, ComponentTypeEnum componentTypeEnum, Wrapper<ResponseFormat> errorWrapper) {
@@ -504,7 +505,6 @@ public abstract class BaseBusinessLogic {
log.debug("Failed to lock {} {}", componentTypeEnum.getValue(), componentId);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
}
-
}
protected ToscaPropertyType getType(String propertyType) {
@@ -525,7 +525,6 @@ public abstract class BaseBusinessLogic {
ComponentTypeEnum componentType = component.getComponentType();
NodeTypeEnum nodeType = componentType.getNodeType();
StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponentByName(name, nodeType);
-
if (lockResourceStatus == StorageOperationStatus.OK) {
return Either.left(true);
} else {
@@ -537,11 +536,10 @@ public abstract class BaseBusinessLogic {
}
}
- protected Component validateComponentExistsByFilter(String componentId, ComponentTypeEnum componentType, ComponentParametersView componentParametersView) {
- return toscaOperationFacade.getToscaElement(componentId, componentParametersView)
- .left()
- .on(err -> handleGetComponentError(componentId, componentType, err));
-
+ protected Component validateComponentExistsByFilter(String componentId, ComponentTypeEnum componentType,
+ ComponentParametersView componentParametersView) {
+ return toscaOperationFacade.getToscaElement(componentId, componentParametersView).left()
+ .on(err -> handleGetComponentError(componentId, componentType, err));
}
private Component handleGetComponentError(String componentId, ComponentTypeEnum componentType, StorageOperationStatus getComponentError) {
@@ -550,14 +548,8 @@ public abstract class BaseBusinessLogic {
throw new ByActionStatusComponentException(actionStatus, componentId);
}
- @SafeVarargs
- static <T extends Enum<T>> boolean enumHasValueFilter(String name, Function<String, T> enumGetter, T... enumValues) {
- T enumFound = enumGetter.apply(name);
- return Arrays.asList(enumValues).contains(enumFound);
- }
-
String validatePropValueBeforeCreate(IPropertyInputCommon property, String value, boolean isValidate,
- Map<String, DataTypeDefinition> allDataTypes) {
+ Map<String, DataTypeDefinition> allDataTypes) {
String propertyType = property.getType();
String updatedInnerType = updateInnerType(property);
Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, updatedInnerType, allDataTypes);
@@ -565,8 +557,7 @@ public abstract class BaseBusinessLogic {
if (isValid.isRight()) {
Boolean res = isValid.right().value();
if (Boolean.FALSE.equals(res)) {
- throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
- JanusGraphOperationStatus.ILLEGAL_ARGUMENT));
+ throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT));
}
} else {
Object object = isValid.left().value();
@@ -578,8 +569,7 @@ public abstract class BaseBusinessLogic {
log.trace("After validateAndUpdateRules. pair = {}", pair);
if (Boolean.FALSE.equals(pair.getRight())) {
BeEcompErrorManager.getInstance().logBeInvalidValueError(ADD_PROPERTY_VALUE, pair.getLeft(), property.getName(), propertyType);
- throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
- JanusGraphOperationStatus.ILLEGAL_ARGUMENT));
+ throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT));
}
return newValue;
}
@@ -603,20 +593,19 @@ public abstract class BaseBusinessLogic {
}
private void failOnIllegalArgument() {
- throw new ByActionStatusComponentException(
- componentsUtils.convertFromStorageResponse(
- DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
+ throw new ByActionStatusComponentException(componentsUtils
+ .convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
}
- public Either<Object, Boolean> validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> dataTypes) {
+ public Either<Object, Boolean> validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType,
+ Map<String, DataTypeDefinition> dataTypes) {
log.trace("Going to validate property value and its type. type = {}, value = {}", propertyType, value);
ToscaPropertyType type = getType(propertyType);
-
if (isValidate) {
-
if (type == null) {
DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
- ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes);
+ ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter
+ .validateAndUpdate(value, dataTypeDefinition, dataTypes);
if (Boolean.FALSE.equals(validateResult.right)) {
log.debug(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, propertyType);
return Either.right(false);
@@ -640,12 +629,11 @@ public abstract class BaseBusinessLogic {
return Either.left(convertedValue);
}
- private ImmutablePair<String, Boolean> validateAndUpdateRules(String propertyType, List<PropertyRule> rules, String innerType, Map<String, DataTypeDefinition> dataTypes, boolean isValidate) {
-
+ private ImmutablePair<String, Boolean> validateAndUpdateRules(String propertyType, List<PropertyRule> rules, String innerType,
+ Map<String, DataTypeDefinition> dataTypes, boolean isValidate) {
if (rules == null || rules.isEmpty()) {
return ImmutablePair.of(null, true);
}
-
for (PropertyRule rule : rules) {
String value = rule.getValue();
Either<Object, Boolean> updateResult = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, dataTypes);
@@ -663,7 +651,6 @@ public abstract class BaseBusinessLogic {
rule.setValue(newValue);
}
}
-
return ImmutablePair.of(null, true);
}
@@ -671,9 +658,7 @@ public abstract class BaseBusinessLogic {
if (isEmptyValue(value)) {
return true;
}
-
PropertyTypeValidator validator = type.getValidator();
-
return validator.isValid(value, innerType, dataTypes);
}
@@ -696,26 +681,22 @@ public abstract class BaseBusinessLogic {
throw new ByActionStatusComponentException(actionStatus, params);
}
- public <T extends ToscaDataDefinition> Either<List<T>, ResponseFormat> declareProperties(final String userId,
- final String componentId,
- final ComponentTypeEnum componentTypeEnum,
- final ComponentInstInputsMap componentInstInputsMap) {
+ public <T extends ToscaDataDefinition> Either<List<T>, ResponseFormat> declareProperties(final String userId, final String componentId,
+ final ComponentTypeEnum componentTypeEnum,
+ final ComponentInstInputsMap componentInstInputsMap) {
return Either.left(new ArrayList<>());
}
- public <T extends ToscaDataDefinition> Either<List<T>, ResponseFormat> declareAttributes(final String userId,
- final String componentId,
- final ComponentTypeEnum componentTypeEnum,
- final ComponentInstOutputsMap componentInstOutputsMap) {
+ public <T extends ToscaDataDefinition> Either<List<T>, ResponseFormat> declareAttributes(final String userId, final String componentId,
+ final ComponentTypeEnum componentTypeEnum,
+ final ComponentInstOutputsMap componentInstOutputsMap) {
return Either.left(new ArrayList<>());
}
public <T extends PropertyDataDefinition> List<PropertyConstraint> setInputConstraint(T inputDefinition) {
- if (StringUtils.isNotBlank(inputDefinition.getParentPropertyType())
- && StringUtils.isNotBlank(inputDefinition.getSubPropertyInputPath())) {
+ if (StringUtils.isNotBlank(inputDefinition.getParentPropertyType()) && StringUtils.isNotBlank(inputDefinition.getSubPropertyInputPath())) {
return setConstraint(inputDefinition);
}
-
return Collections.emptyList();
}
@@ -725,32 +706,22 @@ public abstract class BaseBusinessLogic {
if (inputPathArr.length > 1) {
inputPathArr = ArrayUtils.remove(inputPathArr, 0);
}
-
- Map<String, DataTypeDefinition> dataTypeDefinitionMap =
- applicationDataTypeCache.getAll().left().value();
-
+ Map<String, DataTypeDefinition> dataTypeDefinitionMap = applicationDataTypeCache.getAll().left().value();
String propertyType = inputDefinition.getParentPropertyType();
-
for (String anInputPathArr : inputPathArr) {
if (ToscaType.isPrimitiveType(propertyType)) {
- constraints.addAll(
- dataTypeDefinitionMap.get(propertyType).getConstraints());
+ constraints.addAll(dataTypeDefinitionMap.get(propertyType).getConstraints());
} else if (!ToscaType.isCollectionType(propertyType)) {
- propertyType = setConstraintForComplexType(dataTypeDefinitionMap, propertyType, anInputPathArr,
- constraints);
+ propertyType = setConstraintForComplexType(dataTypeDefinitionMap, propertyType, anInputPathArr, constraints);
}
}
-
return constraints;
}
- private String setConstraintForComplexType(Map<String, DataTypeDefinition> dataTypeDefinitionMap,
- String propertyType,
- String anInputPathArr,
+ private String setConstraintForComplexType(Map<String, DataTypeDefinition> dataTypeDefinitionMap, String propertyType, String anInputPathArr,
List<PropertyConstraint> constraints) {
String type = null;
- List<PropertyDefinition> propertyDefinitions =
- dataTypeDefinitionMap.get(propertyType).getProperties();
+ List<PropertyDefinition> propertyDefinitions = dataTypeDefinitionMap.get(propertyType).getProperties();
for (PropertyDefinition propertyDefinition : propertyDefinitions) {
if (propertyDefinition.getName().equals(anInputPathArr)) {
if (ToscaType.isPrimitiveType(propertyDefinition.getType())) {
@@ -761,18 +732,16 @@ public abstract class BaseBusinessLogic {
break;
}
}
-
return type;
}
-
protected void unlockRollbackWithException(Component component, RuntimeException e) {
janusGraphDao.rollback();
graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
throw e;
}
- protected void unlockWithCommit(Component component){
+ protected void unlockWithCommit(Component component) {
ComponentTypeEnum componentType = component.getComponentType();
NodeTypeEnum nodeType = componentType.getNodeType();
janusGraphDao.commit();
@@ -796,17 +765,13 @@ public abstract class BaseBusinessLogic {
}
protected Component getComponent(final String componentId) throws BusinessLogicException {
-
final Either<Component, StorageOperationStatus> result = toscaOperationFacade.getToscaElement(componentId);
-
if (result.isRight()) {
final StorageOperationStatus errorStatus = result.right().value();
- log.error(BUSINESS_PROCESS_ERROR, this.getClass().getName(),
- "Failed to fetch component information by component id, error {}", errorStatus);
- throw new BusinessLogicException(componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(errorStatus)));
+ log.error(BUSINESS_PROCESS_ERROR, this.getClass().getName(), "Failed to fetch component information by component id, error {}",
+ errorStatus);
+ throw new BusinessLogicException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
}
return result.left().value();
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CADIHealthCheck.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CADIHealthCheck.java
index f94528c64a..2fc012b720 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CADIHealthCheck.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CADIHealthCheck.java
@@ -17,42 +17,37 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
+import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_CADI;
+import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOWN;
+
import org.openecomp.sdc.common.api.HealthCheckInfo;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.springframework.stereotype.Component;
-import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_CADI;
-import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOWN;
-
@Component
public class CADIHealthCheck {
- private static CADIHealthCheck cadiHealthCheckInstance = new CADIHealthCheck();;
-
- private static HealthCheckInfo.HealthCheckStatus isCADIUpOrDown = DOWN;
-
private static final Logger log = Logger.getLogger(CADIHealthCheck.class.getName());
+ private static CADIHealthCheck cadiHealthCheckInstance = new CADIHealthCheck();
+ private static HealthCheckInfo.HealthCheckStatus isCADIUpOrDown = DOWN;
public static CADIHealthCheck getCADIHealthCheckInstance() {
return cadiHealthCheckInstance;
}
- public void setIsCADIUp(HealthCheckInfo.HealthCheckStatus cadiStatus) {
- log.debug("Setting cadiHealthCheckInstance status to: {}", cadiStatus.toString());
- isCADIUpOrDown = cadiStatus;
- }
-
public static HealthCheckInfo getCADIStatus() {
log.debug("getCADIStatus: Checking whether CADI was up or down while its init.");
String description = "OK";
- if (isCADIUpOrDown == DOWN){
+ if (isCADIUpOrDown == DOWN) {
description = "CADI filter failed initialization";
}
- return new HealthCheckInfo(HC_COMPONENT_CADI, isCADIUpOrDown, null,
- description);
+ return new HealthCheckInfo(HC_COMPONENT_CADI, isCADIUpOrDown, null, description);
}
+ public void setIsCADIUp(HealthCheckInfo.HealthCheckStatus cadiStatus) {
+ log.debug("Setting cadiHealthCheckInstance status to: {}", cadiStatus.toString());
+ isCADIUpOrDown = cadiStatus;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilitiesBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilitiesBusinessLogic.java
index 4bfc6509c6..cadaf6fcbc 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilitiesBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilitiesBusinessLogic.java
@@ -13,10 +13,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
@@ -51,42 +60,25 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.UUID;
-import java.util.stream.Collectors;
-
@org.springframework.stereotype.Component("capabilitiesBusinessLogic")
public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
+
private static final Logger LOGGER = LoggerFactory.getLogger(CapabilitiesBusinessLogic.class);
private static final String FAILED_TO_LOCK_COMPONENT_RESPONSE_IS = "Failed to lock component {}. Response is {}";
private static final String DELETE_CAPABILITIES = "deleteCapability";
private static final String GET_CAPABILITIES = "getCapabilities";
private static final String EXCEPTION_OCCURRED_DURING_CAPABILITIES = "Exception occurred during {}. Response is {}";
-
private final ICapabilityTypeOperation capabilityTypeOperation;
-
private CapabilitiesOperation capabilitiesOperation;
private CapabilitiesValidation capabilitiesValidation;
@Autowired
- public CapabilitiesBusinessLogic(IElementOperation elementDao,
- IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation,
- IGroupTypeOperation groupTypeOperation,
- GroupBusinessLogic groupBusinessLogic,
- InterfaceOperation interfaceOperation,
- InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
- ICapabilityTypeOperation capabilityTypeOperation,
- ArtifactsOperations artifactToscaOperation) {
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
- interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+ public CapabilitiesBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+ IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic,
+ InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+ ICapabilityTypeOperation capabilityTypeOperation, ArtifactsOperations artifactToscaOperation) {
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+ artifactToscaOperation);
this.capabilityTypeOperation = capabilityTypeOperation;
}
@@ -100,16 +92,14 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
this.capabilitiesOperation = capabilitiesOperation;
}
- public Either<List<CapabilityDefinition>, ResponseFormat> createCapabilities(String componentId,
- List<CapabilityDefinition> capabilityDefinitions,
+ public Either<List<CapabilityDefinition>, ResponseFormat> createCapabilities(String componentId, List<CapabilityDefinition> capabilityDefinitions,
User user, String errorContext, boolean lock) {
- Either<Component, ResponseFormat> validateUserAndCapabilitiesEither =
- validateUserAndCapabilities(user, componentId, errorContext, capabilityDefinitions);
- if(validateUserAndCapabilitiesEither.isRight()) {
+ Either<Component, ResponseFormat> validateUserAndCapabilitiesEither = validateUserAndCapabilities(user, componentId, errorContext,
+ capabilityDefinitions);
+ if (validateUserAndCapabilitiesEither.isRight()) {
return Either.right(validateUserAndCapabilitiesEither.right().value());
}
- Component storedComponent = validateUserAndCapabilitiesEither.left().value();
-
+ Component storedComponent = validateUserAndCapabilitiesEither.left().value();
Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock, storedComponent, errorContext);
if (lockResult.isRight()) {
return Either.right(lockResult.right().value());
@@ -122,16 +112,14 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
} finally {
if (lockResult.isLeft() && lockResult.left().value()) {
- graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
- NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+ graphLockOperation
+ .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
}
}
}
-
- private Either<Component, ResponseFormat> validateUserAndCapabilities(User user, String componentId,
- String errorContext,
- List<CapabilityDefinition> capabilityDefinitions ) {
+ private Either<Component, ResponseFormat> validateUserAndCapabilities(User user, String componentId, String errorContext,
+ List<CapabilityDefinition> capabilityDefinitions) {
validateUserExists(user.getUserId());
Either<Component, ResponseFormat> componentEither = getComponentDetails(componentId);
if (componentEither.isRight()) {
@@ -139,15 +127,14 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
}
Component storedComponent = componentEither.left().value();
Either<Boolean, ResponseFormat> capabilitiesValidationEither = capabilitiesValidation
- .validateCapabilities(capabilityDefinitions, storedComponent, false);
+ .validateCapabilities(capabilityDefinitions, storedComponent, false);
if (capabilitiesValidationEither.isRight()) {
return Either.right(capabilitiesValidationEither.right().value());
}
return Either.left(storedComponent);
}
- private Either<List<CapabilityDefinition>, ResponseFormat> createCapability(String componentId,
- List<CapabilityDefinition> capabilityDefinitions,
+ private Either<List<CapabilityDefinition>, ResponseFormat> createCapability(String componentId, List<CapabilityDefinition> capabilityDefinitions,
Component storedComponent) {
Either<List<CapabilityDefinition>, StorageOperationStatus> result;
List<CapabilityDefinition> capabilitiesListStoredInComponent = null;
@@ -157,32 +144,30 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
if (Objects.isNull(capabilityDefinitionToGetType)) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
- capabilitiesListStoredInComponent = getCapabilityStoredInComponentByType(capabilityDefinitionToGetType
- .getType(), storedComponentCapabilities);
+ capabilitiesListStoredInComponent = getCapabilityStoredInComponentByType(capabilityDefinitionToGetType.getType(),
+ storedComponentCapabilities);
}
List<CapabilityDefinition> capabilitiesDefListToCreate;
List<CapabilityDefinition> capabilitiesToReturn;
if (CollectionUtils.isNotEmpty(capabilitiesListStoredInComponent)) {
- capabilitiesDefListToCreate = capabilityDefinitions.stream().map(capabilityDefinition ->
- initiateNewCapability(storedComponent, capabilityDefinition)).collect(Collectors.toList());
+ capabilitiesDefListToCreate = capabilityDefinitions.stream()
+ .map(capabilityDefinition -> initiateNewCapability(storedComponent, capabilityDefinition)).collect(Collectors.toList());
capabilitiesToReturn = capabilitiesDefListToCreate;
capabilitiesDefListToCreate.addAll(capabilitiesListStoredInComponent);
result = capabilitiesOperation.updateCapabilities(componentId, capabilitiesDefListToCreate);
} else {
- capabilitiesToReturn = capabilityDefinitions.stream().map(capabilityDefinition ->
- initiateNewCapability(storedComponent, capabilityDefinition)).collect(Collectors.toList());
+ capabilitiesToReturn = capabilityDefinitions.stream()
+ .map(capabilityDefinition -> initiateNewCapability(storedComponent, capabilityDefinition)).collect(Collectors.toList());
result = capabilitiesOperation.addCapabilities(componentId, capabilitiesToReturn);
}
if (result.isRight()) {
janusGraphDao.rollback();
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result
- .right().value(), storedComponent.getComponentType()), ""));
+ return Either.right(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value(), storedComponent.getComponentType()), ""));
}
- Map<String, MapPropertiesDataDefinition> propertiesMap =
- getCapabilitiesPropertiesDataDefinitionMap(capabilityDefinitions);
+ Map<String, MapPropertiesDataDefinition> propertiesMap = getCapabilitiesPropertiesDataDefinitionMap(capabilityDefinitions);
if (MapUtils.isNotEmpty(propertiesMap)) {
- StorageOperationStatus storageOperationStatus = capabilitiesOperation
- .createOrUpdateCapabilityProperties(componentId, propertiesMap);
+ StorageOperationStatus storageOperationStatus = capabilitiesOperation.createOrUpdateCapabilityProperties(componentId, propertiesMap);
if (storageOperationStatus != StorageOperationStatus.OK) {
janusGraphDao.rollback();
return Either.right(componentsUtils.getResponseFormat(storageOperationStatus));
@@ -192,8 +177,7 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
return Either.left(capabilitiesToReturn);
}
- public Either<List<CapabilityDefinition>, ResponseFormat> updateCapabilities(String componentId,
- List<CapabilityDefinition> capabilityDefinitions,
+ public Either<List<CapabilityDefinition>, ResponseFormat> updateCapabilities(String componentId, List<CapabilityDefinition> capabilityDefinitions,
User user, String errorContext, boolean lock) {
validateUserExists(user.getUserId());
Either<Component, ResponseFormat> componentEither = getComponentDetails(componentId);
@@ -202,11 +186,10 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
}
Component storedComponent = componentEither.left().value();
Either<Boolean, ResponseFormat> capabilitiesValidationEither = capabilitiesValidation
- .validateCapabilities(capabilityDefinitions, storedComponent, true);
+ .validateCapabilities(capabilityDefinitions, storedComponent, true);
if (capabilitiesValidationEither.isRight()) {
return Either.right(capabilitiesValidationEither.right().value());
}
-
Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock, storedComponent, errorContext);
if (lockResult.isRight()) {
return Either.right(lockResult.right().value());
@@ -220,32 +203,30 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
if (Objects.isNull(capabilityDefinitionToGetType)) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
- capabilitiesListStoredInComponent = getCapabilityStoredInComponentByType(capabilityDefinitionToGetType
- .getType(), storedComponentCapabilities);
+ capabilitiesListStoredInComponent = getCapabilityStoredInComponentByType(capabilityDefinitionToGetType.getType(),
+ storedComponentCapabilities);
}
List<CapabilityDefinition> capabilitiesDefListToUpdate = new ArrayList<>();
List<CapabilityDefinition> capabilitiesToReturn = null;
if (CollectionUtils.isNotEmpty(capabilitiesListStoredInComponent)) {
- if (capabilityDefinitions.stream().anyMatch(capabilityDefinition ->
- isCapabilityUsedInServiceComposition(capabilityDefinition, storedComponent))) {
+ if (capabilityDefinitions.stream()
+ .anyMatch(capabilityDefinition -> isCapabilityUsedInServiceComposition(capabilityDefinition, storedComponent))) {
LOGGER.error("Capability can't be edited, since it is" + " used in service composition");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.
- CAPABILITY_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION));
}
for (CapabilityDefinition capabilityDefinitionToUpdate : capabilityDefinitions) {
- capabilitiesToReturn = capabilitiesListStoredInComponent.stream().filter(capToUpdate ->
- capToUpdate.getUniqueId().equals(capabilityDefinitionToUpdate.getUniqueId()))
- .map(capabilityDefinition -> updateCapability(capabilityDefinition,
- capabilityDefinitionToUpdate, storedComponent)).collect(Collectors.toList());
- capabilitiesListStoredInComponent.removeIf(capToUpdate -> capToUpdate.getUniqueId()
- .equals(capabilityDefinitionToUpdate.getUniqueId()));
+ capabilitiesToReturn = capabilitiesListStoredInComponent.stream()
+ .filter(capToUpdate -> capToUpdate.getUniqueId().equals(capabilityDefinitionToUpdate.getUniqueId()))
+ .map(capabilityDefinition -> updateCapability(capabilityDefinition, capabilityDefinitionToUpdate, storedComponent))
+ .collect(Collectors.toList());
+ capabilitiesListStoredInComponent
+ .removeIf(capToUpdate -> capToUpdate.getUniqueId().equals(capabilityDefinitionToUpdate.getUniqueId()));
if (CollectionUtils.isNotEmpty(capabilitiesToReturn)) {
capabilitiesListStoredInComponent.addAll(capabilitiesToReturn);
capabilitiesDefListToUpdate.addAll(capabilitiesListStoredInComponent);
} else {
- Either<List<CapabilityDefinition>, ResponseFormat> capTypeUpdateEither
- = handleCapabilityTypeUpdateWhenNewTypeExist(storedComponent, storedComponent
- .getCapabilities(), capabilitiesToReturn, capabilityDefinitionToUpdate);
+ Either<List<CapabilityDefinition>, ResponseFormat> capTypeUpdateEither = handleCapabilityTypeUpdateWhenNewTypeExist(
+ storedComponent, storedComponent.getCapabilities(), capabilitiesToReturn, capabilityDefinitionToUpdate);
if (capTypeUpdateEither.isRight()) {
return Either.right(capTypeUpdateEither.right().value());
}
@@ -254,26 +235,23 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
}
result = capabilitiesOperation.updateCapabilities(componentId, capabilitiesDefListToUpdate);
} else {
- Either<List<CapabilityDefinition>, ResponseFormat> capabilityDefinitionToDelete
- = handleCapabilityTypeUpdateWhenNewTypeNotExist(capabilityDefinitions, storedComponent,
- storedComponentCapabilities);
+ Either<List<CapabilityDefinition>, ResponseFormat> capabilityDefinitionToDelete = handleCapabilityTypeUpdateWhenNewTypeNotExist(
+ capabilityDefinitions, storedComponent, storedComponentCapabilities);
if (capabilityDefinitionToDelete != null) {
return capabilityDefinitionToDelete;
}
- capabilitiesToReturn = capabilityDefinitions.stream().map(capabilityDefinition ->
- initiateNewCapability(storedComponent, capabilityDefinition)).collect(Collectors.toList());
+ capabilitiesToReturn = capabilityDefinitions.stream()
+ .map(capabilityDefinition -> initiateNewCapability(storedComponent, capabilityDefinition)).collect(Collectors.toList());
result = capabilitiesOperation.addCapabilities(componentId, capabilitiesToReturn);
}
if (result.isRight()) {
janusGraphDao.rollback();
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result
- .right().value(), storedComponent.getComponentType()), ""));
+ return Either.right(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value(), storedComponent.getComponentType()), ""));
}
- Map<String, MapPropertiesDataDefinition> propertiesMap =
- getCapabilitiesPropertiesDataDefinitionMap(capabilityDefinitions);
+ Map<String, MapPropertiesDataDefinition> propertiesMap = getCapabilitiesPropertiesDataDefinitionMap(capabilityDefinitions);
if (MapUtils.isNotEmpty(propertiesMap)) {
- StorageOperationStatus storageOperationStatus = capabilitiesOperation
- .createOrUpdateCapabilityProperties(componentId, propertiesMap);
+ StorageOperationStatus storageOperationStatus = capabilitiesOperation.createOrUpdateCapabilityProperties(componentId, propertiesMap);
if (storageOperationStatus != StorageOperationStatus.OK) {
janusGraphDao.rollback();
return Either.right(componentsUtils.getResponseFormat(storageOperationStatus));
@@ -287,81 +265,67 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
} finally {
if (lockResult.isLeft() && lockResult.left().value()) {
- graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
- NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+ graphLockOperation
+ .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
}
}
}
- private Either<List<CapabilityDefinition>, ResponseFormat> handleCapabilityTypeUpdateWhenNewTypeExist(
- Component storedComponent,
- Map<String, List<CapabilityDefinition>> storedComponentCapabilities,
- List<CapabilityDefinition> capabilitiesToReturn,
- CapabilityDefinition capabilityDefinitionToUpdate) {
-
+ private Either<List<CapabilityDefinition>, ResponseFormat> handleCapabilityTypeUpdateWhenNewTypeExist(Component storedComponent,
+ Map<String, List<CapabilityDefinition>> storedComponentCapabilities,
+ List<CapabilityDefinition> capabilitiesToReturn,
+ CapabilityDefinition capabilityDefinitionToUpdate) {
List<CapabilityDefinition> capabilitiesListStoredInComponent;
List<CapabilityDefinition> capabilitiesDefsToCreateOrUpdate = new ArrayList<>();
- Optional<CapabilityDefinition> definitionOptional = storedComponentCapabilities.values().stream()
- .flatMap(Collection::stream).filter(capabilityDefinition -> capabilityDefinition.getUniqueId()
- .equals(capabilityDefinitionToUpdate.getUniqueId())).findAny();
+ Optional<CapabilityDefinition> definitionOptional = storedComponentCapabilities.values().stream().flatMap(Collection::stream)
+ .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(capabilityDefinitionToUpdate.getUniqueId())).findAny();
if (!definitionOptional.isPresent()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND,
- storedComponent.getUniqueId()));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, storedComponent.getUniqueId()));
}
CapabilityDefinition capabilityDefinitionToDelete = definitionOptional.get();
-
- capabilitiesListStoredInComponent = getCapabilityStoredInComponentByType(capabilityDefinitionToUpdate.getType(),
- storedComponentCapabilities);
- Either<List<CapabilityDefinition>, StorageOperationStatus> deleteCapabilityEither
- = deleteCapability(storedComponent, storedComponentCapabilities, capabilityDefinitionToDelete);
+ capabilitiesListStoredInComponent = getCapabilityStoredInComponentByType(capabilityDefinitionToUpdate.getType(), storedComponentCapabilities);
+ Either<List<CapabilityDefinition>, StorageOperationStatus> deleteCapabilityEither = deleteCapability(storedComponent,
+ storedComponentCapabilities, capabilityDefinitionToDelete);
if (deleteCapabilityEither.isRight()) {
janusGraphDao.rollback();
return Either.right(componentsUtils.getResponseFormat(deleteCapabilityEither.right().value()));
}
StorageOperationStatus deleteStorageOperationStatus = capabilitiesOperation
- .deleteCapabilityProperties(storedComponent, buildCapPropKey(capabilityDefinitionToDelete));
+ .deleteCapabilityProperties(storedComponent, buildCapPropKey(capabilityDefinitionToDelete));
if (deleteStorageOperationStatus != StorageOperationStatus.OK) {
janusGraphDao.rollback();
return Either.right(componentsUtils.getResponseFormat(deleteStorageOperationStatus));
}
capabilitiesToReturn.add(initiateNewCapability(storedComponent, capabilityDefinitionToUpdate));
-
capabilitiesDefsToCreateOrUpdate.addAll(capabilitiesToReturn);
capabilitiesDefsToCreateOrUpdate.addAll(capabilitiesListStoredInComponent);
return Either.left(capabilitiesDefsToCreateOrUpdate);
}
private Either<List<CapabilityDefinition>, ResponseFormat> handleCapabilityTypeUpdateWhenNewTypeNotExist(
- List<CapabilityDefinition> capabilityDefinitions,
- Component storedComponent,
- Map<String, List<CapabilityDefinition>> storedComponentCapabilities) {
+ List<CapabilityDefinition> capabilityDefinitions, Component storedComponent,
+ Map<String, List<CapabilityDefinition>> storedComponentCapabilities) {
for (CapabilityDefinition capabilityDefinitionToUpdate : capabilityDefinitions) {
-
- Optional<CapabilityDefinition> definitionOptional = storedComponentCapabilities.values().stream()
- .flatMap(Collection::stream).filter(capabilityDefinition -> capabilityDefinition.getUniqueId()
- .equals(capabilityDefinitionToUpdate.getUniqueId())).findAny();
+ Optional<CapabilityDefinition> definitionOptional = storedComponentCapabilities.values().stream().flatMap(Collection::stream)
+ .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(capabilityDefinitionToUpdate.getUniqueId())).findAny();
if (!definitionOptional.isPresent()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus
- .CAPABILITY_NOT_FOUND, storedComponent.getUniqueId()));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, storedComponent.getUniqueId()));
}
CapabilityDefinition capabilityDefinitionToDelete = definitionOptional.get();
- Boolean isCapabilityUsedInServiceComposition = isCapabilityUsedInServiceComposition(capabilityDefinitionToDelete,
- storedComponent);
+ Boolean isCapabilityUsedInServiceComposition = isCapabilityUsedInServiceComposition(capabilityDefinitionToDelete, storedComponent);
if (isCapabilityUsedInServiceComposition) {
- LOGGER.error("Capability {} can't be edited, since it is used in service composition",
- capabilityDefinitionToDelete.getUniqueId());
- return Either.right(componentsUtils.getResponseFormat(
- ActionStatus.CAPABILITY_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION,
- capabilityDefinitionToDelete.getName()));
+ LOGGER.error("Capability {} can't be edited, since it is used in service composition", capabilityDefinitionToDelete.getUniqueId());
+ return Either.right(componentsUtils
+ .getResponseFormat(ActionStatus.CAPABILITY_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION, capabilityDefinitionToDelete.getName()));
}
- Either<List<CapabilityDefinition>, StorageOperationStatus> deleteCapabilityEither
- = deleteCapability(storedComponent, storedComponentCapabilities, capabilityDefinitionToDelete);
+ Either<List<CapabilityDefinition>, StorageOperationStatus> deleteCapabilityEither = deleteCapability(storedComponent,
+ storedComponentCapabilities, capabilityDefinitionToDelete);
if (deleteCapabilityEither.isRight()) {
janusGraphDao.rollback();
return Either.right(componentsUtils.getResponseFormat(deleteCapabilityEither.right().value()));
}
StorageOperationStatus deleteStorageOperationStatus = capabilitiesOperation
- .deleteCapabilityProperties(storedComponent, buildCapPropKey(capabilityDefinitionToDelete));
+ .deleteCapabilityProperties(storedComponent, buildCapPropKey(capabilityDefinitionToDelete));
if (deleteStorageOperationStatus != StorageOperationStatus.OK) {
janusGraphDao.rollback();
return Either.right(componentsUtils.getResponseFormat(deleteStorageOperationStatus));
@@ -370,22 +334,19 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
return null;
}
- public Either<CapabilityDefinition, ResponseFormat> getCapability(String componentId, String capabilityToGet,
- User user, boolean lock) {
+ public Either<CapabilityDefinition, ResponseFormat> getCapability(String componentId, String capabilityToGet, User user, boolean lock) {
validateUserExists(user.getUserId());
Either<Component, ResponseFormat> componentEither = getComponentDetails(componentId);
if (componentEither.isRight()) {
return Either.right(componentEither.right().value());
}
Component storedComponent = componentEither.left().value();
-
Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock, storedComponent, GET_CAPABILITIES);
if (lockResult.isRight()) {
return Either.right(lockResult.right().value());
}
try {
- Either<CapabilityDefinition, ResponseFormat> getCapabilityDefinitionEither =
- getCapabilityDefinition(capabilityToGet, storedComponent);
+ Either<CapabilityDefinition, ResponseFormat> getCapabilityDefinitionEither = getCapabilityDefinition(capabilityToGet, storedComponent);
if (getCapabilityDefinitionEither.isRight()) {
return Either.right(getCapabilityDefinitionEither.right().value());
}
@@ -395,42 +356,36 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, componentId));
} finally {
if (lockResult.isLeft() && lockResult.left().value()) {
- graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
- NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+ graphLockOperation
+ .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
}
}
}
- private Either<CapabilityDefinition, ResponseFormat> getCapabilityDefinition(String capabilityIdToGet,
- Component storedComponent) {
- List<CapabilityDefinition> capabilityDefinitions = storedComponent.getCapabilities().values()
- .stream().flatMap(Collection::stream).collect(Collectors.toList());
+ private Either<CapabilityDefinition, ResponseFormat> getCapabilityDefinition(String capabilityIdToGet, Component storedComponent) {
+ List<CapabilityDefinition> capabilityDefinitions = storedComponent.getCapabilities().values().stream().flatMap(Collection::stream)
+ .collect(Collectors.toList());
if (capabilityDefinitions.isEmpty()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND,
- storedComponent.getUniqueId()));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, storedComponent.getUniqueId()));
}
CapabilityDefinition capabilityDefinitionToReturn;
Optional<CapabilityDefinition> capabilityDefinitionOptional = capabilityDefinitions.stream()
- .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(capabilityIdToGet)).findAny();
+ .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(capabilityIdToGet)).findAny();
if (capabilityDefinitionOptional.isPresent()) {
capabilityDefinitionToReturn = capabilityDefinitionOptional.get();
} else {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND,
- storedComponent.getUniqueId()));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, storedComponent.getUniqueId()));
}
-
return Either.left(capabilityDefinitionToReturn);
}
- public Either<CapabilityDefinition, ResponseFormat> deleteCapability(String componentId, String capabilityIdToDelete,
- User user, boolean lock) {
+ public Either<CapabilityDefinition, ResponseFormat> deleteCapability(String componentId, String capabilityIdToDelete, User user, boolean lock) {
validateUserExists(user.getUserId());
Either<Component, ResponseFormat> componentEither = getComponentDetails(componentId);
if (componentEither.isRight()) {
return Either.right(componentEither.right().value());
}
Component storedComponent = componentEither.left().value();
-
Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock, storedComponent, DELETE_CAPABILITIES);
if (lockResult.isRight()) {
return Either.right(lockResult.right().value());
@@ -443,85 +398,74 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND));
} finally {
if (lockResult.isLeft() && lockResult.left().value()) {
- graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
- NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+ graphLockOperation
+ .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
}
}
}
- private Either<CapabilityDefinition, ResponseFormat> deleteCapability(String capabilityIdToDelete,
- Component storedComponent) {
+ private Either<CapabilityDefinition, ResponseFormat> deleteCapability(String capabilityIdToDelete, Component storedComponent) {
Map<String, List<CapabilityDefinition>> storedComponentCapabilities = storedComponent.getCapabilities();
if (storedComponentCapabilities.isEmpty()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, storedComponent.getUniqueId()));
}
- Either<CapabilityDefinition, ResponseFormat> capabilityDefinitionToDeleteEither =
- getAndValidateCapabilitiesToDelete(storedComponent, storedComponentCapabilities, capabilityIdToDelete);
-
- if(capabilityDefinitionToDeleteEither.isRight()) {
+ Either<CapabilityDefinition, ResponseFormat> capabilityDefinitionToDeleteEither = getAndValidateCapabilitiesToDelete(storedComponent,
+ storedComponentCapabilities, capabilityIdToDelete);
+ if (capabilityDefinitionToDeleteEither.isRight()) {
return Either.right(capabilityDefinitionToDeleteEither.right().value());
}
- Either<List<CapabilityDefinition>, StorageOperationStatus> result = deleteCapability(storedComponent,
- storedComponentCapabilities, capabilityDefinitionToDeleteEither.left().value());
+ Either<List<CapabilityDefinition>, StorageOperationStatus> result = deleteCapability(storedComponent, storedComponentCapabilities,
+ capabilityDefinitionToDeleteEither.left().value());
if (result.isRight()) {
janusGraphDao.rollback();
- LOGGER.error("Failed to delete capability from component {}. Response is {}", storedComponent.getName(),
- result.right().value());
- return Either.right(componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(result.right().value(),
- storedComponent.getComponentType())));
+ LOGGER.error("Failed to delete capability from component {}. Response is {}", storedComponent.getName(), result.right().value());
+ return Either.right(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value(), storedComponent.getComponentType())));
}
janusGraphDao.commit();
-
return Either.left(capabilityDefinitionToDeleteEither.left().value());
}
private Either<CapabilityDefinition, ResponseFormat> getAndValidateCapabilitiesToDelete(Component storedComponent,
Map<String, List<CapabilityDefinition>> storedComponentCapabilities,
String capabilityIdToDelete) {
-
- Optional<CapabilityDefinition> definitionOptional = storedComponentCapabilities.values().stream()
- .flatMap(Collection::stream).filter(capabilityDefinition -> capabilityDefinition.getUniqueId()
- .equals(capabilityIdToDelete)).findAny();
+ Optional<CapabilityDefinition> definitionOptional = storedComponentCapabilities.values().stream().flatMap(Collection::stream)
+ .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(capabilityIdToDelete)).findAny();
if (!definitionOptional.isPresent()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, storedComponent.getUniqueId()));
}
CapabilityDefinition capabilityDefinitionToDelete = definitionOptional.get();
- Boolean isCapabilityUsedInServiceComposition
- = isCapabilityUsedInServiceComposition(capabilityDefinitionToDelete, storedComponent);
+ Boolean isCapabilityUsedInServiceComposition = isCapabilityUsedInServiceComposition(capabilityDefinitionToDelete, storedComponent);
if (isCapabilityUsedInServiceComposition) {
- LOGGER.error("Capability {} can't be deleted, since it is used in service composition",
- capabilityDefinitionToDelete.getUniqueId());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus
- .CAPABILITY_DELETION_NOT_ALLOWED_USED_IN_COMPOSITION, capabilityDefinitionToDelete.getName()));
+ LOGGER.error("Capability {} can't be deleted, since it is used in service composition", capabilityDefinitionToDelete.getUniqueId());
+ return Either.right(componentsUtils
+ .getResponseFormat(ActionStatus.CAPABILITY_DELETION_NOT_ALLOWED_USED_IN_COMPOSITION, capabilityDefinitionToDelete.getName()));
}
-
return Either.left(capabilityDefinitionToDelete);
}
+
private Either<List<CapabilityDefinition>, StorageOperationStatus> deleteCapability(Component storedComponent,
Map<String, List<CapabilityDefinition>> storedComponentCapabilities,
CapabilityDefinition capabilityDefinitionToDelete) {
-
- List<CapabilityDefinition> capabilitiesListStoredInComponent =
- getCapabilityStoredInComponentByType(capabilityDefinitionToDelete.getType(), storedComponentCapabilities);
- capabilitiesListStoredInComponent.removeIf(capabilityDefinition ->
- capabilityDefinition.getUniqueId().equals(capabilityDefinitionToDelete.getUniqueId()));
+ List<CapabilityDefinition> capabilitiesListStoredInComponent = getCapabilityStoredInComponentByType(capabilityDefinitionToDelete.getType(),
+ storedComponentCapabilities);
+ capabilitiesListStoredInComponent
+ .removeIf(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(capabilityDefinitionToDelete.getUniqueId()));
Either<List<CapabilityDefinition>, StorageOperationStatus> result;
if (capabilitiesListStoredInComponent.isEmpty()) {
- StorageOperationStatus operationStatus = capabilitiesOperation.deleteCapabilities(storedComponent,
- capabilityDefinitionToDelete.getType());
+ StorageOperationStatus operationStatus = capabilitiesOperation
+ .deleteCapabilities(storedComponent, capabilityDefinitionToDelete.getType());
if (StorageOperationStatus.OK.equals(operationStatus)) {
result = Either.left(Collections.singletonList(capabilityDefinitionToDelete));
} else {
result = Either.right(operationStatus);
}
} else {
- result = capabilitiesOperation.updateCapabilities(storedComponent.getUniqueId(),
- capabilitiesListStoredInComponent);
+ result = capabilitiesOperation.updateCapabilities(storedComponent.getUniqueId(), capabilitiesListStoredInComponent);
}
if (result.isLeft()) {
StorageOperationStatus deleteStorageOperationStatus = capabilitiesOperation
- .deleteCapabilityProperties(storedComponent, buildCapPropKey(capabilityDefinitionToDelete));
+ .deleteCapabilityProperties(storedComponent, buildCapPropKey(capabilityDefinitionToDelete));
if (deleteStorageOperationStatus != StorageOperationStatus.OK) {
result = Either.right(deleteStorageOperationStatus);
}
@@ -529,17 +473,14 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
return result;
}
-
private Either<Component, ResponseFormat> getComponentDetails(String componentId) {
ComponentParametersView filter = new ComponentParametersView(true);
filter.setIgnoreCapabilities(false);
filter.setIgnoreCapabiltyProperties(false);
- Either<Component, StorageOperationStatus> componentStorageOperationStatusEither =
- toscaOperationFacade.getToscaElement(componentId, filter);
+ Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId, filter);
if (componentStorageOperationStatusEither.isRight()) {
StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
- LOGGER.error("Failed to fetch component information by component id {}, Response is {}",
- componentId, errorStatus);
+ LOGGER.error("Failed to fetch component information by component id {}, Response is {}", componentId, errorStatus);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
}
return Either.left(componentStorageOperationStatusEither.left().value());
@@ -549,7 +490,7 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
if (lock) {
try {
lockComponent(component.getUniqueId(), component, action);
- } catch (ComponentException e){
+ } catch (ComponentException e) {
LOGGER.debug(FAILED_TO_LOCK_COMPONENT_RESPONSE_IS, component.getName(), e.getMessage());
janusGraphDao.rollback();
throw e;
@@ -558,40 +499,41 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
return Either.left(true);
}
- private List<CapabilityDefinition> getCapabilityStoredInComponentByType(String capabilityType, Map<String,
- List<CapabilityDefinition>> capabilities) {
+ private List<CapabilityDefinition> getCapabilityStoredInComponentByType(String capabilityType,
+ Map<String, List<CapabilityDefinition>> capabilities) {
Optional<Map.Entry<String, List<CapabilityDefinition>>> entryOptional = capabilities.entrySet().stream()
- .filter(map -> map.getKey().equals(capabilityType)).findFirst();
+ .filter(map -> map.getKey().equals(capabilityType)).findFirst();
return entryOptional.map(Map.Entry::getValue).orElse(Collections.emptyList());
}
private CapabilityDefinition initiateNewCapability(Component component, CapabilityDefinition capabilityDefinition) {
- if (StringUtils.isEmpty(capabilityDefinition.getUniqueId()))
+ if (StringUtils.isEmpty(capabilityDefinition.getUniqueId())) {
capabilityDefinition.setUniqueId(UUID.randomUUID().toString());
- if (StringUtils.isEmpty(capabilityDefinition.getOwnerId()))
+ }
+ if (StringUtils.isEmpty(capabilityDefinition.getOwnerId())) {
capabilityDefinition.setOwnerId(component.getUniqueId());
- if (StringUtils.isEmpty(capabilityDefinition.getOwnerName()))
+ }
+ if (StringUtils.isEmpty(capabilityDefinition.getOwnerName())) {
capabilityDefinition.setOwnerName(component.getName());
+ }
capabilityDefinition.setLeftOccurrences(capabilityDefinition.getMaxOccurrences());
List<ComponentInstanceProperty> capabilityProperties = capabilityDefinition.getProperties();
initiateProperties(capabilityDefinition, capabilityProperties);
return capabilityDefinition;
}
- private void initiateProperties(CapabilityDefinition capabilityDefinition,
- List<ComponentInstanceProperty> capabilityProperties) {
+ private void initiateProperties(CapabilityDefinition capabilityDefinition, List<ComponentInstanceProperty> capabilityProperties) {
if (CollectionUtils.isNotEmpty(capabilityProperties)) {
- capabilityProperties.stream().filter(prop -> prop != null && StringUtils.isEmpty(prop.getUniqueId()))
- .forEach(propDef -> {
- String uid = UniqueIdBuilder.buildRequirementUid(capabilityDefinition.getUniqueId(), propDef.getName());
- propDef.setUniqueId(uid);
- propDef.setParentUniqueId(capabilityDefinition.getUniqueId());
- });
+ capabilityProperties.stream().filter(prop -> prop != null && StringUtils.isEmpty(prop.getUniqueId())).forEach(propDef -> {
+ String uid = UniqueIdBuilder.buildRequirementUid(capabilityDefinition.getUniqueId(), propDef.getName());
+ propDef.setUniqueId(uid);
+ propDef.setParentUniqueId(capabilityDefinition.getUniqueId());
+ });
}
}
- private CapabilityDefinition updateCapability(CapabilityDefinition storedCapability,
- CapabilityDefinition capabilityToUpdate, Component component) {
+ private CapabilityDefinition updateCapability(CapabilityDefinition storedCapability, CapabilityDefinition capabilityToUpdate,
+ Component component) {
storedCapability.setName(capabilityToUpdate.getName());
storedCapability.setDescription(capabilityToUpdate.getDescription());
storedCapability.setType(capabilityToUpdate.getType());
@@ -605,48 +547,44 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
}
if (!storedCapability.getName().equals(capabilityToUpdate.getName())) {
StorageOperationStatus deleteStorageOperationStatus = capabilitiesOperation
- .deleteCapabilityProperties(component, buildCapPropKey(storedCapability));
+ .deleteCapabilityProperties(component, buildCapPropKey(storedCapability));
if (deleteStorageOperationStatus != StorageOperationStatus.OK) {
janusGraphDao.rollback();
}
}
-
return storedCapability;
}
-
private Boolean isCapabilityUsedInServiceComposition(CapabilityDefinition capabilityDefinition, Component component) {
- Either<List<Component>, StorageOperationStatus> componentList = toscaOperationFacade
- .getParentComponents(component.getUniqueId());
+ Either<List<Component>, StorageOperationStatus> componentList = toscaOperationFacade.getParentComponents(component.getUniqueId());
if (componentList.isRight()) {
return Boolean.FALSE;
}
- return componentList.left().value().stream().flatMap(parentComponent -> parentComponent
- .getComponentInstancesRelations().stream()).flatMap(requirementCapabilityRelDef ->
- requirementCapabilityRelDef.getRelationships().stream()).anyMatch(capabilityRequirementRelationship ->
- capabilityRequirementRelationship.getRelation().getCapabilityUid().equals(capabilityDefinition.getUniqueId()));
+ return componentList.left().value().stream().flatMap(parentComponent -> parentComponent.getComponentInstancesRelations().stream())
+ .flatMap(requirementCapabilityRelDef -> requirementCapabilityRelDef.getRelationships().stream()).anyMatch(
+ capabilityRequirementRelationship -> capabilityRequirementRelationship.getRelation().getCapabilityUid()
+ .equals(capabilityDefinition.getUniqueId()));
}
public Either<Map<String, CapabilityTypeDefinition>, ResponseFormat> getAllCapabilityTypes() {
- Either<Map<String, CapabilityTypeDefinition>, JanusGraphOperationStatus> capabilityTypeCacheAll =
- capabilityTypeOperation.getAllCapabilityTypes();
+ Either<Map<String, CapabilityTypeDefinition>, JanusGraphOperationStatus> capabilityTypeCacheAll = capabilityTypeOperation
+ .getAllCapabilityTypes();
if (capabilityTypeCacheAll.isRight()) {
JanusGraphOperationStatus operationStatus = capabilityTypeCacheAll.right().value();
if (JanusGraphOperationStatus.NOT_FOUND == operationStatus) {
- BeEcompErrorManager.getInstance().logInternalDataError("FetchCapabilityTypes",
- "Capability types are not loaded", BeEcompErrorManager.ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError("FetchCapabilityTypes", "Capability types are not loaded", BeEcompErrorManager.ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY));
} else {
- BeEcompErrorManager.getInstance().logInternalFlowError("FetchCapabilityTypes",
- "Failed to fetch capability types", BeEcompErrorManager.ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalFlowError("FetchCapabilityTypes", "Failed to fetch capability types", BeEcompErrorManager.ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
}
return Either.left(capabilityTypeCacheAll.left().value());
}
- private Map<String, MapPropertiesDataDefinition> getCapabilitiesPropertiesDataDefinitionMap(
- List<CapabilityDefinition> capabilityDefinitions) {
+ private Map<String, MapPropertiesDataDefinition> getCapabilitiesPropertiesDataDefinitionMap(List<CapabilityDefinition> capabilityDefinitions) {
CapabilityDefinition capabilityDefinitionToAddOrUpdateCapProp = capabilityDefinitions.get(0);
List<ComponentInstanceProperty> componentInstanceProperties = null;
if (Objects.nonNull(capabilityDefinitionToAddOrUpdateCapProp)) {
@@ -664,7 +602,7 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
}
private String buildCapPropKey(CapabilityDefinition capabilityDefinitionToAddOrUpdateCapProp) {
- return capabilityDefinitionToAddOrUpdateCapProp.getType() + ModelConverter.CAP_PROP_DELIM +
- capabilityDefinitionToAddOrUpdateCapProp.getName();
+ return capabilityDefinitionToAddOrUpdateCapProp.getType() + ModelConverter.CAP_PROP_DELIM + capabilityDefinitionToAddOrUpdateCapProp
+ .getName();
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java
index ebe79f57f8..df7650f24a 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,10 +17,11 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
+import java.util.List;
+import java.util.Map;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
@@ -33,9 +34,6 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import java.util.List;
-import java.util.Map;
-
@Component("capabilityTypeImportManager")
public class CapabilityTypeImportManager {
@@ -50,51 +48,44 @@ public class CapabilityTypeImportManager {
}
public Either<List<ImmutablePair<CapabilityTypeDefinition, Boolean>>, ResponseFormat> createCapabilityTypes(String capabilityTypesYml) {
- return commonImportManager.createElementTypes(capabilityTypesYml, this::createCapabilityTypesFromYml, this::upsertCapabilityTypesByDao, CommonImportManager.ElementTypeEnum.CAPABILITY_TYPE);
-
+ return commonImportManager.createElementTypes(capabilityTypesYml, this::createCapabilityTypesFromYml, this::upsertCapabilityTypesByDao,
+ CommonImportManager.ElementTypeEnum.CAPABILITY_TYPE);
}
private Either<List<CapabilityTypeDefinition>, ActionStatus> createCapabilityTypesFromYml(String capabilityTypesYml) {
return commonImportManager.createElementTypesFromYml(capabilityTypesYml, this::createCapabilityType);
-
}
- private Either<List<ImmutablePair<CapabilityTypeDefinition, Boolean>>, ResponseFormat> upsertCapabilityTypesByDao(List<CapabilityTypeDefinition> capabilityTypesToCreate) {
- return commonImportManager.createElementTypesByDao(capabilityTypesToCreate,
- capabilityType -> Either.left(ActionStatus.OK),
- capabilityType -> new ImmutablePair<>(CommonImportManager.ElementTypeEnum.CAPABILITY_TYPE, capabilityType.getType()),
- capabilityTypeOperation::getCapabilityType,
- capabilityTypeOperation::addCapabilityType,
- this::updateCapabilityType);
+ private Either<List<ImmutablePair<CapabilityTypeDefinition, Boolean>>, ResponseFormat> upsertCapabilityTypesByDao(
+ List<CapabilityTypeDefinition> capabilityTypesToCreate) {
+ return commonImportManager.createElementTypesByDao(capabilityTypesToCreate, capabilityType -> Either.left(ActionStatus.OK),
+ capabilityType -> new ImmutablePair<>(CommonImportManager.ElementTypeEnum.CAPABILITY_TYPE, capabilityType.getType()),
+ capabilityTypeOperation::getCapabilityType, capabilityTypeOperation::addCapabilityType, this::updateCapabilityType);
}
-
- private Either<CapabilityTypeDefinition, StorageOperationStatus> updateCapabilityType(CapabilityTypeDefinition newCapabilityType, CapabilityTypeDefinition oldCapabilityType) {
+
+ private Either<CapabilityTypeDefinition, StorageOperationStatus> updateCapabilityType(CapabilityTypeDefinition newCapabilityType,
+ CapabilityTypeDefinition oldCapabilityType) {
Either<CapabilityTypeDefinition, StorageOperationStatus> validationRes = capabilityTypeOperation.validateUpdateProperties(newCapabilityType);
if (validationRes.isRight()) {
- log.error("#updateCapabilityType - One or all properties of capability type {} not valid. status is {}", newCapabilityType, validationRes.right().value());
+ log.error("#updateCapabilityType - One or all properties of capability type {} not valid. status is {}", newCapabilityType,
+ validationRes.right().value());
return validationRes;
}
-
if (TypeCompareUtils.isCapabilityTypesEquals(newCapabilityType, oldCapabilityType)) {
return TypeCompareUtils.typeAlreadyExists();
}
-
return capabilityTypeOperation.updateCapabilityType(newCapabilityType, oldCapabilityType);
}
private CapabilityTypeDefinition createCapabilityType(String capabilityTypeName, Map<String, Object> toscaJson) {
CapabilityTypeDefinition capabilityType = new CapabilityTypeDefinition();
-
capabilityType.setType(capabilityTypeName);
-
// Description
commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName(), capabilityType::setDescription);
// Derived From
commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM.getElementName(), capabilityType::setDerivedFrom);
// Properties
commonImportManager.setPropertiesMap(toscaJson, capabilityType::setProperties);
-
return capabilityType;
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java
index fb85ab5326..6ebdb9bfab 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java
@@ -24,15 +24,6 @@ package org.openecomp.sdc.be.components.impl;
import com.datastax.driver.core.KeyspaceMetadata;
import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.Session;
-import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.dao.cassandra.schema.SdcSchemaUtils;
-import org.openecomp.sdc.be.dao.cassandra.schema.Table;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.common.util.GeneralUtility;
-import org.springframework.stereotype.Component;
-
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
@@ -42,40 +33,38 @@ import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.cassandra.schema.SdcSchemaUtils;
+import org.openecomp.sdc.be.dao.cassandra.schema.Table;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.openecomp.sdc.common.util.GeneralUtility;
+import org.springframework.stereotype.Component;
@Component("cassandra-health-check")
public class CassandraHealthCheck {
private static final Logger log = Logger.getLogger(CassandraHealthCheck.class);
-
- private String localDataCenterName;
-
private final Set<String> sdcKeyspaces = new HashSet<>();
-
+ private String localDataCenterName;
private int HC_FormulaNumber;
-
private SdcSchemaUtils sdcSchemaUtils;
@PostConstruct
private void init() {
-
//Initialize local data center name - this field must be filled by DevOps
localDataCenterName = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getLocalDataCenter();
-
- if (GeneralUtility.isEmptyString(localDataCenterName)) {
+ if (GeneralUtility.isEmptyString(localDataCenterName)) {
log.error("localDataCenter Name in configuration.yaml is missing.");
return;
}
-
//Collect all SDC keyspaces
for (Table table : Table.values()) {
sdcKeyspaces.add(table.getTableDescription().getKeyspace());
}
-
- String janusGraphCfgFile = ConfigurationManager.getConfigurationManager()
- .getConfiguration().getJanusGraphCfgFile();
+ String janusGraphCfgFile = ConfigurationManager.getConfigurationManager().getConfiguration().getJanusGraphCfgFile();
Properties prop = new Properties();
-
try (final InputStream janusGraphProp = new FileInputStream(janusGraphCfgFile)) {
//load a properties file
prop.load(janusGraphProp);
@@ -87,34 +76,25 @@ public class CassandraHealthCheck {
} catch (Exception e) {
log.error("Failed to open janusGraph.properties file , url is : {}", janusGraphCfgFile, e);
}
-
log.info("All sdc keyspaces are : {}", sdcKeyspaces);
sdcSchemaUtils = new SdcSchemaUtils();
//Calculate the Formula of Health Check
try {
-
log.info("creating cluster for Cassandra Health Check.");
//Create cluster from nodes in cassandra configuration
-
Metadata metadata = sdcSchemaUtils.getMetadata();
-
if (metadata == null) {
log.error("Failure get cassandra metadata.");
return;
}
-
log.info("Cluster Metadata: {}", metadata);
List<KeyspaceMetadata> keyspaces = metadata.getKeyspaces();
List<Integer> replactionFactorList = new ArrayList<>();
-
//Collect the keyspaces Replication Factor of current localDataCenter
for (KeyspaceMetadata keyspace : keyspaces) {
-
- if (sdcKeyspaces.contains(keyspace.getName())) {
-
- log.info("keyspace : {} , replication: {}", keyspace.getName(), keyspace.getReplication());
+ if (sdcKeyspaces.contains(keyspace.getName())) {
+ log.info("keyspace : {} , replication: {}", keyspace.getName(), keyspace.getReplication());
Map<String, String> replicationOptions = keyspace.getReplication();
-
//In 1 site with one data center
if (replicationOptions.containsKey("replication_factor")) {
replactionFactorList.add(Integer.parseInt(replicationOptions.get("replication_factor")));
@@ -125,61 +105,43 @@ public class CassandraHealthCheck {
}
}
}
-
if (replactionFactorList.isEmpty()) {
log.error("Replication factor NOT found in all keyspaces");
return;
}
-
int maxReplicationFactor = Collections.max(replactionFactorList);
log.info("maxReplication Factor is: {}", maxReplicationFactor);
-
int localQuorum = maxReplicationFactor / 2 + 1;
log.info("localQuorum is: {}", localQuorum);
-
HC_FormulaNumber = maxReplicationFactor - localQuorum;
-
log.info("Health Check formula : Replication Factor – Local_Quorum = {}", HC_FormulaNumber);
-
-
} catch (Exception e) {
log.error("create cassandra cluster failed with exception.", e);
}
-
}
public boolean getCassandraStatus() {
-
if (GeneralUtility.isEmptyString(localDataCenterName)) {
log.error("localDataCenter Name in configuration.yaml is missing.");
return false;
}
-
try (final Session session = sdcSchemaUtils.connect()) {
log.info("creating cluster for Cassandra for monitoring.");
-
log.info("The cassandra session is {}", session);
if (session == null) {
log.error("Failed to connect to cassandra ");
return false;
}
-
Metadata metadata = sdcSchemaUtils.getMetadata();
-
if (metadata == null) {
log.error("Failure get cassandra metadata.");
return false;
}
-
log.info("The number of cassandra nodes is:{}", metadata.getAllHosts().size());
-
//Count the number of data center nodes that are down
- Long downHostsNumber = metadata.getAllHosts().stream()
- .filter(x -> x.getDatacenter().equals(localDataCenterName) && !x.isUp()).count();
-
+ Long downHostsNumber = metadata.getAllHosts().stream().filter(x -> x.getDatacenter().equals(localDataCenterName) && !x.isUp()).count();
log.info("The cassandra down nodes number is {}", downHostsNumber);
return HC_FormulaNumber >= downHostsNumber;
-
} catch (Exception e) {
log.error("create cassandra cluster failed with exception.", e);
return false;
@@ -188,7 +150,7 @@ public class CassandraHealthCheck {
@PreDestroy
public void closeClient() {
- if (sdcSchemaUtils!= null) {
+ if (sdcSchemaUtils != null) {
sdcSchemaUtils.closeCluster();
}
log.info("** sdcSchemaUtils cluster closed");
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java
index 754420dd47..1efb4b6b9c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,12 +17,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum;
import org.openecomp.sdc.be.datamodel.utils.NodeTypeConvertUtils;
import org.openecomp.sdc.be.datatypes.category.MetadataKeyDataDefinition;
@@ -41,27 +46,16 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
@Component("categoriesImportManager")
public class CategoriesImportManager {
+ private static final Logger log = Logger.getLogger(CategoriesImportManager.class.getName());
@javax.annotation.Resource
private IElementOperation elementOperation;
-
@javax.annotation.Resource
private ComponentsUtils componentsUtils;
- private static final Logger log = Logger.getLogger(CategoriesImportManager.class.getName());
-
public Either<Map<String, List<CategoryDefinition>>, ResponseFormat> createCategories(String categoriesTypesYml) {
-
Map<String, List<CategoryDefinition>> allCategories = createCategoriesFromYml(categoriesTypesYml);
return createCategoriesByDao(allCategories);
}
@@ -74,21 +68,21 @@ public class CategoriesImportManager {
NodeTypeEnum nodeTypeCategory = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.CATEGORY);
NodeTypeEnum nodeTypeSubCategory = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.SUBCATEGORY);
NodeTypeEnum nodeTypeGroup = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.GROUPING);
- log.debug("createCategoriesByDao: creating componentType:{} nodeTypeCategory:{} nodeTypeSubCategory:{} nodeTypeGroup:{}", componentType, nodeTypeCategory, nodeTypeSubCategory, nodeTypeGroup);
+ log.debug("createCategoriesByDao: creating componentType:{} nodeTypeCategory:{} nodeTypeSubCategory:{} nodeTypeGroup:{}", componentType,
+ nodeTypeCategory, nodeTypeSubCategory, nodeTypeGroup);
List<CategoryDefinition> newCategoriesvalue = new ArrayList<>();
for (CategoryDefinition category : entry.getValue()) {
-
Either<CategoryDefinition, ResponseFormat> createdCategoryRes = createCategorieDeo(entry, category, nodeTypeCategory);
if (createdCategoryRes.isRight()) {
return Either.right(createdCategoryRes.right().value());
}
-
CategoryDefinition newcategory = createdCategoryRes.left().value();
log.debug("createCategoriesByDao: create category was successful {}", newcategory);
List<SubCategoryDefinition> newsubcategories = new ArrayList<>();
List<SubCategoryDefinition> subcategories = category.getSubcategories();
if (subcategories != null) {
- boolean createdNewSubCategory = isCreatedNewSubCategory(entry, nodeTypeSubCategory, nodeTypeGroup, category, newcategory, newsubcategories, subcategories);
+ boolean createdNewSubCategory = isCreatedNewSubCategory(entry, nodeTypeSubCategory, nodeTypeGroup, category, newcategory,
+ newsubcategories, subcategories);
if (!createdNewSubCategory) {
return Either.right(createdCategoryRes.right().value());
}
@@ -101,9 +95,12 @@ public class CategoriesImportManager {
return Either.left(result);
}
- private boolean isCreatedNewSubCategory(Entry<String, List<CategoryDefinition>> entry, NodeTypeEnum nodeTypeSubCategory, NodeTypeEnum nodeTypeGroup, CategoryDefinition category, CategoryDefinition newcategory, List<SubCategoryDefinition> newsubcategories, List<SubCategoryDefinition> subcategories) {
+ private boolean isCreatedNewSubCategory(Entry<String, List<CategoryDefinition>> entry, NodeTypeEnum nodeTypeSubCategory,
+ NodeTypeEnum nodeTypeGroup, CategoryDefinition category, CategoryDefinition newcategory,
+ List<SubCategoryDefinition> newsubcategories, List<SubCategoryDefinition> subcategories) {
for (SubCategoryDefinition subcategory : subcategories) {
- Either<SubCategoryDefinition, ResponseFormat> createdSubCategory = createSubCategorieDeo(entry, newcategory, subcategory, nodeTypeSubCategory);
+ Either<SubCategoryDefinition, ResponseFormat> createdSubCategory = createSubCategorieDeo(entry, newcategory, subcategory,
+ nodeTypeSubCategory);
if (createdSubCategory.isRight()) {
return false;
}
@@ -112,7 +109,8 @@ public class CategoriesImportManager {
if (groupings != null) {
List<GroupingDefinition> newgroupings = new ArrayList<>();
for (GroupingDefinition grouping : groupings) {
- Either<GroupingDefinition, ResponseFormat> createdGrouping = createGroupingDeo(entry, grouping, subcategory, category, nodeTypeGroup);
+ Either<GroupingDefinition, ResponseFormat> createdGrouping = createGroupingDeo(entry, grouping, subcategory, category,
+ nodeTypeGroup);
if (createdGrouping.isRight()) {
return false;
}
@@ -125,10 +123,12 @@ public class CategoriesImportManager {
return true;
}
- private Either<GroupingDefinition, ResponseFormat> createGroupingDeo(Map.Entry<String, List<CategoryDefinition>> entry, GroupingDefinition grouping, SubCategoryDefinition subcategory, CategoryDefinition category, NodeTypeEnum nodeTypeGroup) {
-
+ private Either<GroupingDefinition, ResponseFormat> createGroupingDeo(Map.Entry<String, List<CategoryDefinition>> entry,
+ GroupingDefinition grouping, SubCategoryDefinition subcategory,
+ CategoryDefinition category, NodeTypeEnum nodeTypeGroup) {
log.debug("createGroupingDeo: creating grouping {}", grouping);
- Either<GroupingDefinition, ActionStatus> createdGrouping = elementOperation.createGrouping(subcategory.getUniqueId(), grouping, nodeTypeGroup);
+ Either<GroupingDefinition, ActionStatus> createdGrouping = elementOperation
+ .createGrouping(subcategory.getUniqueId(), grouping, nodeTypeGroup);
if (createdGrouping.isRight()) {
if (ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY == createdGrouping.right().value()) {
log.debug(" create grouping for {} group {} already exists ", entry.getKey(), grouping.getName());
@@ -139,28 +139,31 @@ public class CategoriesImportManager {
return Either.right(componentsUtils.getResponseFormat(createdGrouping.right().value()));
}
}
- log.debug("Failed to create groupingcategory for {} category {} subcategory {} grouping {} error {}", entry.getKey(),
- category.getName(), subcategory.getName(), grouping != null ? grouping.getName() : null,
- createdGrouping != null && createdGrouping.right() != null ? createdGrouping.right().value() : null);
-
+ log.debug("Failed to create groupingcategory for {} category {} subcategory {} grouping {} error {}", entry.getKey(), category.getName(),
+ subcategory.getName(), grouping != null ? grouping.getName() : null,
+ createdGrouping != null && createdGrouping.right() != null ? createdGrouping.right().value() : null);
return Either.right(componentsUtils.getResponseFormat(createdGrouping.right().value()));
} else {
log.debug("createGroupingDeo: create Grouping was successful {}", createdGrouping.left().value());
}
return Either.left(createdGrouping.left().value());
-
}
- private Either<SubCategoryDefinition, ResponseFormat> createSubCategorieDeo(Map.Entry<String, List<CategoryDefinition>> entry, CategoryDefinition newcategory, SubCategoryDefinition subcategory, NodeTypeEnum nodeTypeSubCategory) {
+ private Either<SubCategoryDefinition, ResponseFormat> createSubCategorieDeo(Map.Entry<String, List<CategoryDefinition>> entry,
+ CategoryDefinition newcategory, SubCategoryDefinition subcategory,
+ NodeTypeEnum nodeTypeSubCategory) {
log.debug("createSubCategorieDeo: creating subcategory {}", subcategory);
- Either<SubCategoryDefinition, ActionStatus> createdSubCategory = elementOperation.createSubCategory(newcategory.getUniqueId(), subcategory, nodeTypeSubCategory);
+ Either<SubCategoryDefinition, ActionStatus> createdSubCategory = elementOperation
+ .createSubCategory(newcategory.getUniqueId(), subcategory, nodeTypeSubCategory);
if (createdSubCategory.isRight() && ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY == createdSubCategory.right().value()) {
- log.debug(" create subcategory for {} category {} subcategory {} already exists, updating", entry.getKey(), newcategory.getName(), subcategory.getName());
+ log.debug(" create subcategory for {} category {} subcategory {} already exists, updating", entry.getKey(), newcategory.getName(),
+ subcategory.getName());
String subCategoryId = UniqueIdBuilder.buildSubCategoryUid(newcategory.getUniqueId(), subcategory.getNormalizedName());
createdSubCategory = elementOperation.updateSubCategory(subCategoryId, subcategory, nodeTypeSubCategory);
}
if (createdSubCategory.isRight()) {
- log.debug("Failed to create subcategory for {} category: {} subcategory: {} error {}", entry.getKey(), newcategory.getName(), subcategory.getName(), createdSubCategory.right().value());
+ log.debug("Failed to create subcategory for {} category: {} subcategory: {} error {}", entry.getKey(), newcategory.getName(),
+ subcategory.getName(), createdSubCategory.right().value());
return Either.right(componentsUtils.getResponseFormat(createdSubCategory.right().value()));
} else {
log.debug("createSubCategorieDeo: create subcategory was successful {}", createdSubCategory.left().value());
@@ -168,14 +171,14 @@ public class CategoriesImportManager {
return Either.left(createdSubCategory.left().value());
}
- private Either<CategoryDefinition, ResponseFormat> createCategorieDeo(Map.Entry<String, List<CategoryDefinition>> entry, CategoryDefinition category, NodeTypeEnum nodeTypeCategory) {
+ private Either<CategoryDefinition, ResponseFormat> createCategorieDeo(Map.Entry<String, List<CategoryDefinition>> entry,
+ CategoryDefinition category, NodeTypeEnum nodeTypeCategory) {
log.debug("createCategorieDeo: creating category {}", category);
Either<CategoryDefinition, ActionStatus> createdCategory = elementOperation.createCategory(category, nodeTypeCategory);
if (createdCategory.isRight() && ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS == createdCategory.right().value()) {
log.debug("createCategorieDeo: already exists, updating {}", category);
createdCategory = elementOperation.updateCategory(category, nodeTypeCategory);
}
-
if (createdCategory.isRight()) {
log.debug("Failed to create category for {} {} error {}", entry.getKey(), category.getName(), createdCategory.right().value());
return Either.right(componentsUtils.getResponseFormat(createdCategory.right().value()));
@@ -188,7 +191,6 @@ public class CategoriesImportManager {
private Map<String, List<CategoryDefinition>> createCategoriesFromYml(String categoriesTypesYml) {
Map<String, Object> toscaJson = (Map<String, Object>) new Yaml().load(categoriesTypesYml);
Map<String, List<CategoryDefinition>> allCategories = new HashMap<>();
-
Iterator<Entry<String, Object>> categoryEntryItr = toscaJson.entrySet().iterator();
while (categoryEntryItr.hasNext()) {
Entry<String, Object> categoryTypeEntry = categoryEntryItr.next();
@@ -196,20 +198,20 @@ public class CategoriesImportManager {
List<CategoryDefinition> categoriesPerType = null;
Map<String, Object> categoryPerType = null;
switch (categoryType) {
- case ComponentTypeEnum.SERVICE_PARAM_NAME:
- categoryPerType = (Map<String, Object>) categoryTypeEntry.getValue();
- categoriesPerType = createServiceCategories(categoryPerType);
- break;
- case ComponentTypeEnum.RESOURCE_PARAM_NAME:
- categoryPerType = (Map<String, Object>) categoryTypeEntry.getValue();
- categoriesPerType = createResourceCategories(categoryPerType);
- break;
- case ComponentTypeEnum.PRODUCT_PARAM_NAME:
- // TODO
- break;
- default:
- log.debug("Not supported category type - {}", categoryType);
- break;
+ case ComponentTypeEnum.SERVICE_PARAM_NAME:
+ categoryPerType = (Map<String, Object>) categoryTypeEntry.getValue();
+ categoriesPerType = createServiceCategories(categoryPerType);
+ break;
+ case ComponentTypeEnum.RESOURCE_PARAM_NAME:
+ categoryPerType = (Map<String, Object>) categoryTypeEntry.getValue();
+ categoriesPerType = createResourceCategories(categoryPerType);
+ break;
+ case ComponentTypeEnum.PRODUCT_PARAM_NAME:
+ // TODO
+ break;
+ default:
+ log.debug("Not supported category type - {}", categoryType);
+ break;
}
if (categoriesPerType != null) {
allCategories.put(categoryType, categoriesPerType);
@@ -232,18 +234,18 @@ public class CategoriesImportManager {
String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(catName);
catDef.setNormalizedName(normalizedName);
final Object useServiceSubstitutionForNestedServicesProperty = category.get("useServiceSubstitutionForNestedServices");
- final boolean useServiceSubstitutionForNestedServices = useServiceSubstitutionForNestedServicesProperty == null ?
- false : (Boolean) useServiceSubstitutionForNestedServicesProperty;
+ final boolean useServiceSubstitutionForNestedServices =
+ useServiceSubstitutionForNestedServicesProperty == null ? false : (Boolean) useServiceSubstitutionForNestedServicesProperty;
catDef.setUseServiceSubstitutionForNestedServices(useServiceSubstitutionForNestedServices);
catDef.setMetadataKeys(getMetadataKeys(category));
categoriesDef.add(catDef);
}
-
return categoriesDef;
}
-
+
private List<MetadataKeyDataDefinition> getMetadataKeys(Map<String, Object> parentObject) {
- Map<String, Object> metadataKeys = (Map<String, Object>) parentObject.getOrDefault(MetadataKeyEnum.METADATA_KEYS.getName(), Collections.EMPTY_MAP);
+ Map<String, Object> metadataKeys = (Map<String, Object>) parentObject
+ .getOrDefault(MetadataKeyEnum.METADATA_KEYS.getName(), Collections.EMPTY_MAP);
List<MetadataKeyDataDefinition> metadataKeyDefs = new ArrayList<>();
for (Entry<String, Object> metadataKey : metadataKeys.entrySet()) {
Map<String, Object> metadataKeyInfo = (Map<String, Object>) metadataKey.getValue();
@@ -284,7 +286,6 @@ public class CategoriesImportManager {
subDef.setMetadataKeys(getMetadataKeys(subcategoryInfo));
subcateDef.add(subDef);
}
-
catDef.setSubcategories(subcateDef);
categroiesDef.add(catDef);
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java
index c3ecda3e03..326022d806 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,10 +19,21 @@
* Modifications copyright (c) 2019 Nokia
* ================================================================================
*/
-
package org.openecomp.sdc.be.components.impl;
+import static java.util.stream.Collectors.toList;
+
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.function.BiFunction;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
@@ -47,24 +58,10 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.function.BiFunction;
-import java.util.function.Consumer;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
-import static java.util.stream.Collectors.toList;
-
@Component("commonImportManager")
public class CommonImportManager {
private static final Logger log = Logger.getLogger(CommonImportManager.class.getName());
-
private final ComponentsUtils componentsUtils;
private final PropertyOperation propertyOperation;
@@ -81,12 +78,10 @@ public class CommonImportManager {
private static List<PropertyDefinition> getProperties(Map<String, Object> toscaJson) {
List<PropertyDefinition> values = null;
Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(toscaJson);
-
if (properties.isLeft()) {
values = new ArrayList<>();
Map<String, PropertyDefinition> propertiesMap = properties.left().value();
if (propertiesMap != null && !propertiesMap.isEmpty()) {
-
for (Entry<String, PropertyDefinition> entry : propertiesMap.entrySet()) {
String propName = entry.getKey();
PropertyDefinition propertyDefinition = entry.getValue();
@@ -96,28 +91,27 @@ public class CommonImportManager {
}
}
}
-
return values;
}
+ private static <T> List<T> append(List<T> list, T value) {
+ list.add(value);
+ return list;
+ }
+
protected void setPropertiesMap(Map<String, Object> toscaJson, Consumer<Map<String, PropertyDefinition>> consumer) {
final List<PropertyDefinition> properties = getProperties(toscaJson);
if (properties != null) {
- Map<String, PropertyDefinition> collect = properties.stream()
- .collect(Collectors.toMap(PropertyDefinition::getName, Function.identity()));
+ Map<String, PropertyDefinition> collect = properties.stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity()));
consumer.accept(collect);
}
}
- public interface ICreateElementType<T1, T2, T3> {
- T3 createElement(T1 firstArg, T2 secondArg);
- }
-
- protected <T> Either<List<T>, ActionStatus> createElementTypesFromYml(String elementTypesYml, ICreateElementType<String, Map<String, Object>, T> createApi) {
-
+ protected <T> Either<List<T>, ActionStatus> createElementTypesFromYml(String elementTypesYml,
+ ICreateElementType<String, Map<String, Object>, T> createApi) {
List<T> elementTypes;
Map<String, Object> toscaJson = convertToFieldMap(elementTypesYml);
- if (toscaJson==null) {
+ if (toscaJson == null) {
return Either.right(ActionStatus.INVALID_YAML_FILE);
}
elementTypes = createElementTypesFromToscaJsonMap(createApi, toscaJson);
@@ -135,11 +129,9 @@ public class CommonImportManager {
return toscaJson;
}
-
- protected <T extends ToscaDataDefinition> List<T> createTypesFromToscaJsonMap(
- BiFunction<String, Map<String, Object>, T> createApi, Map<String, Object> toscaJson) {
+ protected <T extends ToscaDataDefinition> List<T> createTypesFromToscaJsonMap(BiFunction<String, Map<String, Object>, T> createApi,
+ Map<String, Object> toscaJson) {
List<T> elementTypes = new ArrayList<>();
-
for (Entry<String, Object> elementTypeNameDataEntry : toscaJson.entrySet()) {
String elementTypeName = elementTypeNameDataEntry.getKey();
Map<String, Object> elementTypeJsonData = (Map<String, Object>) elementTypeNameDataEntry.getValue();
@@ -149,10 +141,9 @@ public class CommonImportManager {
return elementTypes;
}
- protected <T> List<T> createElementTypesFromToscaJsonMap(
- ICreateElementType<String, Map<String, Object>, T> createApi, Map<String, Object> toscaJson) {
+ protected <T> List<T> createElementTypesFromToscaJsonMap(ICreateElementType<String, Map<String, Object>, T> createApi,
+ Map<String, Object> toscaJson) {
List<T> elementTypes = new ArrayList<>();
-
for (Entry<String, Object> elementTypeNameDataEntry : toscaJson.entrySet()) {
String elementTypeName = elementTypeNameDataEntry.getKey();
Map<String, Object> elementTypeJsonData = (Map<String, Object>) elementTypeNameDataEntry.getValue();
@@ -162,10 +153,9 @@ public class CommonImportManager {
return elementTypes;
}
- protected <T> Map<String, T> createElementTypesMapFromToscaJsonMap(
- ICreateElementType<String, Map<String, Object>, T> createApi, Map<String, Object> toscaJson) {
+ protected <T> Map<String, T> createElementTypesMapFromToscaJsonMap(ICreateElementType<String, Map<String, Object>, T> createApi,
+ Map<String, Object> toscaJson) {
Map<String, T> elementTypesMap = new HashMap<>();
-
Iterator<Entry<String, Object>> elementTypesEntryItr = toscaJson.entrySet().iterator();
while (elementTypesEntryItr.hasNext()) {
Entry<String, Object> elementTypeNameDataEntry = elementTypesEntryItr.next();
@@ -184,31 +174,27 @@ public class CommonImportManager {
}
}
- public enum ElementTypeEnum {
- POLICY_TYPE, GROUP_TYPE, DATA_TYPE, CAPABILITY_TYPE, INTERFACE_LIFECYCLE_TYPE, RELATIONSHIP_TYPE
- }
-
private ActionStatus convertFromStorageResponseForElementType(StorageOperationStatus status, ElementTypeEnum elementTypeEnum) {
ActionStatus ret;
switch (elementTypeEnum) {
- case GROUP_TYPE:
- ret = componentsUtils.convertFromStorageResponseForGroupType(status);
- break;
- case DATA_TYPE:
- ret = componentsUtils.convertFromStorageResponseForDataType(status);
- break;
- case CAPABILITY_TYPE:
- ret = componentsUtils.convertFromStorageResponseForCapabilityType(status);
- break;
- case INTERFACE_LIFECYCLE_TYPE:
- ret = componentsUtils.convertFromStorageResponseForLifecycleType(status);
- break;
- case RELATIONSHIP_TYPE:
- ret = componentsUtils.convertFromStorageResponseForRelationshipType(status);
- break;
- default:
- ret = componentsUtils.convertFromStorageResponse(status);
- break;
+ case GROUP_TYPE:
+ ret = componentsUtils.convertFromStorageResponseForGroupType(status);
+ break;
+ case DATA_TYPE:
+ ret = componentsUtils.convertFromStorageResponseForDataType(status);
+ break;
+ case CAPABILITY_TYPE:
+ ret = componentsUtils.convertFromStorageResponseForCapabilityType(status);
+ break;
+ case INTERFACE_LIFECYCLE_TYPE:
+ ret = componentsUtils.convertFromStorageResponseForLifecycleType(status);
+ break;
+ case RELATIONSHIP_TYPE:
+ ret = componentsUtils.convertFromStorageResponseForRelationshipType(status);
+ break;
+ default:
+ ret = componentsUtils.convertFromStorageResponse(status);
+ break;
}
return ret;
}
@@ -216,22 +202,21 @@ public class CommonImportManager {
private <T> ResponseFormat getResponseFormatForElementType(ActionStatus actionStatus, ElementTypeEnum elementTypeEnum, T elementTypeDefinition) {
ResponseFormat ret;
switch (elementTypeEnum) {
- case GROUP_TYPE:
- ret = componentsUtils.getResponseFormatByGroupType(actionStatus, (GroupTypeDefinition) elementTypeDefinition);
- break;
- case POLICY_TYPE:
- ret = componentsUtils.getResponseFormatByPolicyType(actionStatus, (PolicyTypeDefinition) elementTypeDefinition);
- break;
- case DATA_TYPE:
- ret = componentsUtils.getResponseFormatByDataType(actionStatus, (DataTypeDefinition) elementTypeDefinition, null);
- break;
- case CAPABILITY_TYPE:
- ret = componentsUtils.getResponseFormatByCapabilityType(actionStatus, (CapabilityTypeDefinition) elementTypeDefinition);
- break;
-
- default:
- ret = componentsUtils.getResponseFormat(actionStatus);
- break;
+ case GROUP_TYPE:
+ ret = componentsUtils.getResponseFormatByGroupType(actionStatus, (GroupTypeDefinition) elementTypeDefinition);
+ break;
+ case POLICY_TYPE:
+ ret = componentsUtils.getResponseFormatByPolicyType(actionStatus, (PolicyTypeDefinition) elementTypeDefinition);
+ break;
+ case DATA_TYPE:
+ ret = componentsUtils.getResponseFormatByDataType(actionStatus, (DataTypeDefinition) elementTypeDefinition, null);
+ break;
+ case CAPABILITY_TYPE:
+ ret = componentsUtils.getResponseFormatByCapabilityType(actionStatus, (CapabilityTypeDefinition) elementTypeDefinition);
+ break;
+ default:
+ ret = componentsUtils.getResponseFormat(actionStatus);
+ break;
}
return ret;
}
@@ -264,11 +249,13 @@ public class CommonImportManager {
}
return createdElementTypes;
}
-
+
protected <T> Either<List<ImmutablePair<T, Boolean>>, ResponseFormat> createElementTypesByDao(List<T> elementTypesToCreate,
- Function<T, Either<ActionStatus, ResponseFormat>> validator, Function<T, ImmutablePair<ElementTypeEnum, String>> elementInfoGetter,
- Function<String, Either<T, StorageOperationStatus>> elementFetcher, Function<T, Either<T, StorageOperationStatus>> elementAdder,
- BiFunction<T, T, Either<T, StorageOperationStatus>> elementUpgrader) {
+ Function<T, Either<ActionStatus, ResponseFormat>> validator,
+ Function<T, ImmutablePair<ElementTypeEnum, String>> elementInfoGetter,
+ Function<String, Either<T, StorageOperationStatus>> elementFetcher,
+ Function<T, Either<T, StorageOperationStatus>> elementAdder,
+ BiFunction<T, T, Either<T, StorageOperationStatus>> elementUpgrader) {
List<ImmutablePair<T, Boolean>> createdElementTypes = new ArrayList<>();
@@ -279,49 +266,42 @@ public class CommonImportManager {
while (elementTypeItr.hasNext()) {
T elementType = elementTypeItr.next();
eitherResult = handleType(elementType, validator, elementInfoGetter, elementFetcher, elementAdder, elementUpgrader)
- .left()
- .map(elem -> append(createdElementTypes, elem));
-
+ .left()
+ .map(elem -> append(createdElementTypes, elem));
+
if (eitherResult.isRight()) {
break;
}
-
- if(!elementTypeItr.hasNext()) {
+
+ if (!elementTypeItr.hasNext()) {
log.info("all {} were created successfully!!!", elementType);
}
}
- }
- catch(Exception e) {
+ } catch (Exception e) {
eitherResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
throw e;
- }
- finally {
+ } finally {
if (eitherResult.isLeft()) {
propertyOperation.getJanusGraphGenericDao().commit();
- }
- else {
+ } else {
propertyOperation.getJanusGraphGenericDao().rollback();
}
}
return eitherResult;
}
-
- private static <T> List<T> append(List<T> list, T value) {
- list.add(value);
- return list;
- }
-
-
- private <T> Either<ImmutablePair<T, Boolean>, ResponseFormat> handleType(T elementType,
- Function<T, Either<ActionStatus, ResponseFormat>> validator, Function<T, ImmutablePair<ElementTypeEnum, String>> elementInfoGetter,
- Function<String, Either<T, StorageOperationStatus>> elementFetcher, Function<T, Either<T, StorageOperationStatus>> elementAdder,
- BiFunction<T, T, Either<T, StorageOperationStatus>> elementUpgrader) {
-
+
+ private <T> Either<ImmutablePair<T, Boolean>, ResponseFormat> handleType(T elementType,
+ Function<T, Either<ActionStatus, ResponseFormat>> validator,
+ Function<T, ImmutablePair<ElementTypeEnum, String>> elementInfoGetter,
+ Function<String, Either<T, StorageOperationStatus>> elementFetcher,
+ Function<T, Either<T, StorageOperationStatus>> elementAdder,
+ BiFunction<T, T, Either<T, StorageOperationStatus>> elementUpgrader) {
+
final ImmutablePair<ElementTypeEnum, String> elementInfo = elementInfoGetter.apply(elementType);
ElementTypeEnum elementTypeEnum = elementInfo.left;
String elementName = elementInfo.right;
-
+
Either<ActionStatus, ResponseFormat> validateElementType = validator.apply(elementType);
if (validateElementType.isRight()) {
ResponseFormat responseFormat = validateElementType.right().value();
@@ -336,7 +316,8 @@ public class CommonImportManager {
StorageOperationStatus status = findElementType.right().value();
log.debug("searched {} finished with result:{}", elementTypeEnum, status);
if (status != StorageOperationStatus.NOT_FOUND) {
- ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(status, elementTypeEnum), elementTypeEnum, elementType);
+ ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(status, elementTypeEnum),
+ elementTypeEnum, elementType);
return Either.right(responseFormat);
} else {
return addElementType(elementType, elementAdder, elementTypeEnum, elementName);
@@ -356,15 +337,18 @@ public class CommonImportManager {
}
}
- private <T> Either<ImmutablePair<T, Boolean>, ResponseFormat> addElementType(T elementType, Function<T, Either<T, StorageOperationStatus>> elementAdder, ElementTypeEnum elementTypeEnum, String elementName) {
+ private <T> Either<ImmutablePair<T, Boolean>, ResponseFormat> addElementType(T elementType,
+ Function<T, Either<T, StorageOperationStatus>> elementAdder,
+ ElementTypeEnum elementTypeEnum, String elementName) {
Either<T, StorageOperationStatus> dataModelResponse = elementAdder.apply(elementType);
-
+
if (dataModelResponse.isRight()) {
BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("Create {}", elementTypeEnum.name());
log.debug("failed to create {}: {}", elementTypeEnum, elementName);
if (dataModelResponse.right().value() != StorageOperationStatus.OK) {
- ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(dataModelResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType);
-
+ ResponseFormat responseFormat = getResponseFormatForElementType(
+ convertFromStorageResponseForElementType(dataModelResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType);
+
return Either.right(responseFormat);
} else {
return Either.left(new ImmutablePair<>(elementType, false));
@@ -374,17 +358,19 @@ public class CommonImportManager {
return Either.left(new ImmutablePair<>(elementType, true));
}
}
-
-
- private <T> Either<ImmutablePair<T, Boolean>, ResponseFormat> updateElementType(T elementType, BiFunction<T, T, Either<T, StorageOperationStatus>> elementUpgrader,
- ElementTypeEnum elementTypeEnum, String elementName, T existingElementType) {
+
+ private <T> Either<ImmutablePair<T, Boolean>, ResponseFormat> updateElementType(T elementType,
+ BiFunction<T, T, Either<T, StorageOperationStatus>> elementUpgrader,
+ ElementTypeEnum elementTypeEnum, String elementName,
+ T existingElementType) {
Either<T, StorageOperationStatus> upgradeResponse = elementUpgrader.apply(elementType, existingElementType);
if (upgradeResponse.isRight()) {
StorageOperationStatus status = upgradeResponse.right().value();
if (status == StorageOperationStatus.OK) {
return Either.left(new ImmutablePair<>(elementType, false));
} else {
- ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(upgradeResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType);
+ ResponseFormat responseFormat = getResponseFormatForElementType(
+ convertFromStorageResponseForElementType(upgradeResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType);
return Either.right(responseFormat);
}
} else {
@@ -393,34 +379,35 @@ public class CommonImportManager {
}
}
-
- public <T extends ToscaTypeDataDefinition> Either<List<ImmutablePair<T, Boolean>>, ResponseFormat> createElementTypes(ToscaTypeImportData toscaTypeImportData, Function<String, Either<List<T>, ActionStatus>> elementTypeFromYmlCreater,
- Function<List<T>, Either<List<ImmutablePair<T, Boolean>>, ResponseFormat>> elementTypeDaoCreater) {
+ public <T extends ToscaTypeDataDefinition> Either<List<ImmutablePair<T, Boolean>>, ResponseFormat> createElementTypes(
+ ToscaTypeImportData toscaTypeImportData, Function<String, Either<List<T>, ActionStatus>> elementTypeFromYmlCreater,
+ Function<List<T>, Either<List<ImmutablePair<T, Boolean>>, ResponseFormat>> elementTypeDaoCreater) {
Either<List<T>, ActionStatus> elementTypes = elementTypeFromYmlCreater.apply(toscaTypeImportData.getToscaTypesYml());
return elementTypes
- .right()
- .map(err -> componentsUtils.getResponseFormat(err, ""))
- .left()
- .map(toscaTypes -> enrichTypesWithNonToscaMetadata(toscaTypes, toscaTypeImportData.getToscaTypeMetadata()))
- .left()
- .bind(elementTypeDaoCreater::apply);
+ .right()
+ .map(err -> componentsUtils.getResponseFormat(err, ""))
+ .left()
+ .map(toscaTypes -> enrichTypesWithNonToscaMetadata(toscaTypes, toscaTypeImportData.getToscaTypeMetadata()))
+ .left()
+ .bind(elementTypeDaoCreater::apply);
}
public <T extends ToscaDataDefinition> List<ImmutablePair<T, Boolean>> createElementTypes(String toscaTypesYml,
BiFunction<String, Map<String, Object>, T> createApi,
TypeOperations<T> typeOperations) {
Map<String, Object> fieldMap = convertToFieldMap(toscaTypesYml);
- if (fieldMap==null) {
+ if (fieldMap == null) {
throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML_FILE);
}
List<T> elementTypes = createTypesFromToscaJsonMap(createApi, fieldMap);
return createTypesByDao(elementTypes, typeOperations);
}
- private <T extends ToscaTypeDataDefinition> List<T> enrichTypesWithNonToscaMetadata(List<T> toscaTypes, Map<String, ToscaTypeMetadata> toscaTypeMetadata) {
+ private <T extends ToscaTypeDataDefinition> List<T> enrichTypesWithNonToscaMetadata(List<T> toscaTypes,
+ Map<String, ToscaTypeMetadata> toscaTypeMetadata) {
return toscaTypes.stream()
- .map(toscaType -> setNonToscaMetaDataOnType(toscaTypeMetadata, toscaType))
- .collect(toList());
+ .map(toscaType -> setNonToscaMetaDataOnType(toscaTypeMetadata, toscaType))
+ .collect(toList());
}
private <T extends ToscaTypeDataDefinition> T setNonToscaMetaDataOnType(Map<String, ToscaTypeMetadata> toscaTypeMetadata, T toscaTypeDefinition) {
@@ -435,8 +422,10 @@ public class CommonImportManager {
return toscaTypeDefinition;
}
- public <T> Either<List<ImmutablePair<T, Boolean>>, ResponseFormat> createElementTypes(String elementTypesYml, Function<String, Either<List<T>, ActionStatus>> elementTypeFromYmlCreater,
- Function<List<T>, Either<List<ImmutablePair<T, Boolean>>, ResponseFormat>> elementTypeDaoCreater, ElementTypeEnum elementTypeEnum) {
+ public <T> Either<List<ImmutablePair<T, Boolean>>, ResponseFormat> createElementTypes(String elementTypesYml,
+ Function<String, Either<List<T>, ActionStatus>> elementTypeFromYmlCreater,
+ Function<List<T>, Either<List<ImmutablePair<T, Boolean>>, ResponseFormat>> elementTypeDaoCreater,
+ ElementTypeEnum elementTypeEnum) {
Either<List<T>, ActionStatus> elementTypes = elementTypeFromYmlCreater.apply(elementTypesYml);
if (elementTypes.isRight()) {
@@ -447,4 +436,13 @@ public class CommonImportManager {
return elementTypeDaoCreater.apply(elementTypes.left().value());
}
+
+ public enum ElementTypeEnum {
+ POLICY_TYPE, GROUP_TYPE, DATA_TYPE, CAPABILITY_TYPE, INTERFACE_LIFECYCLE_TYPE, RELATIONSHIP_TYPE
+ }
+
+ public interface ICreateElementType<T1, T2, T3> {
+
+ T3 createElement(T1 firstArg, T2 secondArg);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java
index efab8592c1..9ce54c2cc8 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,13 +19,18 @@
* Modifications copyright (c) 2019 Nokia
* ================================================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.BooleanSupplier;
+import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
@@ -96,51 +101,31 @@ import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.stream.Collectors;
-
public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
- protected ArtifactsBusinessLogic artifactsBusinessLogic;
-
+ private static final Logger log = Logger.getLogger(ComponentBusinessLogic.class.getName());
protected final GroupBusinessLogic groupBusinessLogic;
-
+ protected ArtifactsBusinessLogic artifactsBusinessLogic;
protected GenericTypeBusinessLogic genericTypeBusinessLogic;
-
protected ComponentDescriptionValidator componentDescriptionValidator;
protected ComponentProjectCodeValidator componentProjectCodeValidator;
-
protected CatalogOperation catalogOperations;
protected ComponentIconValidator componentIconValidator;
-
protected ComponentValidator componentValidator;
protected ComponentTagsValidator componentTagsValidator;
protected ComponentNameValidator componentNameValidator;
protected ComponentContactIdValidator componentContactIdValidator;
- public ComponentBusinessLogic(IElementOperation elementDao,
- IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation,
- IGroupTypeOperation groupTypeOperation,
- GroupBusinessLogic groupBusinessLogic,
- InterfaceOperation interfaceOperation,
- InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
- ArtifactsBusinessLogic artifactsBusinessLogic,
- ArtifactsOperations artifactToscaOperation,
- ComponentContactIdValidator componentContactIdValidator,
- ComponentNameValidator componentNameValidator,
- ComponentTagsValidator componentTagsValidator,
- ComponentValidator componentValidator,
- ComponentIconValidator componentIconValidator,
- ComponentProjectCodeValidator componentProjectCodeValidator,
- ComponentDescriptionValidator componentDescriptionValidator){
-
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
- interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+ public ComponentBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+ IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic,
+ InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+ ArtifactsBusinessLogic artifactsBusinessLogic, ArtifactsOperations artifactToscaOperation,
+ ComponentContactIdValidator componentContactIdValidator, ComponentNameValidator componentNameValidator,
+ ComponentTagsValidator componentTagsValidator, ComponentValidator componentValidator,
+ ComponentIconValidator componentIconValidator, ComponentProjectCodeValidator componentProjectCodeValidator,
+ ComponentDescriptionValidator componentDescriptionValidator) {
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+ artifactToscaOperation);
this.artifactsBusinessLogic = artifactsBusinessLogic;
this.groupBusinessLogic = groupBusinessLogic;
this.componentContactIdValidator = componentContactIdValidator;
@@ -152,6 +137,33 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
this.componentDescriptionValidator = componentDescriptionValidator;
}
+ private static Either<ArtifactDefinition, Operation> saveToscaArtifactAndPopulateToscaArtifactsWithResult(Component component,
+ final ComponentsUtils componentsUtils,
+ final ArtifactTypeEnum artifactEnum,
+ final BiFunction<Component, ArtifactDefinition, Either<ArtifactDefinition, Operation>> saveToscaArtifactPayloadFunction) {
+ ArtifactDefinition artifactDefinition = getToscaArtifactByTypeOrThrowException(component, artifactEnum, componentsUtils);
+ Either<ArtifactDefinition, Operation> result = saveToscaArtifactPayloadFunction.apply(component, artifactDefinition);
+ if (result.isLeft()) {
+ ArtifactDefinition def = result.left().value();
+ component.getToscaArtifacts().put(def.getArtifactLabel(), def);
+ }
+ return result;
+ }
+
+ private static Optional<ArtifactDefinition> getToscaArtifactByType(final Map<String, ArtifactDefinition> toscaArtifacts,
+ final ArtifactTypeEnum typeEnum) {
+ return toscaArtifacts.values().stream().filter(p -> p.getArtifactType().equals(typeEnum.getType())).findAny();
+ }
+
+ private static ArtifactDefinition getToscaArtifactByTypeOrThrowException(final Component component, final ArtifactTypeEnum typeEnum,
+ final ComponentsUtils componentsUtils) {
+ return Optional.ofNullable(component.getToscaArtifacts()).flatMap(toscaArtifacts -> getToscaArtifactByType(toscaArtifacts, typeEnum))
+ .orElseThrow(() -> {
+ log.debug("Impossible to find a ToscaArtifact with type '{}' for {}", typeEnum.getType(), component);
+ return new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, typeEnum.name()));
+ });
+ }
+
public void setComponentDescriptionValidator(ComponentDescriptionValidator componentDescriptionValidator) {
this.componentDescriptionValidator = componentDescriptionValidator;
}
@@ -176,27 +188,25 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
this.componentNameValidator = componentNameValidator;
}
-
@Autowired
public void setGenericTypeBusinessLogic(GenericTypeBusinessLogic genericTypeBusinessLogic) {
this.genericTypeBusinessLogic = genericTypeBusinessLogic;
}
- private static final Logger log = Logger.getLogger(ComponentBusinessLogic.class.getName());
-
public abstract Either<List<String>, ResponseFormat> deleteMarkedComponents();
public abstract ComponentInstanceBusinessLogic getComponentInstanceBL();
- public abstract Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, String userId);
+ public abstract Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId,
+ String userId);
/**
- *
* @param componentId
* @param dataParamsToReturn
* @return
*/
- public abstract Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId, List<String> dataParamsToReturn);
+ public abstract Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId,
+ List<String> dataParamsToReturn);
User validateUser(User user, String ecompErrorContext, Component component, AuditingActionEnum auditAction, boolean inTransaction) {
User validatedUser;
@@ -204,14 +214,14 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
try {
validateUserNotEmpty(user, ecompErrorContext);
validatedUser = validateUserExists(user);
- } catch(ByActionStatusComponentException e){
- if(e.getActionStatus() == ActionStatus.MISSING_INFORMATION){
+ } catch (ByActionStatusComponentException e) {
+ if (e.getActionStatus() == ActionStatus.MISSING_INFORMATION) {
user.setUserId("UNKNOWN");
}
responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
componentsUtils.auditComponentAdmin(responseFormat, user, component, auditAction, component.getComponentType());
throw e;
- } catch(ByResponseFormatComponentException e){
+ } catch (ByResponseFormatComponentException e) {
responseFormat = e.getResponseFormat();
componentsUtils.auditComponentAdmin(responseFormat, user, component, auditAction, component.getComponentType());
throw e;
@@ -226,69 +236,64 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
}
try {
validateUserRole(user, roles);
- }catch (ByActionStatusComponentException e) {
+ } catch (ByActionStatusComponentException e) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
handleComponentException(component, comment, responseFormat, user, auditAction);
throw e;
- }catch (ByResponseFormatComponentException e) {
+ } catch (ByResponseFormatComponentException e) {
ResponseFormat responseFormat = e.getResponseFormat();
handleComponentException(component, comment, responseFormat, user, auditAction);
throw e;
}
}
- private void handleComponentException(Component component, String comment, ResponseFormat responseFormat,
- User user, AuditingActionEnum auditAction){
+ private void handleComponentException(Component component, String comment, ResponseFormat responseFormat, User user,
+ AuditingActionEnum auditAction) {
String commentStr = null;
String distrStatus = null;
ComponentTypeEnum componentType = component.getComponentType();
- if (componentType == ComponentTypeEnum.SERVICE) {
- distrStatus = ((ServiceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getDistributionStatus();
+ if (componentType == ComponentTypeEnum.SERVICE) {
+ distrStatus = ((ServiceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition())
+ .getDistributionStatus();
commentStr = comment;
}
componentsUtils.auditComponent(responseFormat, user, component, auditAction, new ResourceCommonInfo(componentType.getValue()),
ResourceVersionInfo.newBuilder().distributionStatus(distrStatus).build(),
- ResourceVersionInfo.newBuilder().distributionStatus(distrStatus).build(),
- commentStr, null, null);
+ ResourceVersionInfo.newBuilder().distributionStatus(distrStatus).build(), commentStr, null, null);
}
public Either<Boolean, ResponseFormat> validateConformanceLevel(String componentUuid, ComponentTypeEnum componentTypeEnum, String userId) {
log.trace("validate conformance level");
-
if (componentTypeEnum != ComponentTypeEnum.SERVICE) {
log.error("conformance level validation for non service component, id {}", componentUuid);
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
return Either.right(errorResponse);
}
-
validateUserExists(userId);
-
- Either<ComponentMetadataData, StorageOperationStatus> eitherComponent = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, null);
+ Either<ComponentMetadataData, StorageOperationStatus> eitherComponent = toscaOperationFacade
+ .getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, null);
if (eitherComponent.isRight()) {
log.error("can't validate conformance level, component not found, uuid {}", componentUuid);
BeEcompErrorManager.getInstance().logBeComponentMissingError("validateConformanceLevel", componentTypeEnum.getValue(), componentUuid);
-
StorageOperationStatus status = eitherComponent.right().value();
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(status, componentTypeEnum);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus);
return Either.right(responseFormat);
}
-
String componentConformanceLevel = eitherComponent.left().value().getMetadataDataDefinition().getConformanceLevel();
if (StringUtils.isBlank(componentConformanceLevel)) {
log.error("component conformance level property is null or empty, uuid {}", componentUuid);
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
return Either.right(errorResponse);
}
-
String configConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getMinToscaConformanceLevel();
Boolean result = true;
if (CommonBeUtils.conformanceLevelCompare(componentConformanceLevel, configConformanceLevel) < 0) {
- log.error("invalid asset conformance level, uuid {}, asset conformanceLevel {}, config conformanceLevel {}", componentUuid, componentConformanceLevel, configConformanceLevel);
+ log.error("invalid asset conformance level, uuid {}, asset conformanceLevel {}, config conformanceLevel {}", componentUuid,
+ componentConformanceLevel, configConformanceLevel);
result = false;
}
log.trace("conformance level validation finished");
-
return Either.left(result);
}
@@ -304,9 +309,9 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
}
try {
validateIcon(icon, type);
- } catch(ComponentException e){
- ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
- : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
+ } catch (ComponentException e) {
+ ResponseFormat responseFormat =
+ e.getResponseFormat() != null ? e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, type);
throw e;
}
@@ -318,7 +323,6 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
log.debug("icon exceeds max length");
throw new ComponentException(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH);
}
-
if (!ValidationUtils.validateIcon(icon)) {
log.info("icon is invalid.");
throw new ComponentException(ActionStatus.COMPONENT_INVALID_ICON, type.getValue());
@@ -377,67 +381,70 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
log.debug("validate icon");
validateIcon(user, component, actionEnum);
}
-
- public CapReqDef getRequirementsAndCapabilities(String componentId, ComponentTypeEnum componentTypeEnum, String userId) {
+ public CapReqDef getRequirementsAndCapabilities(String componentId, ComponentTypeEnum componentTypeEnum, String userId) {
validateUserExists(userId);
ComponentParametersView filter = new ComponentParametersView(true);
filter.setIgnoreCapabilities(false);
filter.setIgnoreRequirements(false);
filter.setIgnoreComponentInstances(false);
-
try {
Component component = validateComponentExists(componentId, componentTypeEnum, filter);
return new CapReqDef(component.getRequirements(), component.getCapabilities());
- }catch (ComponentException e){
+ } catch (ComponentException e) {
BeEcompErrorManager.getInstance().logBeComponentMissingError("getRequirementsAndCapabilities", componentTypeEnum.getValue(), componentId);
throwComponentException(e.getResponseFormat());
}
return null;
}
- public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponents(boolean isAbstractAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids,
+ public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponents(boolean isAbstractAbstract,
+ ComponentTypeEnum componentTypeEnum,
+ String internalComponentType, List<String> componentUids,
String userId) {
- try{
+ try {
validateUserExists(userId);
List<Component> result = new ArrayList<>();
List<String> componentsUidToFetch = new ArrayList<>();
componentsUidToFetch.addAll(componentUids);
if (!componentsUidToFetch.isEmpty()) {
log.debug("Number of Components to fetch from graph is {}", componentsUidToFetch.size());
- Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractComponents(isAbstractAbstract, componentTypeEnum, internalComponentType, componentsUidToFetch);
-
+ Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade
+ .getLatestVersionNotAbstractComponents(isAbstractAbstract, componentTypeEnum, internalComponentType, componentsUidToFetch);
if (nonCheckoutCompResponse.isLeft()) {
log.debug("Retrived Resource successfully.");
result.addAll(nonCheckoutCompResponse.left().value());
} else {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())));
+ return Either.right(
+ componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())));
}
}
return Either.left(result);
- }
- finally{
+ } finally {
janusGraphDao.commit();
}
}
- public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponentsMetadata(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, String userId) {
- try{
+ public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponentsMetadata(boolean isAbstractAbstract,
+ HighestFilterEnum highestFilter,
+ ComponentTypeEnum componentTypeEnum,
+ String internalComponentType, String userId) {
+ try {
validateUserExists(userId);
- Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractMetadataOnly(isAbstractAbstract, componentTypeEnum, internalComponentType);
-
+ Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade
+ .getLatestVersionNotAbstractMetadataOnly(isAbstractAbstract, componentTypeEnum, internalComponentType);
if (nonCheckoutCompResponse.isLeft()) {
log.debug("Retrieved Resource successfully.");
return Either.left(nonCheckoutCompResponse.left().value());
}
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())));
+ return Either
+ .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())));
} finally {
janusGraphDao.commit();
}
}
public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
-
}
@SuppressWarnings("unchecked")
@@ -450,141 +457,101 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
String componentSystemName = component.getSystemName();
String componentType = component.getComponentType().getValue().toLowerCase();
Map<String, Object> toscaArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts();
-
if (toscaArtifacts != null) {
for (Entry<String, Object> artifactInfoMap : toscaArtifacts.entrySet()) {
Map<String, Object> artifactInfo = (Map<String, Object>) artifactInfoMap.getValue();
- ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(componentUniqueId, artifactInfoMap.getKey(), artifactInfo, user, ArtifactGroupTypeEnum.TOSCA);
- artifactDefinition.setArtifactName(ValidationUtils.normalizeFileName(componentType + "-" + componentSystemName + artifactInfo.get("artifactName")));
+ ArtifactDefinition artifactDefinition = artifactsBusinessLogic
+ .createArtifactPlaceHolderInfo(componentUniqueId, artifactInfoMap.getKey(), artifactInfo, user, ArtifactGroupTypeEnum.TOSCA);
+ artifactDefinition
+ .setArtifactName(ValidationUtils.normalizeFileName(componentType + "-" + componentSystemName + artifactInfo.get("artifactName")));
artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
}
}
component.setToscaArtifacts(artifactMap);
}
- public Either<ArtifactDefinition, Operation> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock) {
+ public Either<ArtifactDefinition, Operation> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest,
+ boolean inTransaction, boolean shouldLock) {
return populateToscaArtifacts(component, user, isInCertificationRequest, inTransaction, shouldLock, true, true);
}
- public Either<ArtifactDefinition, Operation> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock, boolean retrieveResource) {
+ public Either<ArtifactDefinition, Operation> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest,
+ boolean inTransaction, boolean shouldLock, boolean retrieveResource) {
return populateToscaArtifacts(component, user, isInCertificationRequest, inTransaction, shouldLock, true, retrieveResource);
}
- private Either<ArtifactDefinition, Operation> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock, boolean fetchTemplatesFromDB, boolean retrieveResource) {
+ private Either<ArtifactDefinition, Operation> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest,
+ boolean inTransaction, boolean shouldLock, boolean fetchTemplatesFromDB,
+ boolean retrieveResource) {
if (retrieveResource) {
Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaFullElement(component.getUniqueId());
- if ( toscaElement.isRight() ){
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(toscaElement.right().value(), component.getComponentType()));
+ if (toscaElement.isRight()) {
+ throw new ByActionStatusComponentException(
+ componentsUtils.convertFromStorageResponse(toscaElement.right().value(), component.getComponentType()));
}
component = toscaElement.left().value();
}
-
- Either<ArtifactDefinition, Operation> generateToscaRes =
- saveToscaArtifactAndPopulateToscaArtifactsWithResult(component, componentsUtils,
- ArtifactTypeEnum.TOSCA_TEMPLATE,
- (comp, toscaArtifact) ->
- saveToscaArtifactPayload(toscaArtifact, comp, user, isInCertificationRequest, shouldLock,
- inTransaction, fetchTemplatesFromDB));
-
+ Either<ArtifactDefinition, Operation> generateToscaRes = saveToscaArtifactAndPopulateToscaArtifactsWithResult(component, componentsUtils,
+ ArtifactTypeEnum.TOSCA_TEMPLATE,
+ (comp, toscaArtifact) -> saveToscaArtifactPayload(toscaArtifact, comp, user, isInCertificationRequest, shouldLock, inTransaction,
+ fetchTemplatesFromDB));
if (!isAbstractResource(component)) {
- generateToscaRes = saveToscaArtifactAndPopulateToscaArtifactsWithResult(component, componentsUtils,
- ArtifactTypeEnum.TOSCA_CSAR,
- (comp, toscaArtifactArg) -> saveToscaArtifactPayload(toscaArtifactArg, comp, user,
- isInCertificationRequest, shouldLock, inTransaction, true));
+ generateToscaRes = saveToscaArtifactAndPopulateToscaArtifactsWithResult(component, componentsUtils, ArtifactTypeEnum.TOSCA_CSAR,
+ (comp, toscaArtifactArg) -> saveToscaArtifactPayload(toscaArtifactArg, comp, user, isInCertificationRequest, shouldLock,
+ inTransaction, true));
}
return generateToscaRes;
}
- private static Either<ArtifactDefinition, Operation> saveToscaArtifactAndPopulateToscaArtifactsWithResult(
- Component component,
- final ComponentsUtils componentsUtils,
- final ArtifactTypeEnum artifactEnum,
- final BiFunction<Component, ArtifactDefinition, Either<ArtifactDefinition, Operation>> saveToscaArtifactPayloadFunction) {
-
- ArtifactDefinition artifactDefinition = getToscaArtifactByTypeOrThrowException(component, artifactEnum,
- componentsUtils);
-
- Either<ArtifactDefinition, Operation> result =
- saveToscaArtifactPayloadFunction.apply(component, artifactDefinition);
-
- if (result.isLeft()) {
- ArtifactDefinition def = result.left().value();
- component.getToscaArtifacts().put(def.getArtifactLabel(), def);
- }
-
- return result;
- }
-
- private static Optional<ArtifactDefinition> getToscaArtifactByType(
- final Map<String, ArtifactDefinition> toscaArtifacts,
- final ArtifactTypeEnum typeEnum) {
- return toscaArtifacts.values().stream()
- .filter(p -> p.getArtifactType().equals(typeEnum.getType()))
- .findAny();
- }
-
- private static ArtifactDefinition getToscaArtifactByTypeOrThrowException(
- final Component component,
- final ArtifactTypeEnum typeEnum,
- final ComponentsUtils componentsUtils) {
-
- return Optional.ofNullable(component.getToscaArtifacts())
- .flatMap(toscaArtifacts -> getToscaArtifactByType(toscaArtifacts, typeEnum))
- .orElseThrow(() -> {
- log.debug("Impossible to find a ToscaArtifact with type '{}' for {}", typeEnum.getType(), component);
- return new ByResponseFormatComponentException(
- componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, typeEnum.name()));
- });
- }
-
private boolean isAbstractResource(Component component) {
- return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource)component).isAbstract();
+ return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource) component).isAbstract();
}
- private Either<ArtifactDefinition, Operation> saveToscaArtifactPayload(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest, boolean shouldLock,
- boolean inTransaction, boolean fetchTemplatesFromDB) {
- return artifactsBusinessLogic.generateAndSaveToscaArtifact(artifactDefinition, component, user, isInCertificationRequest, shouldLock, inTransaction, fetchTemplatesFromDB);
+ private Either<ArtifactDefinition, Operation> saveToscaArtifactPayload(ArtifactDefinition artifactDefinition,
+ org.openecomp.sdc.be.model.Component component, User user,
+ boolean isInCertificationRequest, boolean shouldLock,
+ boolean inTransaction, boolean fetchTemplatesFromDB) {
+ return artifactsBusinessLogic
+ .generateAndSaveToscaArtifact(artifactDefinition, component, user, isInCertificationRequest, shouldLock, inTransaction,
+ fetchTemplatesFromDB);
}
- public ImmutablePair<String, byte[]> getToscaModelByComponentUuid(ComponentTypeEnum componentType, String uuid, ResourceCommonInfo resourceCommonInfo) {
-
+ public ImmutablePair<String, byte[]> getToscaModelByComponentUuid(ComponentTypeEnum componentType, String uuid,
+ ResourceCommonInfo resourceCommonInfo) {
Either<List<Component>, StorageOperationStatus> latestVersionEither = toscaOperationFacade.getComponentListByUuid(uuid, null);
-
if (latestVersionEither.isRight()) {
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentType));
+ throw new ByActionStatusComponentException(
+ componentsUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentType));
}
-
List<Component> components = latestVersionEither.left().value();
-
Component component = components.stream().filter(Component::isHighestVersion).findFirst().orElse(null);
- if(component == null){
+ if (component == null) {
component = components.stream().filter(c -> c.getLifecycleState() == LifecycleStateEnum.CERTIFIED).findFirst().orElse(null);
}
-
- if(component == null){
- throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType)));
+ if (component == null) {
+ throw new ByResponseFormatComponentException(
+ componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType)));
}
resourceCommonInfo.setResourceName(component.getName());
// TODO remove after migration - handle artifact not found(no
+
// placeholder)
if (null == component.getToscaArtifacts() || component.getToscaArtifacts().isEmpty()) {
- throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ArtifactTypeEnum.TOSCA_CSAR.name()));
+ throw new ByResponseFormatComponentException(
+ componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ArtifactTypeEnum.TOSCA_CSAR.name()));
}
ArtifactDefinition csarArtifact = component.getToscaArtifacts().values().stream()
- .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType()))
- .findAny().get();
+ .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny().get();
return artifactsBusinessLogic.handleDownloadToscaModelRequest(component, csarArtifact);
}
protected StorageOperationStatus markComponentToDelete(Component component) {
-
ComponentTypeEnum componentType = component.getComponentType();
String uniqueId = component.getUniqueId();
if (Boolean.TRUE.equals(component.getIsDeleted())) {
log.info("component {} already marked as deleted. id= {}, type={}", component.getName(), uniqueId, componentType);
return StorageOperationStatus.NOT_FOUND;
}
-
StorageOperationStatus markResourceToDelete = toscaOperationFacade.markComponentToDelete(component);
if (StorageOperationStatus.OK != markResourceToDelete) {
log.debug("failed to mark component {} of type {} for delete. error = {}", uniqueId, componentType, markResourceToDelete);
@@ -596,7 +563,8 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
}
}
- public Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Component currentComponent, Component updatedComponent, AuditingActionEnum auditingAction) {
+ public Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Component currentComponent, Component updatedComponent,
+ AuditingActionEnum auditingAction) {
String descriptionUpdated = updatedComponent.getDescription();
String descriptionCurrent = currentComponent.getDescription();
if (descriptionUpdated != null && !descriptionCurrent.equals(descriptionUpdated)) {
@@ -621,7 +589,8 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return Either.left(true);
}
- public Either<Boolean, ResponseFormat> validateAndUpdateIcon(User user, Component currentComponent, Component updatedComponent, boolean hasBeenCertified) {
+ public Either<Boolean, ResponseFormat> validateAndUpdateIcon(User user, Component currentComponent, Component updatedComponent,
+ boolean hasBeenCertified) {
String iconUpdated = updatedComponent.getIcon();
String iconCurrent = currentComponent.getIcon();
if (iconUpdated != null && !iconCurrent.equals(iconUpdated)) {
@@ -630,7 +599,8 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
currentComponent.setIcon(updatedComponent.getIcon());
} else {
log.info("icon {} cannot be updated once the component has been certified once.", iconUpdated);
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_PARAMETER_CANNOT_BE_CHANGED, "Icon", currentComponent.getComponentType().name().toLowerCase());
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_PARAMETER_CANNOT_BE_CHANGED, "Icon",
+ currentComponent.getComponentType().name().toLowerCase());
return Either.right(errorResponse);
}
}
@@ -638,14 +608,12 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
}
protected Either<List<String>, ResponseFormat> deleteMarkedComponents(ComponentTypeEnum componentType) {
-
log.trace("start deleteMarkedComponents");
Either<List<String>, StorageOperationStatus> deleteMarkedElements = toscaOperationFacade.deleteMarkedElements(componentType);
-
-
- if ( deleteMarkedElements.isRight()){
+ if (deleteMarkedElements.isRight()) {
janusGraphDao.rollback();
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteMarkedElements.right().value(), componentType));
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(deleteMarkedElements.right().value(), componentType));
return Either.right(responseFormat);
}
log.trace("end deleteMarkedComponents");
@@ -668,32 +636,27 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
}
/**
- *
* @param componentId
* @param user
* @param dataParamsToReturn - ui list of params to return
* @return
*/
-
- public Either<UiComponentDataTransfer, ResponseFormat> getComponentDataFilteredByParams(String componentId, User user, List<String> dataParamsToReturn) {
-
+ public Either<UiComponentDataTransfer, ResponseFormat> getComponentDataFilteredByParams(String componentId, User user,
+ List<String> dataParamsToReturn) {
if (user != null) {
validateUserExists(user);
}
-
- UiComponentDataTransfer result = new UiComponentDataTransfer();
-
- if(dataParamsToReturn == null || dataParamsToReturn.isEmpty()) {
+ UiComponentDataTransfer result = new UiComponentDataTransfer();
+ if (dataParamsToReturn == null || dataParamsToReturn.isEmpty()) {
Either.left(result);
-
} else {
- Either<UiComponentDataTransfer, ResponseFormat> uiDataTransferEither = getUiComponentDataTransferByComponentId(componentId, dataParamsToReturn);
- if(uiDataTransferEither.isRight()){
+ Either<UiComponentDataTransfer, ResponseFormat> uiDataTransferEither = getUiComponentDataTransferByComponentId(componentId,
+ dataParamsToReturn);
+ if (uiDataTransferEither.isRight()) {
return Either.right(uiDataTransferEither.right().value());
}
result = uiDataTransferEither.left().value();
}
-
return Either.left(result);
}
@@ -701,7 +664,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
List<InputDefinition> genericAndComponentInputs = new ArrayList<>();
List<InputDefinition> genericInputs = genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericType);
genericAndComponentInputs.addAll(genericInputs);
- if (null != component.getInputs()){
+ if (null != component.getInputs()) {
List<InputDefinition> nonGenericInputsFromComponent = getAllNonGenericInputsFromComponent(genericInputs, component.getInputs());
genericAndComponentInputs.addAll(nonGenericInputsFromComponent);
}
@@ -712,7 +675,6 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
if (genericInputs == null) {
return componentInputs;
}
-
Map<String, InputDefinition> inputByNameMap = MapUtil.toMap(genericInputs, InputDefinition::getName);
List<InputDefinition> componentNonGenericInputs = new ArrayList<>();
componentInputs.stream().forEach(input -> {
@@ -723,9 +685,9 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return componentNonGenericInputs;
}
- protected <T extends Component> Resource fetchAndSetDerivedFromGenericType(T component){
+ protected <T extends Component> Resource fetchAndSetDerivedFromGenericType(T component) {
Either<Resource, ResponseFormat> genericTypeEither = this.genericTypeBusinessLogic.fetchDerivedFromGenericType(component);
- if(genericTypeEither.isRight()){
+ if (genericTypeEither.isRight()) {
log.debug("Failed to fetch latest generic type for component {} of type", component.getName(), component.assetType());
throw new ByActionStatusComponentException(ActionStatus.GENERIC_TYPE_NOT_FOUND, component.assetType());
}
@@ -734,30 +696,33 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return genericTypeResource;
}
- public Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> getFilteredComponentInstanceProperties(String componentId, Map<FilterKeyEnum, List<String>> filters, String userId) {
+ public Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> getFilteredComponentInstanceProperties(String componentId,
+ Map<FilterKeyEnum, List<String>> filters,
+ String userId) {
Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> response = null;
Either<Component, StorageOperationStatus> getResourceRes = null;
- try{
- if(!filters.containsKey(FilterKeyEnum.NAME_FRAGMENT) && StringUtils.isEmpty(filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0))){
+ try {
+ if (!filters.containsKey(FilterKeyEnum.NAME_FRAGMENT) && StringUtils.isEmpty(filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0))) {
response = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
if (userId != null && response == null) {
validateUserExists(userId);
}
- if(response == null){
+ if (response == null) {
getResourceRes = toscaOperationFacade.getToscaElement(componentId);
- if(getResourceRes.isRight()){
- response = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResourceRes.right().value())));
+ if (getResourceRes.isRight()) {
+ response = Either
+ .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResourceRes.right().value())));
}
}
- if(response == null){
+ if (response == null) {
response = getFilteredComponentInstancesProperties(getResourceRes.left().value(), filters);
}
- } catch(Exception e){
+ } catch (Exception e) {
log.debug("The exception {} occured during filtered instance properties fetching. the containing component is {}. ", e, componentId);
response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- } finally{
- if (response != null && response.isLeft()){
+ } finally {
+ if (response != null && response.isLeft()) {
toscaOperationFacade.commit();
} else {
toscaOperationFacade.rollback();
@@ -766,22 +731,25 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return response;
}
- private Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> getFilteredComponentInstancesProperties(Component component, Map<FilterKeyEnum, List<String>> filters) {
-
- Map<String, List<IComponentInstanceConnectedElement>> filteredProperties = new HashMap<>();
+ private Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> getFilteredComponentInstancesProperties(Component component,
+ Map<FilterKeyEnum, List<String>> filters) {
+ Map<String, List<IComponentInstanceConnectedElement>> filteredProperties = new HashMap<>();
Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> result = Either.left(filteredProperties);
List<ComponentInstance> filteredInstances = getFilteredInstances(component, filters.get(FilterKeyEnum.RESOURCE_TYPE));
- String propertyNameFragment= filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0);
- boolean searchByFragment = propertyNameFragment.length() > 3 ;
- if(CollectionUtils.isNotEmpty(filteredInstances)){
- for(ComponentInstance instance : filteredInstances){
- if(component.getComponentInstancesProperties()!=null &&component.getComponentInstancesProperties().containsKey(instance.getUniqueId())){
- List<IComponentInstanceConnectedElement> currProperties = getFilteredComponentInstanceProperties(component.getComponentInstancesProperties().get(instance.getUniqueId()), propertyNameFragment, searchByFragment);
+ String propertyNameFragment = filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0);
+ boolean searchByFragment = propertyNameFragment.length() > 3;
+ if (CollectionUtils.isNotEmpty(filteredInstances)) {
+ for (ComponentInstance instance : filteredInstances) {
+ if (component.getComponentInstancesProperties() != null && component.getComponentInstancesProperties()
+ .containsKey(instance.getUniqueId())) {
+ List<IComponentInstanceConnectedElement> currProperties = getFilteredComponentInstanceProperties(
+ component.getComponentInstancesProperties().get(instance.getUniqueId()), propertyNameFragment, searchByFragment);
setFilteredProperties(filteredProperties, instance, currProperties);
}
- if(component.getComponentInstancesInputs()!=null && component.getComponentInstancesInputs().containsKey(instance.getUniqueId())){
- List<IComponentInstanceConnectedElement> currInputs = getFilteredComponentInstanceInputs(component.getComponentInstancesInputs().get(instance.getUniqueId()), propertyNameFragment, searchByFragment);
- if(CollectionUtils.isNotEmpty(currInputs)){
+ if (component.getComponentInstancesInputs() != null && component.getComponentInstancesInputs().containsKey(instance.getUniqueId())) {
+ List<IComponentInstanceConnectedElement> currInputs = getFilteredComponentInstanceInputs(
+ component.getComponentInstancesInputs().get(instance.getUniqueId()), propertyNameFragment, searchByFragment);
+ if (CollectionUtils.isNotEmpty(currInputs)) {
checkFilteredProperties(filteredProperties, instance, currInputs);
}
}
@@ -790,34 +758,38 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return result;
}
- private void setFilteredProperties(Map<String, List<IComponentInstanceConnectedElement>> filteredProperties, ComponentInstance instance, List<IComponentInstanceConnectedElement> currProperties) {
- if(CollectionUtils.isNotEmpty(currProperties)){
+ private void setFilteredProperties(Map<String, List<IComponentInstanceConnectedElement>> filteredProperties, ComponentInstance instance,
+ List<IComponentInstanceConnectedElement> currProperties) {
+ if (CollectionUtils.isNotEmpty(currProperties)) {
filteredProperties.put(instance.getUniqueId(), currProperties);
}
}
- private void checkFilteredProperties(Map<String, List<IComponentInstanceConnectedElement>> filteredProperties, ComponentInstance instance, List<IComponentInstanceConnectedElement> currInputs) {
- if(filteredProperties.get(instance.getUniqueId())!=null){
+ private void checkFilteredProperties(Map<String, List<IComponentInstanceConnectedElement>> filteredProperties, ComponentInstance instance,
+ List<IComponentInstanceConnectedElement> currInputs) {
+ if (filteredProperties.get(instance.getUniqueId()) != null) {
filteredProperties.get(instance.getUniqueId()).addAll(currInputs);
} else {
filteredProperties.put(instance.getUniqueId(), currInputs);
}
}
- private List<IComponentInstanceConnectedElement> getFilteredComponentInstanceInputs(List<ComponentInstanceInput> inputs, String propertyNameFragment, boolean searchByFragment) {
+ private List<IComponentInstanceConnectedElement> getFilteredComponentInstanceInputs(List<ComponentInstanceInput> inputs,
+ String propertyNameFragment, boolean searchByFragment) {
return inputs.stream().filter(i -> isMatchingInput(i, propertyNameFragment, searchByFragment)).collect(Collectors.toList());
}
- private List<IComponentInstanceConnectedElement> getFilteredComponentInstanceProperties(List<ComponentInstanceProperty> instanceProperties, String propertyNameFragment, boolean searchByFragment) {
+ private List<IComponentInstanceConnectedElement> getFilteredComponentInstanceProperties(List<ComponentInstanceProperty> instanceProperties,
+ String propertyNameFragment, boolean searchByFragment) {
return instanceProperties.stream().filter(p -> isMatchingProperty(p, propertyNameFragment, searchByFragment)).collect(Collectors.toList());
}
private boolean isMatchingInput(ComponentInstanceInput input, String propertyNameFragment, boolean searchByFragment) {
boolean isMatching = false;
- if(searchByFragment && input.getName().toLowerCase().contains(propertyNameFragment)){
+ if (searchByFragment && input.getName().toLowerCase().contains(propertyNameFragment)) {
isMatching = true;
}
- if(!searchByFragment && input.getName().equalsIgnoreCase(propertyNameFragment)){
+ if (!searchByFragment && input.getName().equalsIgnoreCase(propertyNameFragment)) {
isMatching = true;
}
return isMatching;
@@ -825,56 +797,50 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
private boolean isMatchingProperty(ComponentInstanceProperty property, String propertyNameFragment, boolean searchByFragment) {
boolean isMatching = false;
- if(searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment)){
+ if (searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment)) {
isMatching = true;
}
- if(!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)){
+ if (!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)) {
isMatching = true;
}
- if (!isMatching && !ToscaPropertyType.isPrimitiveType(property.getType())){
+ if (!isMatching && !ToscaPropertyType.isPrimitiveType(property.getType())) {
isMatching = isMatchingComplexPropertyByRecursively(property, propertyNameFragment, searchByFragment);
}
return isMatching;
}
- private boolean isMatchingComplexPropertyByRecursively(PropertyDataDefinition property, String propertyNameFragment, boolean searchByFragment) {
+ private boolean isMatchingComplexPropertyByRecursively(PropertyDataDefinition property, String propertyNameFragment, boolean searchByFragment) {
String propertyType;
- List<PropertyDefinition> dataTypeProperties;
+ List<PropertyDefinition> dataTypeProperties;
DataTypeDefinition currentProperty;
- if(searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment.toLowerCase())){
+ if (searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment.toLowerCase())) {
return true;
}
- if(!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)){
+ if (!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)) {
return true;
}
-
propertyType = isEmptyInnerType(property) ? property.getType() : property.getSchema().getProperty().getType();
-
- if(ToscaPropertyType.isScalarType(propertyType)){
+ if (ToscaPropertyType.isScalarType(propertyType)) {
return false;
}
- Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameRes = propertyOperation.getDataTypeByName(propertyType);
- if(getDataTypeByNameRes.isRight()){
+ Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameRes = propertyOperation.getDataTypeByName(propertyType);
+ if (getDataTypeByNameRes.isRight()) {
return false;
}
currentProperty = getDataTypeByNameRes.left().value();
dataTypeProperties = currentProperty.getProperties();
-
boolean dataPropertiesNotNull = CollectionUtils.isNotEmpty(dataTypeProperties);
- BooleanSupplier dataMatchesComplexProperty = () -> isMatchingComplexProperty(propertyNameFragment,
- searchByFragment, dataTypeProperties);
- BooleanSupplier parentPropertiesNotNull = () -> CollectionUtils
- .isNotEmpty(currentProperty.getDerivedFrom().getProperties());
- BooleanSupplier parentDataMatchesComplexProperty = () -> isMatchingComplexProperty(propertyNameFragment,
- searchByFragment, currentProperty.getDerivedFrom().getProperties());
-
- return ((dataPropertiesNotNull && dataMatchesComplexProperty.getAsBoolean())
- || (parentPropertiesNotNull.getAsBoolean() && parentDataMatchesComplexProperty.getAsBoolean()));
+ BooleanSupplier dataMatchesComplexProperty = () -> isMatchingComplexProperty(propertyNameFragment, searchByFragment, dataTypeProperties);
+ BooleanSupplier parentPropertiesNotNull = () -> CollectionUtils.isNotEmpty(currentProperty.getDerivedFrom().getProperties());
+ BooleanSupplier parentDataMatchesComplexProperty = () -> isMatchingComplexProperty(propertyNameFragment, searchByFragment,
+ currentProperty.getDerivedFrom().getProperties());
+ return ((dataPropertiesNotNull && dataMatchesComplexProperty.getAsBoolean()) || (parentPropertiesNotNull.getAsBoolean()
+ && parentDataMatchesComplexProperty.getAsBoolean()));
}
private boolean isMatchingComplexProperty(String propertyNameFragment, boolean searchByFragment, List<PropertyDefinition> dataTypeProperties) {
- for(PropertyDefinition prop : dataTypeProperties){
- if(isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)){
+ for (PropertyDefinition prop : dataTypeProperties) {
+ if (isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)) {
return true;
}
}
@@ -882,20 +848,22 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
}
private boolean isEmptyInnerType(PropertyDataDefinition property) {
- return property == null|| property.getSchema() == null || property.getSchema().getProperty() == null || property.getSchema().getProperty().getType() == null;
+ return property == null || property.getSchema() == null || property.getSchema().getProperty() == null
+ || property.getSchema().getProperty().getType() == null;
}
public Either<Boolean, ResponseFormat> shouldUpgradeToLatestGeneric(Component clonedComponent) {
-
- if(!clonedComponent.deriveFromGeneric())
+ if (!clonedComponent.deriveFromGeneric()) {
return Either.left(false);
+ }
Boolean shouldUpgrade = false;
String currentGenericType = clonedComponent.getDerivedFromGenericType();
String currentGenericVersion = clonedComponent.getDerivedFromGenericVersion();
Resource genericTypeResource = fetchAndSetDerivedFromGenericType(clonedComponent);
- if(null == currentGenericType || !currentGenericType.equals(genericTypeResource.getToscaResourceName()) || !currentGenericVersion.equals(genericTypeResource.getVersion())){
+ if (null == currentGenericType || !currentGenericType.equals(genericTypeResource.getToscaResourceName()) || !currentGenericVersion
+ .equals(genericTypeResource.getVersion())) {
shouldUpgrade = upgradeToLatestGeneric(clonedComponent, genericTypeResource);
- if(!shouldUpgrade) {
+ if (!shouldUpgrade) {
reverntUpdateOfGenericVersion(clonedComponent, currentGenericType, currentGenericVersion);
}
}
@@ -907,42 +875,45 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
clonedComponent.setDerivedFromGenericVersion(currentGenericVersion);
}
- private <T extends ToscaDataDefinition> Either<Map<String, T>, String> validateNoConflictingProperties(List<T> currentList, List<T> upgradedList) {
+ private <T extends ToscaDataDefinition> Either<Map<String, T>, String> validateNoConflictingProperties(List<T> currentList,
+ List<T> upgradedList) {
Map<String, T> currentMap = ToscaDataDefinition.listToMapByName(currentList);
Map<String, T> upgradedMap = ToscaDataDefinition.listToMapByName(upgradedList);
return ToscaDataDefinition.mergeDataMaps(upgradedMap, currentMap, true);
}
- private boolean shouldUpgradeNodeType(Component componentToCheckOut, Resource latestGeneric){
-
+ private boolean shouldUpgradeNodeType(Component componentToCheckOut, Resource latestGeneric) {
List<PropertyDefinition> genericTypeProps = latestGeneric.getProperties();
- Either<Map<String, PropertyDefinition>, String> validPropertiesMerge = validateNoConflictingProperties(genericTypeProps, ((Resource)componentToCheckOut).getProperties());
+ Either<Map<String, PropertyDefinition>, String> validPropertiesMerge = validateNoConflictingProperties(genericTypeProps,
+ ((Resource) componentToCheckOut).getProperties());
if (validPropertiesMerge.isRight()) {
- log.debug("property {} cannot be overriden, check out performed without upgrading to latest generic", validPropertiesMerge.right().value());
+ log.debug("property {} cannot be overriden, check out performed without upgrading to latest generic",
+ validPropertiesMerge.right().value());
return false;
}
List<AttributeDefinition> genericTypeAttributes = latestGeneric.getAttributes();
- final Either<Map<String, AttributeDefinition>, String> validAttributesMerge = validateNoConflictingProperties(
- genericTypeAttributes, ((Resource) componentToCheckOut).getAttributes());
+ final Either<Map<String, AttributeDefinition>, String> validAttributesMerge = validateNoConflictingProperties(genericTypeAttributes,
+ ((Resource) componentToCheckOut).getAttributes());
if (validAttributesMerge.isRight()) {
- log.debug("attribute {} cannot be overriden, check out performed without upgrading to latest generic", validAttributesMerge.right().value());
+ log.debug("attribute {} cannot be overriden, check out performed without upgrading to latest generic",
+ validAttributesMerge.right().value());
return false;
}
return true;
}
private boolean upgradeToLatestGeneric(Component componentToCheckOut, Resource latestGeneric) {
-
if (!componentToCheckOut.shouldGenerateInputs()) {
//node type - validate properties and attributes
return shouldUpgradeNodeType(componentToCheckOut, latestGeneric);
}
List<PropertyDefinition> genericTypeProps = latestGeneric.getProperties();
- List<InputDefinition> genericTypeInputs = null == genericTypeProps? null : genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericTypeProps, latestGeneric.getUniqueId());
+ List<InputDefinition> genericTypeInputs = null == genericTypeProps ? null
+ : genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericTypeProps, latestGeneric.getUniqueId());
List<InputDefinition> currentList = new ArrayList<>();
// nullify existing ownerId from existing list and merge into updated list
if (null != componentToCheckOut.getInputs()) {
- for(InputDefinition input : componentToCheckOut.getInputs()) {
+ for (InputDefinition input : componentToCheckOut.getInputs()) {
InputDefinition copy = new InputDefinition(input);
copy.setOwnerId(null);
currentList.add(copy);
@@ -952,7 +923,6 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
componentToCheckOut.setInputs(currentList);
return true;
}
-
Either<Map<String, InputDefinition>, String> eitherMerged = validateNoConflictingProperties(genericTypeInputs, currentList);
if (eitherMerged.isRight()) {
log.debug("input {} cannot be overriden, check out performed without upgrading to latest generic", eitherMerged.right().value());
@@ -962,17 +932,15 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return true;
}
-
private List<ComponentInstance> getFilteredInstances(Component component, List<String> resourceTypes) {
List<ComponentInstance> filteredInstances = null;
- if(CollectionUtils.isEmpty(resourceTypes)){
+ if (CollectionUtils.isEmpty(resourceTypes)) {
filteredInstances = component.getComponentInstances();
+ } else if (CollectionUtils.isNotEmpty(component.getComponentInstances())) {
+ filteredInstances = component.getComponentInstances().stream().filter(i -> isMatchingType(i.getOriginType(), resourceTypes))
+ .collect(Collectors.toList());
}
- else if(CollectionUtils.isNotEmpty(component.getComponentInstances())){
- filteredInstances = component.getComponentInstances()
- .stream().filter(i -> isMatchingType(i.getOriginType(), resourceTypes)).collect(Collectors.toList());
- }
- if(filteredInstances == null){
+ if (filteredInstances == null) {
filteredInstances = new ArrayList<>();
}
return filteredInstances;
@@ -980,8 +948,8 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
private boolean isMatchingType(OriginTypeEnum originType, List<String> resourceTypes) {
boolean isMatchingType = false;
- for(String resourceType : resourceTypes){
- if(originType == OriginTypeEnum.findByValue(resourceType.toUpperCase())){
+ for (String resourceType : resourceTypes) {
+ if (originType == OriginTypeEnum.findByValue(resourceType.toUpperCase())) {
isMatchingType = true;
break;
}
@@ -994,14 +962,14 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return Either.right(ActionStatus.GENERAL_ERROR);
}
- protected Either<Component, ResponseFormat> updateCatalog(Component component, ChangeTypeEnum changeStatus){
- log.debug("update Catalog start with Component Type {} And Componet Name {} with change status {}", component.getComponentType().name(), component.getName(), changeStatus.name());
- ActionStatus status = catalogOperations.updateCatalog(changeStatus,component);
- if(status != ActionStatus.OK){
- return Either.right( componentsUtils.getResponseFormat(status));
+ protected Either<Component, ResponseFormat> updateCatalog(Component component, ChangeTypeEnum changeStatus) {
+ log.debug("update Catalog start with Component Type {} And Componet Name {} with change status {}", component.getComponentType().name(),
+ component.getName(), changeStatus.name());
+ ActionStatus status = catalogOperations.updateCatalog(changeStatus, component);
+ if (status != ActionStatus.OK) {
+ return Either.right(componentsUtils.getResponseFormat(status));
}
-
- return Either.left(component);
+ return Either.left(component);
}
public CatalogOperation getCatalogOperations() {
@@ -1016,5 +984,4 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
public List<GroupDefinition> throwComponentException(ResponseFormat responseFormat) {
throw new ByResponseFormatComponentException(responseFormat);
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogicProvider.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogicProvider.java
index 1e0f6863f9..0a7758defb 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogicProvider.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogicProvider.java
@@ -34,7 +34,8 @@ public class ComponentBusinessLogicProvider {
private final ServiceBusinessLogic serviceBusinessLogic;
private final ProductBusinessLogic productBusinessLogic;
- public ComponentBusinessLogicProvider(ResourceBusinessLogic resourceBusinessLogic, ServiceBusinessLogic serviceBusinessLogic, ProductBusinessLogic productBusinessLogic) {
+ public ComponentBusinessLogicProvider(ResourceBusinessLogic resourceBusinessLogic, ServiceBusinessLogic serviceBusinessLogic,
+ ProductBusinessLogic productBusinessLogic) {
this.resourceBusinessLogic = resourceBusinessLogic;
this.serviceBusinessLogic = serviceBusinessLogic;
this.productBusinessLogic = productBusinessLogic;
@@ -43,16 +44,15 @@ public class ComponentBusinessLogicProvider {
public ComponentBusinessLogic getInstance(ComponentTypeEnum componentTypeEnum) {
switch (componentTypeEnum) {
case SERVICE:
- return serviceBusinessLogic;
+ return serviceBusinessLogic;
case PRODUCT:
- return productBusinessLogic;
+ return productBusinessLogic;
case RESOURCE:
case RESOURCE_INSTANCE:
- return resourceBusinessLogic;
+ return resourceBusinessLogic;
default:
BeEcompErrorManager.getInstance().logBeSystemError("getInstance");
throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT, componentTypeEnum.getValue());
}
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java
index a18d8dc8e4..8515c5c468 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import static org.openecomp.sdc.be.components.attribute.GetOutputUtils.isGetOutputValueForOutput;
@@ -142,7 +141,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
private static final String TRY_TO_CREATE_ENTRY_ON_GRAPH = "Try to create entry on graph";
private static final String CLOUD_SPECIFIC_FIXED_KEY_WORD = "cloudtech";
private static final String[][] CLOUD_SPECIFIC_KEY_WORDS = {{"k8s", "azure", "aws"}, /* cloud specific technology */
- {"charts", "day0", "configtemplate"} /*cloud specific sub type*/};
+ {"charts", "day0", "configtemplate"} /*cloud specific sub type*/};
private static final String FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE = "Failed to create entry on graph for component instance {}";
private static final String ENTITY_ON_GRAPH_IS_CREATED = "Entity on graph is created.";
private static final String INVALID_COMPONENT_TYPE = "invalid component type";
@@ -154,28 +153,28 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
private static final String CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE = "Cannot attach resource instances to container resource of type {}";
private static final String SERVICE_PROXY = "serviceProxy";
private static final String ASSOCIATE_RI_TO_RI = "associateRIToRI";
-
private ComponentInstanceOperation componentInstanceOperation;
private ArtifactsBusinessLogic artifactBusinessLogic;
private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL;
private ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator;
private ForwardingPathOperation forwardingPathOperation;
private NodeFilterOperation nodeFilterOperation;
+ @Autowired
+ private CompositionBusinessLogic compositionBusinessLogic;
+ @Autowired
+ private ContainerInstanceTypesData containerInstanceTypesData;
@Autowired
- public ComponentInstanceBusinessLogic(IElementOperation elementDao,
- IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation,
- IGroupTypeOperation groupTypeOperation,
- InterfaceOperation interfaceOperation,
- InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
- ComponentInstanceOperation componentInstanceOperation, ArtifactsBusinessLogic artifactBusinessLogic,
- ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL,
- ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator,
- ForwardingPathOperation forwardingPathOperation, NodeFilterOperation nodeFilterOperation,
- ArtifactsOperations artifactToscaOperation) {
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
- interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+ public ComponentInstanceBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
+ IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation,
+ InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+ ComponentInstanceOperation componentInstanceOperation, ArtifactsBusinessLogic artifactBusinessLogic,
+ ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL,
+ ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator,
+ ForwardingPathOperation forwardingPathOperation, NodeFilterOperation nodeFilterOperation,
+ ArtifactsOperations artifactToscaOperation) {
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+ artifactToscaOperation);
this.componentInstanceOperation = componentInstanceOperation;
this.artifactBusinessLogic = artifactBusinessLogic;
this.compInstMergeDataBL = compInstMergeDataBL;
@@ -184,26 +183,18 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
this.nodeFilterOperation = nodeFilterOperation;
}
- @Autowired
- private CompositionBusinessLogic compositionBusinessLogic;
-
- @Autowired
- private ContainerInstanceTypesData containerInstanceTypesData;
-
public ComponentInstance createComponentInstance(String containerComponentParam, String containerComponentId, String userId,
ComponentInstance resourceInstance) {
return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, true);
}
- public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component,
- String inputId) {
+ public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId) {
List<ComponentInstanceProperty> resList = new ArrayList<>();
Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
if (ciPropertiesMap != null && !ciPropertiesMap.isEmpty()) {
ciPropertiesMap.forEach((s, ciPropList) -> {
String ciName = "";
- Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s))
- .findAny();
+ Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)).findAny();
if (ciOp.isPresent()) {
ciName = ciOp.get().getName();
}
@@ -216,7 +207,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
});
}
return resList;
-
}
public List<ComponentInstanceAttribute> getComponentInstanceAttributesByOutputId(final org.openecomp.sdc.be.model.Component component,
@@ -226,7 +216,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
if (org.apache.commons.collections4.MapUtils.isNotEmpty(componentInstancesAttributes)) {
componentInstancesAttributes.forEach((s, componentInstanceAttributeList) -> {
String ciName = "";
- final Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)).findAny();
+ final Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s))
+ .findAny();
if (ciOp.isPresent()) {
ciName = ciOp.get().getName();
}
@@ -239,7 +230,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
});
}
return resList;
-
}
private void addCompInstanceProperty(String s, String ciName, ComponentInstanceProperty prop, List<GetInputValueDataDefinition> inputsValues,
@@ -256,11 +246,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
}
- private void addCompInstanceAttribute(final String s,
- final String ciName,
- final ComponentInstanceAttribute attribute,
- final List<GetOutputValueDataDefinition> outputsValues,
- final String outputId,
+ private void addCompInstanceAttribute(final String s, final String ciName, final ComponentInstanceAttribute attribute,
+ final List<GetOutputValueDataDefinition> outputsValues, final String outputId,
final List<ComponentInstanceAttribute> resList) {
if (outputsValues != null && !outputsValues.isEmpty()) {
for (final GetOutputValueDataDefinition outputData : outputsValues) {
@@ -274,30 +261,23 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
}
- public Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicyId(Component component,
- PolicyDefinition policy) {
-
+ public Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicyId(Component component, PolicyDefinition policy) {
Optional<ComponentInstanceProperty> propertyCandidate = getComponentInstancePropertyByPolicy(component, policy);
-
if (propertyCandidate.isPresent()) {
ComponentInstanceProperty componentInstanceProperty = propertyCandidate.get();
- Optional<GetPolicyValueDataDefinition> getPolicyCandidate =
- getGetPolicyValueDataDefinition(policy, componentInstanceProperty);
-
- getPolicyCandidate.ifPresent(getPolicyValue ->
- updateComponentInstancePropertyAfterUndeclaration(componentInstanceProperty, getPolicyValue, policy));
+ Optional<GetPolicyValueDataDefinition> getPolicyCandidate = getGetPolicyValueDataDefinition(policy, componentInstanceProperty);
+ getPolicyCandidate
+ .ifPresent(getPolicyValue -> updateComponentInstancePropertyAfterUndeclaration(componentInstanceProperty, getPolicyValue, policy));
return Optional.of(componentInstanceProperty);
}
-
return Optional.empty();
-
}
private void updateComponentInstancePropertyAfterUndeclaration(ComponentInstanceProperty componentInstanceProperty,
- GetPolicyValueDataDefinition getPolicyValue, PolicyDefinition policyDefinition) {
+ GetPolicyValueDataDefinition getPolicyValue, PolicyDefinition policyDefinition) {
componentInstanceProperty.setValue(getPolicyValue.getOrigPropertyValue());
List<GetPolicyValueDataDefinition> getPolicyValues = componentInstanceProperty.getGetPolicyValues();
- if(CollectionUtils.isNotEmpty(getPolicyValues)) {
+ if (CollectionUtils.isNotEmpty(getPolicyValues)) {
getPolicyValues.remove(getPolicyValue);
componentInstanceProperty.setGetPolicyValues(getPolicyValues);
policyDefinition.setGetPolicyValues(getPolicyValues);
@@ -305,45 +285,30 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
private Optional<GetPolicyValueDataDefinition> getGetPolicyValueDataDefinition(PolicyDefinition policy,
- ComponentInstanceProperty componentInstanceProperty) {
+ ComponentInstanceProperty componentInstanceProperty) {
List<GetPolicyValueDataDefinition> getPolicyValues = policy.getGetPolicyValues();
- return getPolicyValues.stream()
- .filter(getPolicyValue -> getPolicyValue
- .getPropertyName()
- .equals(componentInstanceProperty
- .getName()))
- .findAny();
+ return getPolicyValues.stream().filter(getPolicyValue -> getPolicyValue.getPropertyName().equals(componentInstanceProperty.getName()))
+ .findAny();
}
- private Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicy(Component component,
- PolicyDefinition policy) {
- Map<String, List<ComponentInstanceProperty>> componentInstancesProperties =
- component.getComponentInstancesProperties();
-
- if(MapUtils.isEmpty(componentInstancesProperties)) {
+ private Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicy(Component component, PolicyDefinition policy) {
+ Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component.getComponentInstancesProperties();
+ if (MapUtils.isEmpty(componentInstancesProperties)) {
return Optional.empty();
}
-
String instanceUniqueId = policy.getInstanceUniqueId();
-
List<ComponentInstanceProperty> componentInstanceProperties =
- componentInstancesProperties.containsKey(instanceUniqueId)
- ? componentInstancesProperties.get(instanceUniqueId)
- : new ArrayList<>();
-
- return componentInstanceProperties
- .stream().filter(property -> property.getName().equals(policy.getName())).findAny();
+ componentInstancesProperties.containsKey(instanceUniqueId) ? componentInstancesProperties.get(instanceUniqueId) : new ArrayList<>();
+ return componentInstanceProperties.stream().filter(property -> property.getName().equals(policy.getName())).findAny();
}
- public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(
- org.openecomp.sdc.be.model.Component component, String inputId) {
+ public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId) {
List<ComponentInstanceInput> resList = new ArrayList<>();
Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
if (ciInputsMap != null && !ciInputsMap.isEmpty()) {
ciInputsMap.forEach((s, ciPropList) -> {
String ciName = "";
- Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s))
- .findAny();
+ Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)).findAny();
if (ciOp.isPresent()) {
ciName = ciOp.get().getName();
}
@@ -351,13 +316,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
for (ComponentInstanceInput prop : ciPropList) {
List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
addCompInstanceInput(s, ciName, prop, inputsValues, inputId, resList);
-
}
}
});
}
return resList;
-
}
public List<ComponentInstanceOutput> getComponentInstanceOutputsByOutputId(final org.openecomp.sdc.be.model.Component component,
@@ -367,7 +330,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
if (ciInputsMap != null && !ciInputsMap.isEmpty()) {
ciInputsMap.forEach((s, ciPropList) -> {
String ciName = "";
- final Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)).findAny();
+ final Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s))
+ .findAny();
if (ciOp.isPresent()) {
ciName = ciOp.get().getName();
}
@@ -375,13 +339,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
for (final ComponentInstanceOutput prop : ciPropList) {
final List<GetOutputValueDataDefinition> outputValues = prop.getGetOutputValues();
addCompInstanceOutput(s, ciName, prop, outputValues, outputId, resList);
-
}
}
});
}
return resList;
-
}
private void addCompInstanceInput(String s, String ciName, ComponentInstanceInput prop, List<GetInputValueDataDefinition> inputsValues,
@@ -398,11 +360,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
}
- private void addCompInstanceOutput(final String s,
- final String ciName,
- final ComponentInstanceOutput prop,
- final List<GetOutputValueDataDefinition> outputsValues,
- final String outputId,
+ private void addCompInstanceOutput(final String s, final String ciName, final ComponentInstanceOutput prop,
+ final List<GetOutputValueDataDefinition> outputsValues, final String outputId,
final List<ComponentInstanceOutput> resList) {
if (outputsValues != null && !outputsValues.isEmpty()) {
for (final GetOutputValueDataDefinition outputData : outputsValues) {
@@ -416,25 +375,20 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
}
- public ComponentInstance createComponentInstance(final String containerComponentParam,
- final String containerComponentId, final String userId,
+ public ComponentInstance createComponentInstance(final String containerComponentParam, final String containerComponentId, final String userId,
final ComponentInstance resourceInstance, final boolean needLock) {
final User user = validateUserExists(userId);
validateUserNotEmpty(user, "Create component instance");
validateJsonBody(resourceInstance, ComponentInstance.class);
final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
- final org.openecomp.sdc.be.model.Component containerComponent =
- validateComponentExists(containerComponentId, containerComponentType, null);
-
+ final org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
if (ModelConverter.isAtomicComponent(containerComponent)) {
if (log.isDebugEnabled()) {
log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType());
}
throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType());
}
-
validateCanWorkOnComponent(containerComponent, userId);
-
Component origComponent = null;
if (resourceInstance != null && containerComponentType != null) {
final OriginTypeEnum originType = resourceInstance.getOriginType();
@@ -451,8 +405,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
overrideFields(origComponent, resourceInstance);
compositionBusinessLogic.validateAndSetDefaultCoordinates(resourceInstance);
}
- return createComponent(needLock, containerComponent,origComponent, resourceInstance, user);
-
+ return createComponent(needLock, containerComponent, origComponent, resourceInstance, user);
}
private Component getOrigComponentForServiceProxy(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance resourceInstance) {
@@ -461,7 +414,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
}
Component origComponent = serviceProxyOrigin.left().value();
-
StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent);
if (isFillProxyRes(fillProxyRes)) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
@@ -471,55 +423,53 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
private Component getOrigComponentForServiceSubstitution(ComponentInstance resourceInstance) {
- final Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade.getToscaFullElement(resourceInstance.getComponentUid());
+ final Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade
+ .getToscaFullElement(resourceInstance.getComponentUid());
if (getServiceResult.isRight()) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
}
final Component service = getServiceResult.left().value();
-
- final Either<Component, StorageOperationStatus> getServiceDerivedFromTypeResult = toscaOperationFacade.getLatestByToscaResourceName(service.getDerivedFromGenericType());
+ final Either<Component, StorageOperationStatus> getServiceDerivedFromTypeResult = toscaOperationFacade
+ .getLatestByToscaResourceName(service.getDerivedFromGenericType());
if (getServiceDerivedFromTypeResult.isRight()) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
}
-
Component origComponent = getServiceDerivedFromTypeResult.left().value();
-
final StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent);
if (isFillProxyRes(fillProxyRes)) {
- throw new ByActionStatusComponentException(
- componentsUtils.convertFromStorageResponse(fillProxyRes));
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
}
return origComponent;
}
- private ComponentInstance createComponent(boolean needLock, Component containerComponent, Component origComponent, ComponentInstance resourceInstance, User user) {
-
+ private ComponentInstance createComponent(boolean needLock, Component containerComponent, Component origComponent,
+ ComponentInstance resourceInstance, User user) {
boolean failed = false;
try {
-
lockIfNeed(needLock, containerComponent);
-
log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
return createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
- }catch (ComponentException e){
+ } catch (ComponentException e) {
failed = true;
throw e;
- }finally {
- if (needLock)
+ } finally {
+ if (needLock) {
unlockComponent(failed, containerComponent);
+ }
}
}
/**
* Try using either to make a judgment
+ *
* @param containerComponentParam
* @param containerComponentId
* @param userId
* @param resourceInstance
* @return
*/
-
- public Either<ComponentInstance, ResponseFormat> createRealComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) {
+ public Either<ComponentInstance, ResponseFormat> createRealComponentInstance(String containerComponentParam, String containerComponentId,
+ String userId, ComponentInstance resourceInstance) {
log.debug("enter createRealComponentInstance");
return createRealComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, true);
}
@@ -534,11 +484,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
* @param resourceInstance
* @return
*/
- public Either<ComponentInstance, ResponseFormat> createRealComponentInstance(String containerComponentParam,
- String containerComponentId, String userId,
- ComponentInstance resourceInstance,
+ public Either<ComponentInstance, ResponseFormat> createRealComponentInstance(String containerComponentParam, String containerComponentId,
+ String userId, ComponentInstance resourceInstance,
boolean needLock) {
-
log.debug("enter createRealComponentInstance");
Component origComponent = null;
User user;
@@ -550,29 +498,24 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
validateJsonBody(resourceInstance, ComponentInstance.class);
containerComponentType = validateComponentType(containerComponentParam);
containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
-
log.debug("enter createRealComponentInstance,validate user json success");
if (ModelConverter.isAtomicComponent(containerComponent)) {
log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType());
throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType());
}
-
validateCanWorkOnComponent(containerComponent, userId);
log.debug("enter createRealComponentInstance,validateCanWorkOnComponent success");
-
if (resourceInstance != null && containerComponentType != null) {
log.debug("enter createRealComponentInstance,start create ComponentInstance");
OriginTypeEnum originType = resourceInstance.getOriginType();
validateInstanceName(resourceInstance);
if (originType == OriginTypeEnum.ServiceProxy) {
-
log.debug("enter createRealComponentInstance,originType equals ServiceProxy");
Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName(SERVICE_PROXY);
if (isServiceProxyOrigin(serviceProxyOrigin)) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
}
origComponent = serviceProxyOrigin.left().value();
-
StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent);
if (isFillProxyRes(fillProxyRes)) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
@@ -588,52 +531,50 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
log.debug("enter createRealComponentInstance,final validate success");
}
return createRealComponent(needLock, containerComponent, origComponent, resourceInstance, user);
-
} catch (ComponentException e) {
log.debug("create Real Component Instance failed");
throw e;
}
}
- private Either<ComponentInstance, ResponseFormat> createRealComponent(boolean needLock, Component containerComponent, Component origComponent, ComponentInstance resourceInstance, User user) {
-
+ private Either<ComponentInstance, ResponseFormat> createRealComponent(boolean needLock, Component containerComponent, Component origComponent,
+ ComponentInstance resourceInstance, User user) {
log.debug("enter createRealComponent");
boolean failed = false;
try {
-
lockIfNeed(needLock, containerComponent);
-
log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
return createRealComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
} catch (ComponentException e) {
failed = true;
throw e;
} finally {
- if (needLock)
+ if (needLock) {
unlockComponent(failed, containerComponent);
+ }
}
}
- private Either<ComponentInstance, ResponseFormat> createRealComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
+ private Either<ComponentInstance, ResponseFormat> createRealComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent,
+ Component originComponent,
+ ComponentInstance componentInstance, User user) {
log.debug("enter createRealComponentInstanceOnGraph");
-
- Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
-
+ Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade
+ .addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
if (result.isRight()) {
log.debug("enter createRealComponentInstanceOnGraph,result is right");
ActionStatus status = componentsUtils.convertFromStorageResponse(result.right().value());
log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName());
return Either.right(componentsUtils.getResponseFormat(status));
}
-
log.debug(ENTITY_ON_GRAPH_IS_CREATED);
log.debug("enter createRealComponentInstanceOnGraph,Entity on graph is created.");
Component updatedComponent = result.left().value().getLeft();
Map<String, String> existingEnvVersions = new HashMap<>();
// TODO existingEnvVersions ??
addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
-
- Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
+ Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream()
+ .filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
if (!updatedInstanceOptional.isPresent()) {
log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
@@ -648,18 +589,15 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
private void validateInstanceName(ComponentInstance resourceInstance) {
-
String resourceInstanceName = resourceInstance.getName();
if (StringUtils.isEmpty(resourceInstanceName)) {
log.debug("ComponentInstance name is empty");
throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
}
-
if (!ValidationUtils.validateComponentNameLength(resourceInstanceName)) {
log.debug("ComponentInstance name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
}
-
if (!ValidationUtils.validateComponentNamePattern(resourceInstanceName)) {
log.debug("ComponentInstance name {} has invalid format", resourceInstanceName);
throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
@@ -667,14 +605,13 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
private void validateResourceInstanceState(Component containerComponent, Component origComponent) {
- if (origComponent.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT){
+ if (origComponent.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
- containerComponent.getComponentType().getValue(), origComponent.getLifecycleState().toString());
+ containerComponent.getComponentType().getValue(), origComponent.getLifecycleState().toString());
}
}
- private void validateOriginAndResourceInstanceTypes(final Component containerComponent,
- final Component origComponent,
+ private void validateOriginAndResourceInstanceTypes(final Component containerComponent, final Component origComponent,
final OriginTypeEnum originType) {
final ResourceTypeEnum resourceType = getResourceTypeEnumFromOriginComponent(origComponent);
validateOriginType(originType, resourceType);
@@ -686,14 +623,14 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
case SERVICE:
if (!containerInstanceTypesData.isAllowedForServiceComponent(resourceType)) {
throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
- containerComponent.getComponentType().toString(), resourceType.name());
+ containerComponent.getComponentType().toString(), resourceType.name());
}
break;
case RESOURCE:
final ResourceTypeEnum componentResourceType = ((Resource) containerComponent).getResourceType();
if (!containerInstanceTypesData.isAllowedForResourceComponent(componentResourceType, resourceType)) {
throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
- containerComponent.getComponentType().toString(), resourceType.name());
+ containerComponent.getComponentType().toString(), resourceType.name());
}
break;
default:
@@ -705,12 +642,12 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
ResourceTypeEnum convertedOriginType;
try {
convertedOriginType = ResourceTypeEnum.getTypeIgnoreCase(originType.name());
+ } catch (Exception e) {
+ throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
}
- catch (Exception e){
+ if (resourceType != convertedOriginType) {
throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
}
-
- if (resourceType != convertedOriginType) throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
}
private ResourceTypeEnum getResourceTypeEnumFromOriginComponent(final Component origComponent) {
@@ -748,8 +685,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
filter.setIgnoreProperties(false);
filter.setIgnoreAttributes(false);
filter.setIgnoreInputs(false);
- Either<Component, StorageOperationStatus> serviceRes =
- toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
+ Either<Component, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
if (serviceRes.isRight()) {
return serviceRes.right().value();
}
@@ -759,12 +695,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
final Map<String, List<RequirementDefinition>> req = service.getRequirements();
resourceInstance.setRequirements(req);
final Map<String, InterfaceDefinition> serviceInterfaces = service.getInterfaces();
- if(MapUtils.isNotEmpty(serviceInterfaces)) {
+ if (MapUtils.isNotEmpty(serviceInterfaces)) {
serviceInterfaces.forEach(resourceInstance::addInterface);
}
resourceInstance.setProperties(PropertiesUtils.getProperties(service));
resourceInstance.setAttributes(service.getAttributes());
-
final List<InputDefinition> serviceInputs = service.getInputs();
resourceInstance.setInputs(serviceInputs);
resourceInstance.setSourceModelInvariant(service.getInvariantUUID());
@@ -773,18 +708,18 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
resourceInstance.setSourceModelUid(service.getUniqueId());
resourceInstance.setComponentUid(origComponent.getUniqueId());
resourceInstance.setComponentVersion(service.getVersion());
-
- switch(resourceInstance.getOriginType()) {
- case ServiceProxy:
- return fillProxyInstanceData(resourceInstance, origComponent, service);
- case ServiceSubstitution:
- return fillServiceSubstitutableNodeTypeData(resourceInstance, service);
- default:
- return StorageOperationStatus.OK;
+ switch (resourceInstance.getOriginType()) {
+ case ServiceProxy:
+ return fillProxyInstanceData(resourceInstance, origComponent, service);
+ case ServiceSubstitution:
+ return fillServiceSubstitutableNodeTypeData(resourceInstance, service);
+ default:
+ return StorageOperationStatus.OK;
}
}
- private StorageOperationStatus fillProxyInstanceData(final ComponentInstance resourceInstance, final Component origComponent, final Component service) {
+ private StorageOperationStatus fillProxyInstanceData(final ComponentInstance resourceInstance, final Component origComponent,
+ final Component service) {
final String name = ValidationUtils.normalizeComponentInstanceName(service.getName()) + ToscaOperationFacade.PROXY_SUFFIX;
final String toscaResourceName = ((Resource) origComponent).getToscaResourceName();
final int lastIndexOf = toscaResourceName.lastIndexOf('.');
@@ -799,39 +734,32 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
private StorageOperationStatus fillServiceSubstitutableNodeTypeData(final ComponentInstance resourceInstance, final Component service) {
- resourceInstance.setToscaComponentName("org.openecomp.service." + ValidationUtils.convertToSystemName(service.getName()));
+ resourceInstance.setToscaComponentName("org.openecomp.service." + ValidationUtils.convertToSystemName(service.getName()));
resourceInstance.setName(ValidationUtils.normalizeComponentInstanceName(service.getName()));
resourceInstance.setIsProxy(false);
resourceInstance.setDescription("A substitutable node type for service " + service.getName());
-
return StorageOperationStatus.OK;
}
- public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
-
+ public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId,
+ String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
-
User user = validateUserExists(userId);
-
final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
-
org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
-
if (ModelConverter.isAtomicComponent(containerComponent)) {
log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
+ return Either
+ .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
}
-
validateCanWorkOnComponent(containerComponent, userId);
-
boolean failed = false;
try {
lockComponent(containerComponent, "createAndAssociateRIToRI");
log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
Component origComponent = getOriginComponentFromComponentInstance(resourceInstance);
-
log.debug(ENTITY_ON_GRAPH_IS_CREATED);
ComponentInstance resResourceInfo = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
@@ -839,25 +767,24 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
} else {
associationInfo.setToNode(resResourceInfo.getUniqueId());
}
-
- Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponent, containerComponentId, associationInfo);
+ Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade
+ .associateResourceInstances(containerComponent, containerComponentId, associationInfo);
if (resultReqCapDef.isLeft()) {
log.debug(ENTITY_ON_GRAPH_IS_CREATED);
RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
resultOp = Either.left(resInfo);
return resultOp;
-
} else {
log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
- resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(
+ componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
return resultOp;
}
-
- }catch (ComponentException e){
+ } catch (ComponentException e) {
failed = true;
throw e;
- }finally {
+ } finally {
unlockComponent(failed, containerComponent);
}
}
@@ -874,27 +801,29 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId);
if (eitherComponent.isRight()) {
log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName);
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null);
+ throw new ByActionStatusComponentException(
+ componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null);
}
return eitherComponent.left().value();
}
- private ComponentInstance createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
-
- Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
-
+ private ComponentInstance createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent,
+ ComponentInstance componentInstance, User user) {
+ Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade
+ .addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
if (result.isRight()) {
log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName());
- throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null));
+ throw new ByResponseFormatComponentException(componentsUtils
+ .getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "",
+ null));
}
-
log.debug(ENTITY_ON_GRAPH_IS_CREATED);
Component updatedComponent = result.left().value().getLeft();
Map<String, String> existingEnvVersions = new HashMap<>();
// TODO existingEnvVersions ??
addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
-
- Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
+ Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream()
+ .filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
if (!updatedInstanceOptional.isPresent()) {
log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
@@ -902,21 +831,23 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return updatedInstanceOptional.get();
}
- public boolean isCloudSpecificArtifact(String artifact) {
- if (artifact.contains(CLOUD_SPECIFIC_FIXED_KEY_WORD)) {
- for (int i = 0; i < CLOUD_SPECIFIC_KEY_WORDS.length; i++) {
- if (Arrays.stream(CLOUD_SPECIFIC_KEY_WORDS[i]).noneMatch(artifact::contains)) {
- return false;
- }
- }
- return true;
- } else {
- return false;
- }
- }
+ public boolean isCloudSpecificArtifact(String artifact) {
+ if (artifact.contains(CLOUD_SPECIFIC_FIXED_KEY_WORD)) {
+ for (int i = 0; i < CLOUD_SPECIFIC_KEY_WORDS.length; i++) {
+ if (Arrays.stream(CLOUD_SPECIFIC_KEY_WORDS[i]).noneMatch(artifact::contains)) {
+ return false;
+ }
+ }
+ return true;
+ } else {
+ return false;
+ }
+ }
/**
- * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts
+ * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's
+ * artifacts
+ *
* @param containerComponent
* @param componentInstance
* @param originComponent
@@ -924,8 +855,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
* @param existingEnvVersions
* @return
*/
- protected ActionStatus addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user, Map<String, String> existingEnvVersions) {
-
+ protected ActionStatus addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance,
+ org.openecomp.sdc.be.model.Component originComponent, User user,
+ Map<String, String> existingEnvVersions) {
log.debug("add artifacts to resource instance");
List<GroupDefinition> filteredGroups = new ArrayList<>();
ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
@@ -936,30 +868,29 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
// generate heat_env if necessary
Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) {
-
Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<>();
Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
- Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration()
- .getHeatArtifactDeploymentTimeout().getDefaultMinutes();
+ Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getHeatArtifactDeploymentTimeout()
+ .getDefaultMinutes();
List<ArtifactDefinition> listOfCloudSpecificArts = new ArrayList<>();
for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
String type = artifact.getArtifactType();
if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
}
- if (type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HELM.getType())|| type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT.getType())) {
+ if (type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HELM.getType()) || type
+ .equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || type
+ .equalsIgnoreCase(ArtifactTypeEnum.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT.getType())) {
artifact.setTimeout(defaultHeatTimeout);
} else {
continue;
}
if (artifact.checkEsIdExist()) {
- ArtifactDefinition artifactDefinition = artifactBusinessLogic.createHeatEnvPlaceHolder(new ArrayList<>(),
- artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(),
- NodeTypeEnum.ResourceInstance, componentInstance.getName(), user, containerComponent,
- existingEnvVersions);
+ ArtifactDefinition artifactDefinition = artifactBusinessLogic
+ .createHeatEnvPlaceHolder(new ArrayList<>(), artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(),
+ NodeTypeEnum.ResourceInstance, componentInstance.getName(), user, containerComponent, existingEnvVersions);
// put env
finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
-
if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
}
@@ -967,45 +898,47 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
listOfCloudSpecificArts.add(artifact);
}
if (CollectionUtils.isNotEmpty(filteredGroups)) {
- filteredGroups.stream().filter(g ->
- g.getArtifacts()
- .stream()
- .anyMatch(p -> p.equals(artifactDefinition.getGeneratedFromId())))
- .findFirst()
- .ifPresent(g -> fillInstanceArtifactMap(groupInstancesArtifacts, artifactDefinition, g));
+ filteredGroups.stream()
+ .filter(g -> g.getArtifacts().stream().anyMatch(p -> p.equals(artifactDefinition.getGeneratedFromId()))).findFirst()
+ .ifPresent(g -> fillInstanceArtifactMap(groupInstancesArtifacts, artifactDefinition, g));
}
}
}
- groupInstancesArtifacts.forEach((k,v) -> v.addAll(listOfCloudSpecificArts));
+ groupInstancesArtifacts.forEach((k, v) -> v.addAll(listOfCloudSpecificArts));
filteredGroups.forEach(g -> listOfCloudSpecificArts.forEach(e -> {
g.getArtifactsUuid().add(e.getArtifactUUID());
g.getArtifacts().add(e.getUniqueId());
}));
- artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
+ artStatus = toscaOperationFacade
+ .addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
if (artStatus != StorageOperationStatus.OK) {
- log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
- throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
-
+ log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(),
+ containerComponent.getUniqueId(), artStatus);
+ throw new ByResponseFormatComponentException(
+ componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
}
- StorageOperationStatus result = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
+ StorageOperationStatus result = toscaOperationFacade
+ .addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
if (result != StorageOperationStatus.OK) {
log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
}
componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
}
-
- artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
+ artStatus = toscaOperationFacade
+ .addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
if (artStatus != StorageOperationStatus.OK) {
- log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
- throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
-
+ log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}",
+ componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
+ throw new ByResponseFormatComponentException(
+ componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
}
componentInstance.setArtifacts(originComponent.getArtifacts());
return ActionStatus.OK;
}
- private void fillInstanceArtifactMap(Map<String, List<ArtifactDefinition>> groupInstancesArtifacts, ArtifactDefinition artifactDefinition, GroupDefinition groupInstance) {
+ private void fillInstanceArtifactMap(Map<String, List<ArtifactDefinition>> groupInstancesArtifacts, ArtifactDefinition artifactDefinition,
+ GroupDefinition groupInstance) {
List<ArtifactDefinition> artifactsUid;
if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
@@ -1017,9 +950,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts =
- artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null);
-
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic
+ .getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null);
Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
if (getResourceDeploymentArtifacts.isRight()) {
StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
@@ -1030,7 +962,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
} else {
deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
}
-
if (!deploymentArtifacts.isEmpty()) {
Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<>(deploymentArtifacts);
for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
@@ -1038,42 +969,37 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
tempDeploymentArtifacts.remove(artifact.getKey());
}
}
-
resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
}
-
return ActionStatus.OK;
}
- public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
+ public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId,
+ String componentInstanceId, String userId,
+ ComponentInstance componentInstance) {
return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, true);
}
- public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(
- final String containerComponentParam,
- final String containerComponentId,
- final String componentInstanceId,
- final String userId,
- ComponentInstance componentInstance,
- boolean needLock) {
-
+ public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(final String containerComponentParam,
+ final String containerComponentId,
+ final String componentInstanceId, final String userId,
+ ComponentInstance componentInstance, boolean needLock) {
validateUserExists(userId);
-
final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
-
final Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
-
validateCanWorkOnComponent(containerComponent, userId);
ComponentTypeEnum instanceType = getComponentType(containerComponentType);
- Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid());
+ Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade
+ .validateComponentExists(componentInstance.getComponentUid());
if (validateParentStatus.isRight()) {
log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
- throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase());
+ throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(),
+ instanceType.getValue().toLowerCase());
}
if (!validateParentStatus.left().value()) {
- throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId);
+ throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(),
+ instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId);
}
-
if (needLock) {
lockComponent(containerComponent, "updateComponentInstance");
}
@@ -1081,11 +1007,12 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
boolean failed = false;
try {
origComponent = getOriginComponentFromComponentInstance(componentInstance);
- componentInstance = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance);
- }catch (ComponentException e) {
+ componentInstance = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId,
+ componentInstance);
+ } catch (ComponentException e) {
failed = true;
throw e;
- }finally {
+ } finally {
if (needLock) {
unlockComponent(failed, containerComponent);
}
@@ -1094,12 +1021,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
// New Multiple Instance Update API
- public List<ComponentInstance> updateComponentInstance(String containerComponentParam, Component containerComponent, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock) {
-
+ public List<ComponentInstance> updateComponentInstance(String containerComponentParam, Component containerComponent, String containerComponentId,
+ String userId, List<ComponentInstance> componentInstanceList, boolean needLock) {
boolean failed = false;
try {
validateUserExists(userId);
-
final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
ComponentParametersView componentFilter = new ComponentParametersView();
componentFilter.disableAll();
@@ -1109,65 +1035,67 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
containerComponent = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter);
}
validateCanWorkOnComponent(containerComponent, userId);
-
ComponentTypeEnum instanceType = getComponentType(containerComponentType);
-
for (ComponentInstance componentInstance : componentInstanceList) {
boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
if (!validateParent) {
throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(),
- instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(),
- containerComponentId);
+ instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId);
}
}
-
if (needLock) {
lockComponent(containerComponent, "updateComponentInstance");
}
-
List<ComponentInstance> updatedList = new ArrayList<>();
List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
List<ComponentInstance> listForUpdate = new ArrayList<>();
- if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty())
+ if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty()) {
containerComponent.setComponentInstances(componentInstanceList);
- else {
+ } else {
Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
while (iterator.hasNext()) {
ComponentInstance origInst = iterator.next();
- Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny();
+ Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId()))
+ .findAny();
if (op.isPresent()) {
ComponentInstance updatedCi = op.get();
updatedCi = buildComponentInstance(updatedCi, origInst);
-
Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
if (!isUniqueName) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", origInst.getName(), updatedCi.getName());
- throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ",
+ origInst.getName(), updatedCi.getName());
+ throw new ByResponseFormatComponentException(componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
}
listForUpdate.add(updatedCi);
- } else
+ } else {
listForUpdate.add(origInst);
+ }
}
containerComponent.setComponentInstances(listForUpdate);
-
- Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
+ Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade
+ .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
if (updateStatus.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value());
- throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ",
+ containerComponent.getName(), updateStatus.right().value());
+ throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(
+ componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
}
-
for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) {
- Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny();
+ Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName()))
+ .findAny();
if (op.isPresent()) {
updatedList.add(updatedInstance);
}
}
}
return updatedList;
- }catch (ComponentException e){
+ } catch (ComponentException e) {
failed = true;
throw e;
- }finally {
+ } finally {
if (needLock) {
unlockComponent(failed, containerComponent);
}
@@ -1186,127 +1114,131 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
}
- private ComponentInstance updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
+ private ComponentInstance updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType,
+ org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
ComponentInstance componentInstance) {
-
Optional<ComponentInstance> componentInstanceOptional;
Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
ComponentInstance oldComponentInstance = null;
boolean isNameChanged = false;
-
- componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
+ componentInstanceOptional = containerComponent.getComponentInstances().stream()
+ .filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
if (!componentInstanceOptional.isPresent()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ",
+ componentInstance.getName(), containerComponent.getName());
throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
}
String oldComponentName;
oldComponentInstance = componentInstanceOptional.get();
oldComponentName = oldComponentInstance.getName();
String newInstanceName = componentInstance.getName();
- if (oldComponentName != null && !oldComponentInstance.getName().equals(newInstanceName))
+ if (oldComponentName != null && !oldComponentInstance.getName().equals(newInstanceName)) {
isNameChanged = true;
+ }
Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
if (!isUniqueName) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", oldComponentInstance.getName(), newInstanceName);
- throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ",
+ oldComponentInstance.getName(), newInstanceName);
+ throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(),
+ componentInstance.getName());
}
- if(!DirectivesUtil.isValid(componentInstance.getDirectives())) {
- final String directivesStr =
- componentInstance.getDirectives().stream().collect(Collectors.joining(" , ", " [ ", " ] "));
+ if (!DirectivesUtil.isValid(componentInstance.getDirectives())) {
+ final String directivesStr = componentInstance.getDirectives().stream().collect(Collectors.joining(" , ", " [ ", " ] "));
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
- "Failed to update the directives of the component instance {} to {}. Directives data {} is invalid. ",
- oldComponentInstance.getName(), newInstanceName ,
- directivesStr);
- throw new ByActionStatusComponentException(ActionStatus.DIRECTIVES_INVALID_VALUE, containerComponentType.getValue(), componentInstance.getName());
+ "Failed to update the directives of the component instance {} to {}. Directives data {} is invalid. ", oldComponentInstance.getName(),
+ newInstanceName, directivesStr);
+ throw new ByActionStatusComponentException(ActionStatus.DIRECTIVES_INVALID_VALUE, containerComponentType.getValue(),
+ componentInstance.getName());
}
- updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
+ updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent,
+ updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
if (updateRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(),
- updateRes.right().value());
- throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null));
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(),
+ containerComponent.getName(), updateRes.right().value());
+ throw new ByResponseFormatComponentException(componentsUtils
+ .getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true),
+ "", null));
} else {
// region - Update instance Groups
if (isNameChanged) {
- Either<StorageOperationStatus, StorageOperationStatus> result =
- toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
- if (result.isRight())
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value());
-
- if (containerComponent instanceof Service){
- Either<ComponentInstance, ResponseFormat> renameEither =
- renameServiceFilter((Service) containerComponent, newInstanceName,
- oldComponentInstance.getName());
+ Either<StorageOperationStatus, StorageOperationStatus> result = toscaOperationFacade
+ .cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
+ if (result.isRight()) {
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId,
+ result.right().value());
+ }
+ if (containerComponent instanceof Service) {
+ Either<ComponentInstance, ResponseFormat> renameEither = renameServiceFilter((Service) containerComponent, newInstanceName,
+ oldComponentInstance.getName());
if (renameEither.isRight()) {
throw new ByResponseFormatComponentException(renameEither.right().value());
}
-
updateForwardingPathDefinition(containerComponent, componentInstance, oldComponentName);
}
}
// endregion
}
String newInstanceId = updateRes.left().value().getRight();
- Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
-
+ Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream()
+ .filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
if (!updatedInstanceOptional.isPresent()) {
- log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName());
- throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
+ log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(),
+ containerComponent.getName());
+ throw new ByResponseFormatComponentException(
+ componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
}
-
return componentInstanceOptional.get();
}
private void updateForwardingPathDefinition(Component containerComponent, ComponentInstance componentInstance, String oldComponentName) {
Collection<ForwardingPathDataDefinition> forwardingPathDataDefinitions = getForwardingPathDataDefinitions(containerComponent.getUniqueId());
Set<ForwardingPathDataDefinition> updated = new ForwardingPathUtils()
- .updateComponentInstanceName(forwardingPathDataDefinitions, oldComponentName,
- componentInstance.getName());
+ .updateComponentInstanceName(forwardingPathDataDefinitions, oldComponentName, componentInstance.getName());
updated.forEach(fp -> {
Either<ForwardingPathDataDefinition, StorageOperationStatus> resultEither = forwardingPathOperation
- .updateForwardingPath(containerComponent.getUniqueId(), fp);
- if (resultEither.isRight()){
- CommonUtility.addRecordToLog(log, LogLevelEnum.ERROR, "Failed to rename forwarding path for container {}. error {} ",containerComponent.getName(), resultEither.right().value());
+ .updateForwardingPath(containerComponent.getUniqueId(), fp);
+ if (resultEither.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.ERROR, "Failed to rename forwarding path for container {}. error {} ",
+ containerComponent.getName(), resultEither.right().value());
}
});
}
-
- public Either<ComponentInstance, ResponseFormat> renameServiceFilter(final Service containerComponent,
- final String newInstanceName,
+ public Either<ComponentInstance, ResponseFormat> renameServiceFilter(final Service containerComponent, final String newInstanceName,
final String oldInstanceName) {
-
- Map<String, CINodeFilterDataDefinition> renamedNodesFilter =
- ServiceFilterUtils.getRenamedNodesFilter(containerComponent, oldInstanceName, newInstanceName);
- for( Entry<String, CINodeFilterDataDefinition> entry : renamedNodesFilter.entrySet()){
- Either<CINodeFilterDataDefinition, StorageOperationStatus>
- renameEither = nodeFilterOperation.updateNodeFilter(
- containerComponent.getUniqueId(),entry.getKey(),entry.getValue());
- if (renameEither.isRight()){
- return Either.right(componentsUtils.getResponseFormatForResourceInstance(
- componentsUtils.convertFromStorageResponse(renameEither.right().value(), ComponentTypeEnum.SERVICE),
- containerComponent.getName(), null));
+ Map<String, CINodeFilterDataDefinition> renamedNodesFilter = ServiceFilterUtils
+ .getRenamedNodesFilter(containerComponent, oldInstanceName, newInstanceName);
+ for (Entry<String, CINodeFilterDataDefinition> entry : renamedNodesFilter.entrySet()) {
+ Either<CINodeFilterDataDefinition, StorageOperationStatus> renameEither = nodeFilterOperation
+ .updateNodeFilter(containerComponent.getUniqueId(), entry.getKey(), entry.getValue());
+ if (renameEither.isRight()) {
+ return Either.right(componentsUtils.getResponseFormatForResourceInstance(
+ componentsUtils.convertFromStorageResponse(renameEither.right().value(), ComponentTypeEnum.SERVICE), containerComponent.getName(),
+ null));
}
-
}
return Either.left(null);
}
/**
- * @param oldPrefix-
- * The normalized old vf name
- * @param newNormailzedPrefix-
- * The normalized new vf name
- * @param qualifiedGroupInstanceName-
- * old Group Instance Name
+ * @param oldPrefix- The normalized old vf name
+ * @param newNormailzedPrefix- The normalized new vf name
+ * @param qualifiedGroupInstanceName- old Group Instance Name
**/
+
// modify group names
private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) {
if (qualifiedGroupInstanceName == null) {
log.info("CANNOT change group name ");
return null;
}
- if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix)))
+ if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName
+ .startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix))) {
return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
+ }
return qualifiedGroupInstanceName;
}
@@ -1315,42 +1247,37 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
oldComponentInstance.setModificationTime(System.currentTimeMillis());
oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
oldComponentInstance.setDirectives(newComponentInstance.getDirectives());
- if (oldComponentInstance.getGroupInstances() != null)
- oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
+ if (oldComponentInstance.getGroupInstances() != null) {
+ oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(),
+ ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
+ }
return oldComponentInstance;
}
- public ComponentInstance deleteComponentInstance(final String containerComponentParam,
- final String containerComponentId,
- final String componentInstanceId, String userId)
- throws BusinessLogicException {
-
+ public ComponentInstance deleteComponentInstance(final String containerComponentParam, final String containerComponentId,
+ final String componentInstanceId, String userId) throws BusinessLogicException {
validateUserExists(userId);
final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
-
final Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
validateCanWorkOnComponent(containerComponent, userId);
-
boolean failed = false;
final Optional<ComponentInstance> componentInstanceOptional = containerComponent.getComponentInstanceById(componentInstanceId);
if (!componentInstanceOptional.isPresent()) {
- throw new BusinessLogicException(componentsUtils
- .getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND));
+ throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND));
}
ComponentInstance componentInstance = componentInstanceOptional.get();
-
try {
if (containerComponent instanceof Service || containerComponent instanceof Resource) {
- final Either<String, StorageOperationStatus> deleteServiceFilterEither =
- nodeFilterOperation.deleteNodeFilter(containerComponent, componentInstanceId);
+ final Either<String, StorageOperationStatus> deleteServiceFilterEither = nodeFilterOperation
+ .deleteNodeFilter(containerComponent, componentInstanceId);
if (deleteServiceFilterEither.isRight()) {
- final ActionStatus status = componentsUtils.convertFromStorageResponse(deleteServiceFilterEither.right().value(),
- containerComponentType);
+ final ActionStatus status = componentsUtils
+ .convertFromStorageResponse(deleteServiceFilterEither.right().value(), containerComponentType);
janusGraphDao.rollback();
throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(status, componentInstanceId));
}
- final Either<ComponentInstance, ResponseFormat> resultOp = deleteNodeFiltersFromComponentInstance(
- containerComponent, componentInstance, containerComponentType, userId);
+ final Either<ComponentInstance, ResponseFormat> resultOp = deleteNodeFiltersFromComponentInstance(containerComponent,
+ componentInstance, containerComponentType, userId);
if (resultOp.isRight()) {
janusGraphDao.rollback();
throw new ByResponseFormatComponentException(resultOp.right().value());
@@ -1358,24 +1285,23 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
lockComponent(containerComponent, "deleteComponentInstance");
final ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
-
- componentInstance = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId,
- containerComponentType, deletedCompInstance);
- final ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator.doOnDeleteInstanceOperations(containerComponent, componentInstanceId);
+ componentInstance = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, containerComponentType,
+ deletedCompInstance);
+ final ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator
+ .doOnDeleteInstanceOperations(containerComponent, componentInstanceId);
if (ActionStatus.OK != onDeleteOperationsStatus) {
throw new ByActionStatusComponentException(onDeleteOperationsStatus);
}
} catch (final ComponentException e) {
failed = true;
throw e;
- }
- finally {
+ } finally {
unlockComponent(failed, containerComponent);
}
return componentInstance;
}
- /**
+ /**
* Try to modify the delete and return two cases
*
* @param containerComponentParam
@@ -1384,15 +1310,13 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
* @param userId
* @return
*/
- public Either<ComponentInstance, ResponseFormat> deleteAbstractComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) {
+ public Either<ComponentInstance, ResponseFormat> deleteAbstractComponentInstance(String containerComponentParam, String containerComponentId,
+ String componentInstanceId, String userId) {
log.debug("enter deleteAbstractComponentInstance");
validateUserExists(userId);
-
final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
-
org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
validateCanWorkOnComponent(containerComponent, userId);
-
boolean failed = false;
ComponentInstance deletedRelatedInst;
try {
@@ -1400,17 +1324,17 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
final Optional<ComponentInstance> componentInstanceById = containerComponent.getComponentInstanceById(componentInstanceId);
if (componentInstanceById.isPresent()) {
ComponentInstance componentInstance = componentInstanceById.get();
- Either<String, StorageOperationStatus> deleteServiceFilterEither =
- nodeFilterOperation.deleteNodeFilter(containerComponent, componentInstanceId);
+ Either<String, StorageOperationStatus> deleteServiceFilterEither = nodeFilterOperation
+ .deleteNodeFilter(containerComponent, componentInstanceId);
if (deleteServiceFilterEither.isRight()) {
log.debug("enter deleteAbstractComponentInstance:deleteServiceFilterEither is right, filed");
- ActionStatus status = componentsUtils.convertFromStorageResponse(deleteServiceFilterEither.right().value(),
- containerComponentType);
+ ActionStatus status = componentsUtils
+ .convertFromStorageResponse(deleteServiceFilterEither.right().value(), containerComponentType);
janusGraphDao.rollback();
return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName()));
}
- Either<ComponentInstance, ResponseFormat> resultOp = deleteNodeFiltersFromComponentInstance(containerComponent,
- componentInstance, ComponentTypeEnum.SERVICE, userId);
+ Either<ComponentInstance, ResponseFormat> resultOp = deleteNodeFiltersFromComponentInstance(containerComponent, componentInstance,
+ ComponentTypeEnum.SERVICE, userId);
if (resultOp.isRight()) {
log.debug("enter deleteAbstractComponentInstance:resultOp is right, filed");
janusGraphDao.rollback();
@@ -1421,11 +1345,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
log.debug("enter deleteAbstractComponentInstance:");
lockComponent(containerComponent, "deleteComponentInstance");
ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
-
- deletedRelatedInst = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId,
- containerComponentType, deletedCompInstance);
- ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator.doOnDeleteInstanceOperations(containerComponent, componentInstanceId);
- log.debug("enter deleteAbstractComponentInstance,get onDeleteOperationsStatus:{}",onDeleteOperationsStatus);
+ deletedRelatedInst = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, containerComponentType,
+ deletedCompInstance);
+ ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator
+ .doOnDeleteInstanceOperations(containerComponent, componentInstanceId);
+ log.debug("enter deleteAbstractComponentInstance,get onDeleteOperationsStatus:{}", onDeleteOperationsStatus);
if (ActionStatus.OK != onDeleteOperationsStatus) {
throw new ByActionStatusComponentException(onDeleteOperationsStatus);
}
@@ -1439,24 +1363,19 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return Either.left(deletedRelatedInst);
}
- public Either<ComponentInstance, ResponseFormat> deleteNodeFiltersFromComponentInstance(
- final Component component,
- final ComponentInstance componentInstance,
- final ComponentTypeEnum containerComponentType,
- final String userId) {
-
- final Set<String> componentFiltersIDsToBeDeleted =
- getComponentFiltersRelatedToComponentInstance(component.getUniqueId(), componentInstance);
+ public Either<ComponentInstance, ResponseFormat> deleteNodeFiltersFromComponentInstance(final Component component,
+ final ComponentInstance componentInstance,
+ final ComponentTypeEnum containerComponentType,
+ final String userId) {
+ final Set<String> componentFiltersIDsToBeDeleted = getComponentFiltersRelatedToComponentInstance(component.getUniqueId(), componentInstance);
if (!componentFiltersIDsToBeDeleted.isEmpty()) {
- final Set<String> ids = component.getComponentInstances().stream()
- .filter(ci -> componentFiltersIDsToBeDeleted.contains(ci.getName()))
+ final Set<String> ids = component.getComponentInstances().stream().filter(ci -> componentFiltersIDsToBeDeleted.contains(ci.getName()))
.map(ComponentInstance::getUniqueId).collect(Collectors.toSet());
- final Either<Set<String>, StorageOperationStatus> deleteComponentNodeFiltersEither =
- nodeFilterOperation.deleteNodeFilters(component, ids);
+ final Either<Set<String>, StorageOperationStatus> deleteComponentNodeFiltersEither = nodeFilterOperation
+ .deleteNodeFilters(component, ids);
if (deleteComponentNodeFiltersEither.isRight()) {
final ActionStatus status = componentsUtils
- .convertFromStorageResponse(deleteComponentNodeFiltersEither.right().value(),
- containerComponentType);
+ .convertFromStorageResponse(deleteComponentNodeFiltersEither.right().value(), containerComponentType);
return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName()));
}
for (final String id : ids) {
@@ -1465,11 +1384,10 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
final ComponentInstance componentInstanceToBeUpdated = componentInstanceById.get();
-
componentInstanceToBeUpdated.setDirectives(Collections.emptyList());
- final Either<ComponentInstance, ResponseFormat> componentInstanceResponseFormatEither =
- updateComponentInstanceMetadata(containerComponentType.getValue(), component.getUniqueId(),
- componentInstanceToBeUpdated.getUniqueId(), userId, componentInstanceToBeUpdated, false);
+ final Either<ComponentInstance, ResponseFormat> componentInstanceResponseFormatEither = updateComponentInstanceMetadata(
+ containerComponentType.getValue(), component.getUniqueId(), componentInstanceToBeUpdated.getUniqueId(), userId,
+ componentInstanceToBeUpdated, false);
if (componentInstanceResponseFormatEither.isRight()) {
return componentInstanceResponseFormatEither;
}
@@ -1478,19 +1396,17 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return Either.left(componentInstance);
}
- private Set<String> getComponentFiltersRelatedToComponentInstance(String containerComponentId,
- ComponentInstance componentInstance) {
+ private Set<String> getComponentFiltersRelatedToComponentInstance(String containerComponentId, ComponentInstance componentInstance) {
ComponentParametersView filter = new ComponentParametersView(true);
filter.setIgnoreComponentInstances(false);
- Either<Component, StorageOperationStatus> componentFilterOrigin =
- toscaOperationFacade.getToscaElement(containerComponentId, filter);
+ Either<Component, StorageOperationStatus> componentFilterOrigin = toscaOperationFacade.getToscaElement(containerComponentId, filter);
final Component component = componentFilterOrigin.left().value();
return ComponentsUtils.getNodesFiltersToBeDeleted(component, componentInstance);
}
- ComponentInstance deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId,
- ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) {
- if(containerComponentType == ComponentTypeEnum.SERVICE){
+ ComponentInstance deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId, ComponentTypeEnum containerComponentType,
+ ComponentInstance componentInstance) {
+ if (containerComponentType == ComponentTypeEnum.SERVICE) {
List<String> pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstance.getName());
if (!pathIDsToBeDeleted.isEmpty()) {
deleteForwardingPaths(containerComponentId, pathIDsToBeDeleted);
@@ -1499,48 +1415,43 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return componentInstance;
}
- private void deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete){
-
+ private void deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete) {
Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
- if(storageStatus.isRight()) {
+ if (storageStatus.isRight()) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus.right().value()));
}
- Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation.deleteForwardingPath(storageStatus.left().value(),
- Sets.newHashSet(pathIdsToDelete));
-
- if(result.isRight()) {
+ Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation
+ .deleteForwardingPath(storageStatus.left().value(), Sets.newHashSet(pathIdsToDelete));
+ if (result.isRight()) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(result.right().value()));
}
}
- private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId){
+ private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId) {
Collection<ForwardingPathDataDefinition> allPaths = getForwardingPathDataDefinitions(containerComponentId);
List<String> pathIDsToBeDeleted = new ArrayList<>();
-
- allPaths.stream().filter(path -> isPathRelatedToComponent(path,componentInstanceId ))
- .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId()));
-
+ allPaths.stream().filter(path -> isPathRelatedToComponent(path, componentInstanceId))
+ .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId()));
return pathIDsToBeDeleted;
}
private Collection<ForwardingPathDataDefinition> getForwardingPathDataDefinitions(String containerComponentId) {
ComponentParametersView filter = new ComponentParametersView(true);
filter.setIgnoreServicePath(false);
- Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade
- .getToscaElement(containerComponentId, filter);
+ Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade.getToscaElement(containerComponentId, filter);
return forwardingPathOrigin.left().value().getForwardingPaths().values();
}
- private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition,
- String componentInstanceId){
- return pathDataDefinition.getPathElements().getListToscaDataDefinition()
- .stream().anyMatch(elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) ||
- elementDataDefinition.getToNode()
- .equalsIgnoreCase(componentInstanceId));
+ private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition, String componentInstanceId) {
+ return pathDataDefinition.getPathElements().getListToscaDataDefinition().stream().anyMatch(
+ elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) || elementDataDefinition.getToNode()
+ .equalsIgnoreCase(componentInstanceId));
}
- private ComponentInstance deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) {
- Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
+ private ComponentInstance deleteComponentInstance(Component containerComponent, String componentInstanceId,
+ ComponentTypeEnum containerComponentType) {
+ Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade
+ .deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
if (deleteRes.isRight()) {
log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
@@ -1548,26 +1459,29 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
ComponentInstance deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
-
if (CollectionUtils.isNotEmpty(containerComponent.getInputs())) {
- List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
+ List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream()
+ .filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(inputsToDelete)) {
- StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, inputsToDelete);
+ StorageOperationStatus deleteInputsRes = toscaOperationFacade
+ .deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, inputsToDelete);
if (deleteInputsRes != StorageOperationStatus.OK) {
log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
- throw new ByActionStatusComponentException(
- componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId);
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType),
+ componentInstanceId);
}
}
}
if (CollectionUtils.isNotEmpty(containerComponent.getOutputs())) {
- final List<OutputDefinition> outputsToDelete = containerComponent.getOutputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
+ final List<OutputDefinition> outputsToDelete = containerComponent.getOutputs().stream()
+ .filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(outputsToDelete)) {
- final StorageOperationStatus deleteOutputsRes = toscaOperationFacade.deleteComponentInstanceOutputsFromTopologyTemplate(containerComponent, outputsToDelete);
+ final StorageOperationStatus deleteOutputsRes = toscaOperationFacade
+ .deleteComponentInstanceOutputsFromTopologyTemplate(containerComponent, outputsToDelete);
if (deleteOutputsRes != StorageOperationStatus.OK) {
log.debug("Failed to delete outputs of the component instance {} from container component. ", componentInstanceId);
- throw new ByActionStatusComponentException(
- componentsUtils.convertFromStorageResponse(deleteOutputsRes, containerComponentType), componentInstanceId);
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(deleteOutputsRes, containerComponentType),
+ componentInstanceId);
}
}
}
@@ -1588,8 +1502,10 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
private void findAndRemoveComponentInstanceRelations(String componentInstanceId, Component containerComponent) {
- if(CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())){
- containerComponent.setComponentInstancesRelations(containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r)).collect(Collectors.toList()));
+ if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())) {
+ containerComponent.setComponentInstancesRelations(
+ containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r))
+ .collect(Collectors.toList()));
}
}
@@ -1597,19 +1513,16 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId);
}
- public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
+ public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef,
+ ComponentTypeEnum componentTypeEnum) {
return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, true);
}
public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef,
ComponentTypeEnum componentTypeEnum, boolean needLock) {
-
validateUserExists(userId);
-
RequirementCapabilityRelDef requirementCapabilityRelDef;
-
org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
-
validateCanWorkOnComponent(containerComponent, userId);
boolean failed = false;
try {
@@ -1617,22 +1530,21 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
lockComponent(containerComponent, ASSOCIATE_RI_TO_RI);
}
requirementCapabilityRelDef = associateRIToRIOnGraph(containerComponent, requirementDef);
- }catch (ComponentException e){
+ } catch (ComponentException e) {
failed = true;
throw e;
- }finally {
- if (needLock)
+ } finally {
+ if (needLock) {
unlockComponent(failed, containerComponent);
+ }
}
return requirementCapabilityRelDef;
}
public RequirementCapabilityRelDef associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef) {
-
log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
-
- Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(null, containerComponent.getUniqueId(), requirementDef);
-
+ Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade
+ .associateResourceInstances(null, containerComponent.getUniqueId(), requirementDef);
if (result.isLeft()) {
log.debug(ENTITY_ON_GRAPH_IS_CREATED);
return result.left().value();
@@ -1642,7 +1554,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
String toNameOrId = "";
Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
-
toNameOrId = requirementDef.getFromNode();
fromNameOrId = requirementDef.getFromNode();
if (fromResult.isLeft()) {
@@ -1651,12 +1562,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
if (toResult.isLeft()) {
toNameOrId = toResult.left().value().getName();
}
-
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponseForResourceInstance
- (result.right().value(), true), fromNameOrId, toNameOrId,
- requirementDef.getRelationships().get(0).getRelation().getRequirement());
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true),
+ fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement());
}
-
}
/**
@@ -1666,12 +1574,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
* @param componentTypeEnum
* @return
*/
- public List<RequirementCapabilityRelDef> batchDissociateRIFromRI(
- String componentId,
- String userId,
- List<RequirementCapabilityRelDef> requirementDefList,
- ComponentTypeEnum componentTypeEnum) {
-
+ public List<RequirementCapabilityRelDef> batchDissociateRIFromRI(String componentId, String userId,
+ List<RequirementCapabilityRelDef> requirementDefList,
+ ComponentTypeEnum componentTypeEnum) {
validateUserExists(userId);
org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
validateCanWorkOnComponent(containerComponent, userId);
@@ -1680,41 +1585,40 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
try {
lockComponent(containerComponent, ASSOCIATE_RI_TO_RI);
for (RequirementCapabilityRelDef requirementDef : requirementDefList) {
- RequirementCapabilityRelDef requirementCapabilityRelDef = dissociateRIFromRI(
- componentId, userId, requirementDef, containerComponent.getComponentType());
+ RequirementCapabilityRelDef requirementCapabilityRelDef = dissociateRIFromRI(componentId, userId, requirementDef,
+ containerComponent.getComponentType());
delOkResult.add(requirementCapabilityRelDef);
}
- }catch (ComponentException e){
+ } catch (ComponentException e) {
failed = true;
throw e;
- }finally {
+ } finally {
unlockComponent(failed, containerComponent);
}
return delOkResult;
}
- public RequirementCapabilityRelDef dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
+ public RequirementCapabilityRelDef dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef,
+ ComponentTypeEnum componentTypeEnum) {
validateUserExists(userId);
-
org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
-
validateCanWorkOnComponent(containerComponent, userId);
boolean failed = false;
try {
lockComponent(containerComponent, ASSOCIATE_RI_TO_RI);
log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
- Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef);
+ Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade
+ .dissociateResourceInstances(componentId, requirementDef);
if (result.isLeft()) {
log.debug(ENTITY_ON_GRAPH_IS_CREATED);
return result.left().value();
} else {
-
log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
String fromNameOrId = "";
String toNameOrId = "";
- Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
+ Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent,
+ requirementDef.getFromNode());
Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
-
toNameOrId = requirementDef.getFromNode();
fromNameOrId = requirementDef.getFromNode();
if (fromResult.isLeft()) {
@@ -1723,57 +1627,57 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
if (toResult.isLeft()) {
toNameOrId = toResult.left().value().getName();
}
-
throw new ByActionStatusComponentException(
- componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true),
- fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement());
+ componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId,
+ requirementDef.getRelationships().get(0).getRelation().getRequirement());
}
- }catch (ComponentException e){
+ } catch (ComponentException e) {
failed = true;
throw e;
- }finally {
+ } finally {
unlockComponent(failed, containerComponent);
}
}
+
/**
* Allows to get relation contained in specified component according to received Id
+ *
* @param componentId
* @param relationId
* @param userId
* @param componentTypeEnum
* @return
*/
- public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId, ComponentTypeEnum componentTypeEnum) {
-
+ public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId,
+ ComponentTypeEnum componentTypeEnum) {
Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
try {
org.openecomp.sdc.be.model.Component containerComponent = null;
RequirementCapabilityRelDef foundRelation = null;
-
validateUserExists(userId);
containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations();
foundRelation = findRelation(relationId, requirementCapabilityRelations);
- if(foundRelation == null){
+ if (foundRelation == null) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId);
log.debug("Relation with id {} was not found on the component", relationId, componentId);
resultOp = Either.right(responseFormat);
}
- if(resultOp == null){
+ if (resultOp == null) {
resultOp = setRelatedCapability(foundRelation, containerComponent);
}
- if(resultOp.isLeft()){
+ if (resultOp.isLeft()) {
resultOp = setRelatedRequirement(foundRelation, containerComponent);
}
} catch (Exception e) {
log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
return resultOp;
}
private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) {
- for(RequirementCapabilityRelDef relationship : requirementCapabilityRelations){
+ for (RequirementCapabilityRelDef relationship : requirementCapabilityRelations) {
if (relationship.getRelationships().stream().anyMatch(r -> r.getRelation().getId().equals(relationId))) {
return relationship;
}
@@ -1781,13 +1685,14 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return null;
}
- private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
+ private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation,
+ Component containerComponent) {
Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
String instanceId = foundRelation.getFromNode();
Optional<RequirementDefinition> foundRequirement;
- Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream()
- .filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
+ Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId))
+ .findFirst();
if (!instance.isPresent()) {
ResponseFormat responseFormat = componentsUtils
.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance",
@@ -1807,12 +1712,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
if (result == null) {
Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade
- .getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation,
- this::isBelongingFullRequirement);
+ .getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullRequirement);
if (getfulfilledRequirementRes.isRight()) {
ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(),
- instanceId, containerComponent.getUniqueId());
+ .getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId,
+ containerComponent.getUniqueId());
log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId,
containerComponent.getUniqueId());
result = Either.right(responseFormat);
@@ -1827,24 +1731,23 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
private boolean isBelongingFullRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) {
- return req.getName().equals(relationshipInfo.getRequirement()) &&
- req.getUniqueId().equals(relationshipInfo.getRequirementUid()) &&
- req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
+ return req.getName().equals(relationshipInfo.getRequirement()) && req.getUniqueId().equals(relationshipInfo.getRequirementUid()) && req
+ .getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
}
private boolean isBelongingCalcRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req, LifecycleStateEnum state) {
- return nameMatches(relationshipInfo.getRequirement(), req.getName(), req.getPreviousName(), state) &&
- req.getUniqueId().equals(relationshipInfo.getRequirementUid()) &&
- req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
+ return nameMatches(relationshipInfo.getRequirement(), req.getName(), req.getPreviousName(), state) && req.getUniqueId()
+ .equals(relationshipInfo.getRequirementUid()) && req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
}
- private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
+ private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation,
+ Component containerComponent) {
Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
String instanceId = foundRelation.getToNode();
Optional<CapabilityDefinition> foundCapability;
- Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream()
- .filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
+ Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId))
+ .findFirst();
if (!instance.isPresent()) {
ResponseFormat responseFormat = componentsUtils
.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance",
@@ -1863,13 +1766,12 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
}
if (result == null) {
- Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes =
- toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation,
- this::isBelongingFullCapability);
+ Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade
+ .getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullCapability);
if (getfulfilledRequirementRes.isRight()) {
ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(),
- instanceId, containerComponent.getUniqueId());
+ .getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId,
+ containerComponent.getUniqueId());
log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId,
containerComponent.getUniqueId());
result = Either.right(responseFormat);
@@ -1877,73 +1779,61 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value());
}
}
- if(result == null){
+ if (result == null) {
result = Either.left(foundRelation);
}
return result;
}
private boolean isBelongingFullCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) {
- return cap.getName().equals(relationshipInfo.getCapability()) &&
- cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) &&
- cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
+ return cap.getName().equals(relationshipInfo.getCapability()) && cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) && cap
+ .getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
}
private boolean isBelongingCalcCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap, LifecycleStateEnum state) {
- return nameMatches(relationshipInfo.getCapability(), cap.getName(), cap.getPreviousName(), state) &&
- cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) &&
- cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
+ return nameMatches(relationshipInfo.getCapability(), cap.getName(), cap.getPreviousName(), state) && cap.getUniqueId()
+ .equals(relationshipInfo.getCapabilityUid()) && cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
}
private boolean nameMatches(String nameFromRelationship, String currName, String previousName, LifecycleStateEnum state) {
- return state == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT ?
- currName.equals(nameFromRelationship):
- previousName!= null && previousName.equals(nameFromRelationship);
+ return state == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT ? currName.equals(nameFromRelationship)
+ : previousName != null && previousName.equals(nameFromRelationship);
}
private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
- Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
+ Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation
+ .updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
Either<ComponentInstanceProperty, ResponseFormat> result;
if (eitherAttribute.isLeft()) {
log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
-
result = Either.left(instanceAttribute);
-
} else {
log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
-
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
-
result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
-
}
return result;
}
private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
-
Either<ComponentInstanceProperty, ResponseFormat> result;
-
Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
-
if (!errorWrapper.isEmpty()) {
result = Either.right(errorWrapper.getInnerElement());
} else {
- Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
+ Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation
+ .addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
if (eitherAttribute.isLeft()) {
log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
result = Either.left(instanceAttribute);
-
} else {
log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId);
-
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
-
}
}
return result;
@@ -1959,10 +1849,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
* @param userId
* @return
*/
- public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) {
+ public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId,
+ String resourceInstanceId,
+ ComponentInstanceProperty attribute, String userId) {
Either<ComponentInstanceProperty, ResponseFormat> result = null;
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
-
validateUserExists(userId);
if (errorWrapper.isEmpty()) {
validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
@@ -1973,7 +1864,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
if (errorWrapper.isEmpty()) {
validateComponentLock(componentId, componentTypeEnum, errorWrapper);
}
-
try {
if (errorWrapper.isEmpty()) {
final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
@@ -1986,9 +1876,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
result = Either.right(errorWrapper.getInnerElement());
}
return result;
- }
-
- finally {
+ } finally {
if (result == null || result.isRight()) {
janusGraphDao.rollback();
} else {
@@ -1999,10 +1887,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
}
- public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties, String userId) {
-
+ public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum,
+ String componentId, String resourceInstanceId,
+ List<ComponentInstanceProperty> properties,
+ String userId) {
Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
-
/*-------------------------------Validations---------------------------------*/
validateUserExists(userId);
@@ -2032,7 +1921,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
if (resourceInstanceStatus.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
- resourceInstanceId, "resource instance", "service", componentId));
+ resourceInstanceId, "resource instance", "service", componentId));
}
ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
@@ -2042,37 +1931,39 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
log.debug(FAILED_TO_LOCK_SERVICE, componentId);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
}
- List <ComponentInstanceProperty> updatedProperties = new ArrayList<>();
+ List<ComponentInstanceProperty> updatedProperties = new ArrayList<>();
try {
- for (ComponentInstanceProperty property: properties) {
+ for (ComponentInstanceProperty property : properties) {
validateMandatoryFields(property);
- ComponentInstanceProperty componentInstanceProperty = validatePropertyExistsOnComponent(property, containerComponent, foundResourceInstance);
+ ComponentInstanceProperty componentInstanceProperty = validatePropertyExistsOnComponent(property, containerComponent,
+ foundResourceInstance);
String propertyParentUniqueId = property.getParentUniqueId();
Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, false);
if (updatedPropertyValue.isRight()) {
log.error("Failed to update property object value of property: {}",
- property);
+ property);
throw new ByResponseFormatComponentException(updatedPropertyValue.right().value());
}
Optional<CapabilityDefinition>
- capPropDefinition = getPropertyCapabilityOfChildInstance(propertyParentUniqueId, foundResourceInstance.getCapabilities());
+ capPropDefinition = getPropertyCapabilityOfChildInstance(propertyParentUniqueId, foundResourceInstance.getCapabilities());
if (capPropDefinition.isPresent()) {
updatedPropertyValue
- .bimap(updatedValue -> updateCapabilityPropFromUpdateInstProp(property, updatedValue,
- containerComponent, foundResourceInstance, capPropDefinition.get().getType(),
- capPropDefinition.get().getName()), Either::right);
+ .bimap(updatedValue -> updateCapabilityPropFromUpdateInstProp(property, updatedValue,
+ containerComponent, foundResourceInstance, capPropDefinition.get().getType(),
+ capPropDefinition.get().getName()), Either::right);
} else {
updatedPropertyValue.bimap(
- updatedValue -> {
- componentInstanceProperty.setValue(updatedValue);
- return updatePropertyOnContainerComponent(property, updatedValue,
- containerComponent, foundResourceInstance);
- }, Either::right);
+ updatedValue -> {
+ componentInstanceProperty.setValue(updatedValue);
+ return updatePropertyOnContainerComponent(property, updatedValue,
+ containerComponent, foundResourceInstance);
+ }, Either::right);
updatedProperties.add(componentInstanceProperty);
}
}
- Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
+ Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
+ .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
if (updateContainerRes.isRight()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
@@ -2094,13 +1985,16 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
private void validateMandatoryFields(PropertyDataDefinition property) {
if (StringUtils.isEmpty(property.getName())) {
- throw new ByActionStatusComponentException (ActionStatus.MISSING_PROPERTY_NAME);
+ throw new ByActionStatusComponentException(ActionStatus.MISSING_PROPERTY_NAME);
}
}
- private ComponentInstanceProperty validatePropertyExistsOnComponent(ComponentInstanceProperty property, Component containerComponent, ComponentInstance foundResourceInstance) {
- List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(foundResourceInstance.getUniqueId());
- Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getName().equals(property.getName())).findAny();
+ private ComponentInstanceProperty validatePropertyExistsOnComponent(ComponentInstanceProperty property, Component containerComponent,
+ ComponentInstance foundResourceInstance) {
+ List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties()
+ .get(foundResourceInstance.getUniqueId());
+ Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getName().equals(property.getName()))
+ .findAny();
if (!instanceProperty.isPresent()) {
throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, property.getName());
}
@@ -2108,11 +2002,12 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property,
- String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
+ String newValue, Component containerComponent,
+ ComponentInstance foundResourceInstance,
String capabilityType, String capabilityName) {
String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
- foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
+ foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
if (actionStatus != null) {
return actionStatus;
}
@@ -2126,13 +2021,13 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
String capabilityType, String capabilityName) {
String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
Either<Component, StorageOperationStatus> getComponentRes =
- toscaOperationFacade.getToscaFullElement(foundResourceInstance.getComponentUid());
- if(getComponentRes.isRight()) {
+ toscaOperationFacade.getToscaFullElement(foundResourceInstance.getComponentUid());
+ if (getComponentRes.isRight()) {
return componentsUtils.getResponseFormat(getComponentRes.right().value());
}
ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
- foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
+ foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
if (actionStatus != null) {
return actionStatus;
}
@@ -2155,20 +2050,22 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
if (capProperties != null) {
Optional<ComponentInstanceProperty> instanceProperty =
- capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
+ capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
StorageOperationStatus status;
if (instanceProperty.isPresent()) {
- String capKey = ModelConverter.buildCapabilityPropertyKey(foundResourceInstance.getOriginType().isAtomicType(), capabilityType, capabilityName, componentInstanceUniqueId, cap.get());
+ String capKey = ModelConverter
+ .buildCapabilityPropertyKey(foundResourceInstance.getOriginType().isAtomicType(), capabilityType, capabilityName,
+ componentInstanceUniqueId, cap.get());
instanceProperty.get().setValue(newValue);
List<String> path = new ArrayList<>();
path.add(componentInstanceUniqueId);
path.add(capKey);
instanceProperty.get().setPath(path);
status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent,
- componentInstanceUniqueId, capKey, instanceProperty.get());
+ componentInstanceUniqueId, capKey, instanceProperty.get());
if (status != StorageOperationStatus.OK) {
ActionStatus actionStatus =
- componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
+ componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
}
@@ -2179,7 +2076,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return null;
}
- private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty instanceProperty, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
+ private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty instanceProperty, String newValue,
+ Component containerComponent, ComponentInstance foundResourceInstance) {
StorageOperationStatus status;
instanceProperty.setValue(newValue);
status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), instanceProperty);
@@ -2191,19 +2089,23 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return componentsUtils.getResponseFormat(ActionStatus.OK);
}
- private <T extends PropertyDefinition> Either<String,ResponseFormat> validatePropertyObjectValue(T property, String newValue, boolean isInput) {
+ private <T extends PropertyDefinition> Either<String, ResponseFormat> validatePropertyObjectValue(T property, String newValue, boolean isInput) {
Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll();
if (allDataTypesEither.isRight()) {
JanusGraphOperationStatus status = allDataTypesEither.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
+ BeEcompErrorManager.getInstance()
+ .logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status,
+ ErrorSeverity.ERROR);
+ return Either.right(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
}
Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
String propertyType = property.getType();
String innerType = getInnerType(property);
// Specific Update Logic
- Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(property.getType(), newValue, true, innerType, allDataTypes);
+ Either<Object, Boolean> isValid = propertyOperation
+ .validateAndUpdatePropertyValue(property.getType(), newValue, true, innerType, allDataTypes);
if (isValid.isRight()) {
Boolean res = isValid.right().value();
if (!res) {
@@ -2216,14 +2118,18 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
newValue = object.toString();
}
}
- if (validateAndUpdateRules(property, isInput, allDataTypes, innerType, propertyType))
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
+ if (validateAndUpdateRules(property, isInput, allDataTypes, innerType, propertyType)) {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils
+ .convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
+ }
return Either.left(newValue);
}
- private <T extends PropertyDefinition> boolean validateAndUpdateRules(T property, boolean isInput, Map<String, DataTypeDefinition> allDataTypes, String innerType, String propertyType) {
+ private <T extends PropertyDefinition> boolean validateAndUpdateRules(T property, boolean isInput, Map<String, DataTypeDefinition> allDataTypes,
+ String innerType, String propertyType) {
if (!isInput) {
- ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
+ ImmutablePair<String, Boolean> pair = propertyOperation
+ .validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
if (pair.getRight() != null && !pair.getRight()) {
BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
return true;
@@ -2232,12 +2138,15 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return false;
}
- private <T extends PropertyDefinition> Either<String,ResponseFormat> updatePropertyObjectValue(T property, boolean isInput) {
+ private <T extends PropertyDefinition> Either<String, ResponseFormat> updatePropertyObjectValue(T property, boolean isInput) {
Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll();
if (allDataTypesEither.isRight()) {
JanusGraphOperationStatus status = allDataTypesEither.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
+ BeEcompErrorManager.getInstance()
+ .logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status,
+ ErrorSeverity.ERROR);
+ return Either.right(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
}
Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
String innerType = null;
@@ -2249,23 +2158,27 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
SchemaDefinition def = property.getSchema();
if (def == null) {
log.debug("Schema doesn't exists for property of type {}", type);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
+ return Either
+ .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
}
PropertyDataDefinition propDef = def.getProperty();
if (propDef == null) {
log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
+ return Either
+ .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
}
innerType = propDef.getType();
}
// Specific Update Logic
- Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
+ Either<Object, Boolean> isValid = propertyOperation
+ .validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
String newValue = property.getValue();
if (isValid.isRight()) {
Boolean res = isValid.right().value();
if (!res) {
log.debug("validate and update property value has failed with value: {}", property.getValue());
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
+ DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
}
} else {
Object object = isValid.left().value();
@@ -2274,16 +2187,19 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
}
if (!isInput) {
- ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
+ ImmutablePair<String, Boolean> pair = propertyOperation
+ .validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
if (pair.getRight() != null && pair.getRight() == false) {
BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
+ DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
}
}
return Either.left(newValue);
}
- private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
+ private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent,
+ ComponentInstance foundResourceInstance) {
StorageOperationStatus status;
input.setValue(newValue);
status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
@@ -2295,7 +2211,10 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return componentsUtils.getResponseFormat(ActionStatus.OK);
}
- public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceInput> inputs, String userId) {
+ public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum,
+ String componentId, String resourceInstanceId,
+ List<ComponentInstanceInput> inputs,
+ String userId) {
Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null;
@@ -2327,7 +2246,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
if (resourceInstanceStatus.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
- resourceInstanceId, "resource instance", "service", componentId));
+ resourceInstanceId, "resource instance", "service", componentId));
}
ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
@@ -2338,19 +2257,21 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
log.debug(FAILED_TO_LOCK_SERVICE, componentId);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
}
- List <ComponentInstanceInput> updatedInputs = new ArrayList<>();
+ List<ComponentInstanceInput> updatedInputs = new ArrayList<>();
try {
- for (ComponentInstanceInput input: inputs) {
+ for (ComponentInstanceInput input : inputs) {
validateMandatoryFields(input);
ComponentInstanceInput componentInstanceInput = validateInputExistsOnComponent(input, containerComponent, foundResourceInstance);
Either<String, ResponseFormat> validatedInputValue = validatePropertyObjectValue(componentInstanceInput, input.getValue(), true);
- if (validatedInputValue.isRight()){
+ if (validatedInputValue.isRight()) {
throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT, input.getName());
}
- updateInputOnContainerComponent(componentInstanceInput, validatedInputValue.left().value(), containerComponent, foundResourceInstance);
+ updateInputOnContainerComponent(componentInstanceInput, validatedInputValue.left().value(), containerComponent,
+ foundResourceInstance);
updatedInputs.add(componentInstanceInput);
}
- Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
+ Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
+ .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
if (updateContainerRes.isRight()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
@@ -2371,7 +2292,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
- private ComponentInstanceInput validateInputExistsOnComponent(ComponentInstanceInput input, Component containerComponent, ComponentInstance foundResourceInstance) {
+ private ComponentInstanceInput validateInputExistsOnComponent(ComponentInstanceInput input, Component containerComponent,
+ ComponentInstance foundResourceInstance) {
List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId());
Optional<ComponentInstanceInput> instanceInput = instanceProperties.stream().filter(p -> p.getName().equals(input.getName())).findAny();
if (!instanceInput.isPresent()) {
@@ -2380,7 +2302,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return instanceInput.get();
}
- public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property, String userId) {
+ public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum,
+ String componentId, String resourceInstanceId,
+ String groupInstanceId,
+ ComponentInstanceProperty property,
+ String userId) {
Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
@@ -2409,7 +2335,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
if (propertyValueUid == null) {
- Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
+ Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation
+ .increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
if (counterRes.isRight()) {
log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
@@ -2418,7 +2345,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
}
Integer index = counterRes.left().value();
- Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
+ Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation
+ .addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
if (result.isLeft()) {
log.trace("Property value was added to resource instance {}", resourceInstanceId);
@@ -2435,7 +2363,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
} else {
- Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
+ Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation
+ .updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
if (result.isLeft()) {
log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
@@ -2474,7 +2403,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
- public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) {
+ public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId,
+ String resourceInstanceId, String propertyValueId, String userId) {
validateUserExists(userId);
@@ -2499,7 +2429,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return resultOp;
}
try {
- Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
+ Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation
+ .removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
if (result.isLeft()) {
log.debug("Property value {} was removed from graph.", propertyValueId);
@@ -2536,7 +2467,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
Component component;
Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
if (getComponentRes.isRight()) {
- log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName());
+ log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(),
+ componentInstance.getName());
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING);
}
@@ -2544,14 +2476,14 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
LifecycleStateEnum resourceCurrState = component.getLifecycleState();
if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
ActionStatus actionStatus = ActionStatus.CONTAINER_CANNOT_CONTAIN_COMPONENT_IN_STATE;
- throw new ByActionStatusComponentException(actionStatus, containerComponent.getComponentType().toString(), resourceCurrState.toString());
+ throw new ByActionStatusComponentException(actionStatus, containerComponent.getComponentType().toString(), resourceCurrState.toString());
}
- if (component.isArchived() == true){
+ if (component.isArchived() == true) {
ActionStatus actionStatus = ActionStatus.COMPONENT_IS_ARCHIVED;
throw new ByActionStatusComponentException(actionStatus, component.getName());
}
final Map<String, InterfaceDefinition> componentInterfaces = component.getInterfaces();
- if(MapUtils.isNotEmpty(componentInterfaces)) {
+ if (MapUtils.isNotEmpty(componentInterfaces)) {
componentInterfaces.forEach(componentInstance::addInterface);
}
return component;
@@ -2570,10 +2502,10 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
//Fetch current component instance
Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance =
- getResourceInstanceById(containerComponent, componentInstanceId);
+ getResourceInstanceById(containerComponent, componentInstanceId);
if (eitherResourceInstance.isRight()) {
resultOp = Either.right(componentsUtils.getResponseFormat(
- ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
+ ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
return resultOp;
}
ComponentInstance currentResourceInstance = eitherResourceInstance.left().value();
@@ -2584,7 +2516,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
if (componentExistsRes.isRight()) {
log.debug("Failed to find resource {}", resourceId);
resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse
- (componentExistsRes.right().value()), resourceId));
+ (componentExistsRes.right().value()), resourceId));
return resultOp;
} else if (!componentExistsRes.left().value()) {
log.debug("The resource {} not found ", resourceId);
@@ -2593,24 +2525,24 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
//Fetch component using new component instance uid
- Component updatedContainerComponent=getOriginComponentFromComponentInstance(newComponentInstance);
+ Component updatedContainerComponent = getOriginComponentFromComponentInstance(newComponentInstance);
Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent,
- currentResourceInstance, updatedContainerComponent);
- resultOp=Either.left(toDeleteForwardingPaths);
+ currentResourceInstance, updatedContainerComponent);
+ resultOp = Either.left(toDeleteForwardingPaths);
return resultOp;
}
private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance,
Component updatedContainerComponent) {
- DataForMergeHolder dataForMergeHolder=new DataForMergeHolder();
+ DataForMergeHolder dataForMergeHolder = new DataForMergeHolder();
dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getName());
Service service = (Service) containerComponent;
ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils();
return forwardingPathUtils.
- getForwardingPathsToBeDeletedOnVersionChange(service,dataForMergeHolder,updatedContainerComponent);
+ getForwardingPathsToBeDeletedOnVersionChange(service, dataForMergeHolder, updatedContainerComponent);
}
private ComponentParametersView getComponentParametersViewForForwardingPath() {
@@ -2620,32 +2552,35 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return componentParametersView;
}
- public ComponentInstance changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
+ public ComponentInstance changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId,
+ String userId, ComponentInstance newComponentInstance) {
User user = validateUserExists(userId);
final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
ComponentParametersView componentParametersView = new ComponentParametersView();
componentParametersView.setIgnoreCapabiltyProperties(false);
- org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
+ org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType,
+ componentParametersView);
validateCanWorkOnComponent(containerComponent, userId);
Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId);
if (resourceInstanceStatus.isRight()) {
- throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId);
+ throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId,
+ containerComponentId);
}
ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
- return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType );
+ return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType);
}
public ComponentInstance changeInstanceVersion(org.openecomp.sdc.be.model.Component containerComponent,
- ComponentInstance currentResourceInstance,
- ComponentInstance newComponentInstance,
- User user,
- final ComponentTypeEnum containerComponentType) {
+ ComponentInstance currentResourceInstance,
+ ComponentInstance newComponentInstance,
+ User user,
+ final ComponentTypeEnum containerComponentType) {
boolean failed = false;
Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus;
@@ -2699,17 +2634,19 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
throw new ByActionStatusComponentException(
componentsUtils.convertFromStorageResponse(fillProxyRes));
}
- } else if (originType == OriginTypeEnum.ServiceSubstitution){
- final Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade.getToscaFullElement(newComponentInstance.getComponentUid());
- if (getServiceResult.isRight()) {
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
- }
- final Component service = getServiceResult.left().value();
-
- final Either<Component, StorageOperationStatus> getServiceDerivedFromTypeResult = toscaOperationFacade.getLatestByToscaResourceName(service.getDerivedFromGenericType());
- if (getServiceDerivedFromTypeResult.isRight()) {
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
- }
+ } else if (originType == OriginTypeEnum.ServiceSubstitution) {
+ final Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade
+ .getToscaFullElement(newComponentInstance.getComponentUid());
+ if (getServiceResult.isRight()) {
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
+ }
+ final Component service = getServiceResult.left().value();
+
+ final Either<Component, StorageOperationStatus> getServiceDerivedFromTypeResult = toscaOperationFacade
+ .getLatestByToscaResourceName(service.getDerivedFromGenericType());
+ if (getServiceDerivedFromTypeResult.isRight()) {
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
+ }
origComponent = getServiceDerivedFromTypeResult.left().value();
@@ -2775,7 +2712,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
// US831698
- public List<ComponentInstanceProperty> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) {
+ public List<ComponentInstanceProperty> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId,
+ String componentInstanceUniqueId, String userId) {
Component containerComponent = null;
boolean failed = false;
@@ -2785,13 +2723,16 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
if (validateContainerComponentExists.isRight()) {
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()));
+ throw new ByActionStatusComponentException(
+ componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()));
}
containerComponent = validateContainerComponentExists.left().value();
- Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
+ Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
+ componentInstanceUniqueId);
if (resourceInstanceStatus.isRight()) {
- throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId);
+ throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId,
+ containerComponentId);
}
List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
@@ -2868,13 +2809,17 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
* @param inTransaction
* @return
*/
- public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
+ public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(
+ ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
Either<ComponentInstanceData, ResponseFormat> result;
- Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
+ Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation
+ .updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
inTransaction);
if (updateComponentInstanceRes.isRight()) {
- log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value());
- result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
+ log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(),
+ updateComponentInstanceRes.right().value());
+ result = Either
+ .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
} else {
result = Either.left(updateComponentInstanceRes.left().value());
}
@@ -2896,12 +2841,12 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return Either.left(new ComponentInstance());
}
- private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
+ private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance,
+ String newInstanceName) {
return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent);
}
private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) {
-
Either<ComponentInstance, StorageOperationStatus> result = Either.right(StorageOperationStatus.NOT_FOUND);
List<ComponentInstance> instances = containerComponent.getComponentInstances();
Optional<ComponentInstance> foundInstance = Optional.empty();
@@ -2920,38 +2865,33 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
-
Long creationDate = origInstanceForUpdate.getCreationTime();
-
Long modificationTime = System.currentTimeMillis();
resourceInstanceForUpdate.setCreationTime(creationDate);
resourceInstanceForUpdate.setModificationTime(modificationTime);
-
resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
-
if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
}
-
resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
-
- if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon()))
+ if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon())) {
resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
-
- if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion()))
+ }
+ if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion())) {
resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
-
- if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName()))
+ }
+ if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName())) {
resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
-
- if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName()))
+ }
+ if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName())) {
resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
-
+ }
if (resourceInstanceForUpdate.getOriginType() == null) {
resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
}
- if(resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy)
+ if (resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy) {
resourceInstanceForUpdate.setIsProxy(true);
+ }
if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
}
@@ -2969,8 +2909,10 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
return resourceInstanceForUpdate;
}
+
/**
* Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
+ *
* @param containerComponentType
* @param containerComponentId
* @param componentInstanceUniqueId
@@ -2980,10 +2922,10 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
* @param ownerId
* @return
*/
- public List<ComponentInstanceProperty> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, String userId) {
-
+ public List<ComponentInstanceProperty> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId,
+ String componentInstanceUniqueId, String capabilityType,
+ String capabilityName, String ownerId, String userId) {
Component containerComponent = null;
-
List<ComponentInstanceProperty> resultOp = null;
try {
validateUserExists(userId);
@@ -3002,12 +2944,15 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return resultOp;
}
- private List<ComponentInstanceProperty> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId, Map<String, List<CapabilityDefinition>> instanceCapabilities) {
+ private List<ComponentInstanceProperty> findCapabilityOfInstance(String componentId, String instanceId, String capabilityType,
+ String capabilityName, String ownerId,
+ Map<String, List<CapabilityDefinition>> instanceCapabilities) {
CapabilityDefinition foundCapability;
if (MapUtils.isNotEmpty(instanceCapabilities)) {
List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
if (capabilitiesPerType != null) {
- Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
+ Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream()
+ .filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
if (capabilityOpt.isPresent()) {
foundCapability = capabilityOpt.get();
return foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties();
@@ -3017,43 +2962,42 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId);
}
- private List<ComponentInstanceProperty> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId) {
+ private List<ComponentInstanceProperty> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType,
+ String capabilityName, String ownerId) {
try {
return toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId)
- .left()
- .on(this::componentInstancePropertyListException);
- } catch(Exception e){
- log.debug("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e);
+ .left().on(this::componentInstancePropertyListException);
+ } catch (Exception e) {
+ log.debug("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId,
+ capabilityName, e);
throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
}
}
public Either<RequirementDefinition, ResponseFormat> updateInstanceRequirement(ComponentTypeEnum componentTypeEnum, String containerComponentId,
String componentInstanceUniqueId,
- RequirementDefinition requirementDef, String userId) {
-
+ RequirementDefinition requirementDef, String userId) {
Either<RequirementDefinition, ResponseFormat> resultOp = null;
-
validateUserExists(userId);
if (componentTypeEnum == null) {
BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceRequirement", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
}
Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
-
if (getResourceResult.isRight()) {
log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
Component containerComponent = getResourceResult.left().value();
-
if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
- Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
+ Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
+ componentInstanceUniqueId);
if (resourceInstanceStatus.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
+ return Either.right(componentsUtils
+ .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
}
// lock resource
StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
@@ -3061,15 +3005,16 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
log.debug("Failed to lock component {}", containerComponentId);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
}
-
try {
- StorageOperationStatus updateRequirementStatus = toscaOperationFacade.updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDef);
+ StorageOperationStatus updateRequirementStatus = toscaOperationFacade
+ .updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDef);
if (updateRequirementStatus != StorageOperationStatus.OK) {
- log.debug("Failed to update component instance requirement on instance {} in container {}", componentInstanceUniqueId, containerComponentId);
+ log.debug("Failed to update component instance requirement on instance {} in container {}", componentInstanceUniqueId,
+ containerComponentId);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateRequirementStatus)));
}
- Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
-
+ Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
+ .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
if (updateContainerRes.isRight()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
@@ -3077,7 +3022,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
resultOp = Either.left(requirementDef);
return resultOp;
-
} finally {
if (resultOp == null || resultOp.isRight()) {
janusGraphDao.rollback();
@@ -3089,30 +3033,33 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
}
- public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName,
- List<ComponentInstanceProperty> properties, String userId) {
+ public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum,
+ String containerComponentId,
+ String componentInstanceUniqueId,
+ String capabilityType, String capabilityName,
+ List<ComponentInstanceProperty> properties,
+ String userId) {
Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
-
validateUserExists(userId);
if (componentTypeEnum == null) {
BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
}
Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
-
if (getResourceResult.isRight()) {
log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
Component containerComponent = getResourceResult.left().value();
-
if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
- Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
+ Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
+ componentInstanceUniqueId);
if (resourceInstanceStatus.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
+ return Either.right(componentsUtils
+ .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
}
ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
// lock resource
@@ -3121,16 +3068,15 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
log.debug("Failed to lock component {}", containerComponentId);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
}
-
try {
for (ComponentInstanceProperty property : properties) {
Either<String, ResponseFormat> newPropertyValueEither = validatePropertyObjectValue(property, property.getValue(), false);
- newPropertyValueEither.bimap(updatedValue ->
- updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName),
- Either::right);
+ newPropertyValueEither.bimap(
+ updatedValue -> updateCapabilityPropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance,
+ capabilityType, capabilityName), Either::right);
}
- Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
-
+ Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
+ .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
if (updateContainerRes.isRight()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
@@ -3138,7 +3084,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
resultOp = Either.left(properties);
return resultOp;
-
} finally {
if (resultOp == null || resultOp.isRight()) {
janusGraphDao.rollback();
@@ -3151,62 +3096,46 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
public Either<Map<String, ComponentInstance>, ResponseFormat> copyComponentInstance(ComponentInstance inputComponentInstance,
- String containerComponentId,
- String componentInstanceId,
+ String containerComponentId, String componentInstanceId,
String userId) {
-
Map<String, ComponentInstance> resultMap = new HashMap<>();
Either<Component, StorageOperationStatus> getOrigComponent = toscaOperationFacade.getToscaElement(containerComponentId);
if (getOrigComponent.isRight()) {
log.error("Failed to get the original component information");
- return Either.right(componentsUtils.getResponseFormat(
- ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
}
-
Component origComponent = getOrigComponent.left().value();
-
try {
lockComponent(origComponent, "copyComponentInstance");
-
} catch (ComponentException e) {
log.error("destComponentInstance's data is {}", origComponent.toString());
- return Either.right(componentsUtils.getResponseFormat(
- ActionStatus.USER_DEFINED, "Failed to lock component destComponentInstance's data is {}", origComponent.toString()));
+ return Either.right(componentsUtils
+ .getResponseFormat(ActionStatus.USER_DEFINED, "Failed to lock component destComponentInstance's data is {}",
+ origComponent.toString()));
}
-
boolean failed = false;
ComponentInstance actionResponse = null;
try {
-
- actionResponse = createComponentInstance(
- "services", containerComponentId, userId, inputComponentInstance, false);
-
+ actionResponse = createComponentInstance("services", containerComponentId, userId, inputComponentInstance, false);
} catch (ComponentException e) {
failed = true;
// on failure of the create instance unlock the resource and rollback the transaction.
return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
} finally {
-
// on failure of the create instance unlock the resource and rollback the transaction.
if (null == actionResponse) {
log.error(FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS);
-
unlockComponent(failed, origComponent);
}
}
-
Either<String, ResponseFormat> resultOp = null;
-
try {
ComponentInstance destComponentInstance = actionResponse;
log.debug("destComponentInstance's data is {}", destComponentInstance);
-
resultOp = deepCopyComponentInstance(origComponent, containerComponentId, componentInstanceId, destComponentInstance, userId);
-
resultMap.put("componentInstance", destComponentInstance);
} finally {
// unlock resource
-
if (resultOp == null || resultOp.isRight()) {
unlockComponent(true, origComponent);
janusGraphDao.rollback();
@@ -3218,66 +3147,58 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
}
if (resultOp == null || resultOp.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas"));
+ return Either
+ .right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas"));
} else {
return Either.left(resultMap);
}
-
}
- private Either<String, ResponseFormat> deepCopyComponentInstance(
- Component sourceComponent, String containerComponentId, String sourceComponentInstanceId,
- ComponentInstance destComponentInstance, String userId) {
-
+ private Either<String, ResponseFormat> deepCopyComponentInstance(Component sourceComponent, String containerComponentId,
+ String sourceComponentInstanceId, ComponentInstance destComponentInstance,
+ String userId) {
Either<Component, StorageOperationStatus> getDestComponent = toscaOperationFacade.getToscaElement(containerComponentId);
if (getDestComponent.isRight()) {
log.error("Failed to get the dest component information");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
}
-
Component destComponent = getDestComponent.left().value();
-
- Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs = copyComponentInstanceWithPropertiesAndInputs(
- sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance);
+ Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs = copyComponentInstanceWithPropertiesAndInputs(sourceComponent,
+ destComponent, sourceComponentInstanceId, destComponentInstance);
if (copyComponentInstanceWithPropertiesAndInputs.isRight()) {
log.error("Failed to copy component instance with properties and inputs as part of deep copy");
- return Either.right(componentsUtils.getResponseFormat(
- ActionStatus.USER_DEFINED, "Failed to copy the component instance with properties and inputs as part of deep copy"));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED,
+ "Failed to copy the component instance with properties and inputs as part of deep copy"));
}
-
- Either<String, ResponseFormat> copyComponentInstanceWithAttributes = copyComponentInstanceWithAttributes(
- sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance, userId);
+ Either<String, ResponseFormat> copyComponentInstanceWithAttributes = copyComponentInstanceWithAttributes(sourceComponent, destComponent,
+ sourceComponentInstanceId, destComponentInstance, userId);
if (copyComponentInstanceWithAttributes.isRight()) {
log.error("Failed to copy component instance with attributes as part of deep copy");
- return Either.right(componentsUtils.getResponseFormat(
- ActionStatus.USER_DEFINED, "Failed to copy the component instance with attributes as part of deep copy"));
+ return Either.right(componentsUtils
+ .getResponseFormat(ActionStatus.USER_DEFINED, "Failed to copy the component instance with attributes as part of deep copy"));
}
return Either.left(COPY_COMPONENT_INSTANCE_OK);
}
- private Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs(
- Component sourceComponent, Component destComponent, String sourceComponentInstanceId,
- ComponentInstance destComponentInstance) {
+ private Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs(Component sourceComponent, Component destComponent,
+ String sourceComponentInstanceId,
+ ComponentInstance destComponentInstance) {
log.debug("start to copy ComponentInstance with properties and inputs");
-
List<ComponentInstanceProperty> sourcePropList = null;
if (sourceComponent.getComponentInstancesProperties() != null
&& sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId) != null) {
sourcePropList = sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId);
log.debug("sourcePropList");
}
-
List<ComponentInstanceProperty> destPropList = null;
String destComponentInstanceId = destComponentInstance.getUniqueId();
log.debug("destComponentInstanceId: {}", destComponentInstance.getUniqueId());
if (destComponent.getComponentInstancesProperties() != null
- && destComponent.getComponentInstancesProperties().get(destComponentInstanceId) != null) {
+ && destComponent.getComponentInstancesProperties().get(destComponentInstanceId) != null) {
destPropList = destComponent.getComponentInstancesProperties().get(destComponentInstanceId);
log.debug("destPropList {}");
}
-
List<ComponentInstancePropInput> componentInstancePropInputList = new ArrayList<>();
-
if (null != destPropList && null != sourcePropList) {
log.debug("start to set property and attribute");
for (ComponentInstanceProperty destProp : destPropList) {
@@ -3288,32 +3209,28 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
log.debug("now set property");
final List<GetInputValueDataDefinition> getInputValues = sourceProp.getGetInputValues();
- if (getInputValues == null && !StringUtils.isEmpty(sourceProp.getValue())
- && (destProp.getValue() == null || !destProp.getValue().equals(sourceProp.getValue()))) {
+ if (getInputValues == null && !StringUtils.isEmpty(sourceProp.getValue()) && (destProp.getValue() == null || !destProp.getValue()
+ .equals(sourceProp.getValue()))) {
log.debug("Now starting to copy the property {} in value {}", destPropertyName, sourceProp.getValue());
-
destProp.setValue(sourceProp.getValue());
- Either<String, ResponseFormat> updatePropertyValueEither = updateComponentInstanceProperty(
- destComponent.getUniqueId(), destComponentInstanceId, destProp);
+ Either<String, ResponseFormat> updatePropertyValueEither = updateComponentInstanceProperty(destComponent.getUniqueId(),
+ destComponentInstanceId, destProp);
if (updatePropertyValueEither.isRight()) {
log.error("Failed to copy the property {}", destPropertyName);
- return Either.right(componentsUtils.getResponseFormat(
- ActionStatus.INVALID_CONTENT_PARAM, "Failed to paste component instance to the canvas, property copy"));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
+ "Failed to paste component instance to the canvas, property copy"));
}
break;
}
-
log.debug("Now start to update inputs");
-
if (getInputValues != null) {
if (getInputValues.isEmpty()) {
log.debug("property is return from input, set by man");
break;
}
log.debug("Now starting to copy the {} property", destPropertyName);
-
- Either<String, ResponseFormat> getSourceInputDefaultValue = getInputListDefaultValue(
- sourceComponent, getInputValues.get(0).getInputId());
+ Either<String, ResponseFormat> getSourceInputDefaultValue = getInputListDefaultValue(sourceComponent,
+ getInputValues.get(0).getInputId());
if (getSourceInputDefaultValue.isRight()) {
return Either.right(getSourceInputDefaultValue.right().value());
}
@@ -3325,121 +3242,93 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return Either.left(COPY_COMPONENT_INSTANCE_OK);
}
- private Either<String, ResponseFormat> copyComponentInstanceWithAttributes(Component sourceComponent,
- Component destComponent,
+ private Either<String, ResponseFormat> copyComponentInstanceWithAttributes(Component sourceComponent, Component destComponent,
String sourceComponentInstanceId,
- ComponentInstance destComponentInstance,
- String userId) {
+ ComponentInstance destComponentInstance, String userId) {
String destComponentInstanceId = destComponentInstance.getUniqueId();
-
log.info("start to copy component instance with attributes");
-
List<ComponentInstanceAttribute> sourceAttributeList = null;
if (sourceComponent.getComponentInstancesAttributes() != null
- && sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId) != null) {
+ && sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId) != null) {
sourceAttributeList = sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId);
log.info("sourceAttributes {}");
}
-
List<ComponentInstanceAttribute> destAttributeList = null;
if (destComponent.getComponentInstancesAttributes() != null
- && destComponent.getComponentInstancesAttributes().get(destComponentInstanceId) != null) {
+ && destComponent.getComponentInstancesAttributes().get(destComponentInstanceId) != null) {
destAttributeList = destComponent.getComponentInstancesAttributes().get(destComponentInstanceId);
log.info("destAttributeList {}");
}
if (null != sourceAttributeList && null != destAttributeList) {
log.info("set attribute");
-
for (ComponentInstanceAttribute sourceAttribute : sourceAttributeList) {
String sourceAttributeName = sourceAttribute.getName();
for (ComponentInstanceAttribute destAttribute : destAttributeList) {
if (sourceAttributeName.equals(destAttribute.getName())) {
log.debug("Start to copy the attribute exists {}", sourceAttributeName);
-
sourceAttribute.setUniqueId(
- UniqueIdBuilder.buildResourceInstanceUniuqeId(
- "attribute", destComponentInstanceId.split("\\.")[1], sourceAttributeName));
-
- Either<ComponentInstanceAttribute, ResponseFormat> updateAttributeValueEither =
- createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum.SERVICE,
- destComponent.getUniqueId(), destComponentInstanceId, sourceAttribute,
- userId);
+ UniqueIdBuilder.buildResourceInstanceUniuqeId("attribute", destComponentInstanceId.split("\\.")[1], sourceAttributeName));
+ Either<ComponentInstanceAttribute, ResponseFormat> updateAttributeValueEither = createOrUpdateAttributeValueForCopyPaste(
+ ComponentTypeEnum.SERVICE, destComponent.getUniqueId(), destComponentInstanceId, sourceAttribute, userId);
if (updateAttributeValueEither.isRight()) {
log.error("Failed to copy the attribute");
- return Either.right(componentsUtils
- .getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
- "Failed to paste component instance to the canvas, attribute copy"));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
+ "Failed to paste component instance to the canvas, attribute copy"));
}
break;
}
}
}
}
-
return Either.left(COPY_COMPONENT_INSTANCE_OK);
}
private Either<ComponentInstanceAttribute, ResponseFormat> createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum componentTypeEnum,
- String componentId,
- String resourceInstanceId,
- ComponentInstanceAttribute attribute,
- String userId) {
-
+ String componentId, String resourceInstanceId,
+ ComponentInstanceAttribute attribute,
+ String userId) {
Either<ComponentInstanceAttribute, ResponseFormat> resultOp = null;
-
validateUserExists(userId);
-
if (componentTypeEnum == null) {
- BeEcompErrorManager.getInstance().logInvalidInputError(
- "createOrUpdateAttributeValue", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
+ BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateAttributeValue", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
return resultOp;
}
-
Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
-
if (getResourceResult.isRight()) {
log.info("Failed to retrieve component id {}", componentId);
resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
return resultOp;
}
-
Component containerComponent = getResourceResult.left().value();
-
Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
-
if (resourceInstanceStatus.isRight()) {
- resultOp = Either.right(componentsUtils.getResponseFormat(
- ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
+ resultOp = Either
+ .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
return resultOp;
}
-
ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
-
-
String propertyType = attribute.getType();
ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
log.info("The type of attribute id{},is {} ", attribute.getUniqueId(), propertyType);
-
if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
SchemaDefinition def = attribute.getSchema();
if (def == null) {
log.info("Schema doesn't exists for attribute of type {}", type);
- return Either.right(componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
+ return Either
+ .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
}
PropertyDataDefinition propDef = def.getProperty();
if (propDef == null) {
log.info("Attribute in Schema Definition inside attribute of type {} doesn't exist", type);
- return Either.right(componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
+ return Either
+ .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
}
}
-
List<ComponentInstanceAttribute> instanceAttributes = containerComponent.getComponentInstancesAttributes().get(resourceInstanceId);
- Optional<ComponentInstanceAttribute> instanceAttribute = instanceAttributes.stream().filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny();
+ Optional<ComponentInstanceAttribute> instanceAttribute = instanceAttributes.stream()
+ .filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny();
StorageOperationStatus status;
-
if (instanceAttribute.isPresent()) {
log.info("updateComponentInstanceAttribute");
status = toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
@@ -3455,54 +3344,41 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
List<String> path = new ArrayList<>();
path.add(foundResourceInstance.getUniqueId());
attribute.setPath(path);
-
foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
- Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.
- updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
-
+ Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
+ .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
if (updateContainerRes.isRight()) {
- ActionStatus actionStatus = componentsUtils.
- convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
- resultOp = Either.right(componentsUtils.
- getResponseFormatForResourceInstanceProperty(actionStatus, ""));
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
return resultOp;
}
resultOp = Either.left(attribute);
return resultOp;
}
- private Either<String, ResponseFormat> updateComponentInstanceProperty(String containerComponentId,
- String componentInstanceId,
+ private Either<String, ResponseFormat> updateComponentInstanceProperty(String containerComponentId, String componentInstanceId,
ComponentInstanceProperty property) {
Either<String, ResponseFormat> resultOp;
Either<Component, StorageOperationStatus> getComponent = toscaOperationFacade.getToscaElement(containerComponentId);
-
if (getComponent.isRight()) {
log.error("Failed to get the component information");
- return Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(
- ActionStatus.INVALID_CONTENT_PARAM, "Failed to get the component information"));
+ return Either.right(componentsUtils
+ .getResponseFormatForResourceInstanceProperty(ActionStatus.INVALID_CONTENT_PARAM, "Failed to get the component information"));
}
-
Component containerComponent = getComponent.left().value();
-
- StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceProperty(
- containerComponent, componentInstanceId, property);
+ StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
if (status != StorageOperationStatus.OK) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
return resultOp;
}
-
- Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.
- updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
-
+ Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
+ .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
if (updateContainerRes.isRight()) {
- ActionStatus actionStatus = componentsUtils.
- convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
return resultOp;
}
-
return Either.left("Update OK");
}
@@ -3518,34 +3394,31 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
}
log.error("The input's default value with id {} is not found", inputId);
- return Either.right(componentsUtils.getResponseFormat(
- ActionStatus.USER_DEFINED, "Failed to paste component instance to the canvas"));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to paste component instance to the canvas"));
}
/**
* Method to delete selected nodes and edges on composition page
+ *
* @param containerComponentType
* @param componentId
* @param componentInstanceIdList
* @param userId
* @return
*/
- public Map<String, List<String>> batchDeleteComponentInstance(String containerComponentType,
- String componentId,
- List<String> componentInstanceIdList,
- String userId) {
-
+ public Map<String, List<String>> batchDeleteComponentInstance(String containerComponentType, String componentId,
+ List<String> componentInstanceIdList, String userId) {
List<String> deleteErrorIds = new ArrayList<>();
Map<String, List<String>> deleteErrorMap = new HashMap<>();
validateUserExists(userId);
- org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, ComponentTypeEnum.findByParamName(containerComponentType), null);
-
+ org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId,
+ ComponentTypeEnum.findByParamName(containerComponentType), null);
boolean failed = false;
try {
lockComponent(containerComponent, "batchDeleteComponentInstance");
for (String eachInstanceId : componentInstanceIdList) {
- Either<ComponentInstance, ResponseFormat> actionResponse = batchDeleteComponentInstance(
- containerComponent, containerComponentType, eachInstanceId);
+ Either<ComponentInstance, ResponseFormat> actionResponse = batchDeleteComponentInstance(containerComponent, containerComponentType,
+ eachInstanceId);
log.debug("batchDeleteResourceInstances actionResponse is {}", actionResponse);
if (actionResponse.isRight()) {
log.error("Failed to delete ComponentInstance [{}]", eachInstanceId);
@@ -3555,27 +3428,23 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
//sending the ids of the error nodes that were not deleted to UI
deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
return deleteErrorMap;
- }catch (ComponentException e){
+ } catch (ComponentException e) {
failed = true;
throw e;
- }finally {
+ } finally {
unlockComponent(failed, containerComponent);
}
}
- private Either<ComponentInstance, ResponseFormat> batchDeleteComponentInstance(Component containerComponent,
- String containerComponentType,
+ private Either<ComponentInstance, ResponseFormat> batchDeleteComponentInstance(Component containerComponent, String containerComponentType,
String componentInstanceId) {
-
ComponentInstance resultOp;
final ComponentTypeEnum containerComponentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-
try {
resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentTypeEnum);
log.info("Successfully deleted instance with id {}", componentInstanceId);
return Either.left(resultOp);
- }
- catch (ComponentException e){
+ } catch (ComponentException e) {
log.error("Failed to deleteComponentInstance with instanceId[{}]", componentInstanceId);
return Either.right(new ResponseFormat());
}
@@ -3585,5 +3454,4 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
final User user = userValidations.validateUserExists(userId);
userValidations.validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN));
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInterfaceOperationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInterfaceOperationBusinessLogic.java
index e32c51f7da..e73ade119e 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInterfaceOperationBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInterfaceOperationBusinessLogic.java
@@ -18,7 +18,6 @@
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
@@ -59,163 +58,125 @@ import org.springframework.beans.factory.annotation.Autowired;
@org.springframework.stereotype.Component("componentInterfaceOperationBusinessLogic")
public class ComponentInterfaceOperationBusinessLogic extends BaseBusinessLogic {
+ private static final Logger LOGGER = LoggerFactory.getLogger(ComponentInterfaceOperationBusinessLogic.class);
private final ComponentValidations componentValidations;
- private static final Logger LOGGER = LoggerFactory.getLogger(ComponentInterfaceOperationBusinessLogic .class);
-
@Autowired
- public ComponentInterfaceOperationBusinessLogic(final IElementOperation elementDao,
- final IGroupOperation groupOperation,
+ public ComponentInterfaceOperationBusinessLogic(final IElementOperation elementDao, final IGroupOperation groupOperation,
final IGroupInstanceOperation groupInstanceOperation,
- final IGroupTypeOperation groupTypeOperation,
- final InterfaceOperation interfaceOperation,
+ final IGroupTypeOperation groupTypeOperation, final InterfaceOperation interfaceOperation,
final InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
final ArtifactsOperations artifactToscaOperation,
final ComponentValidations componentValidations) {
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation,
- interfaceLifecycleTypeOperation, artifactToscaOperation);
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+ artifactToscaOperation);
this.componentValidations = componentValidations;
}
- public Optional<ComponentInstance> updateComponentInstanceInterfaceOperation(final String componentId,
- final String componentInstanceId,
+ public Optional<ComponentInstance> updateComponentInstanceInterfaceOperation(final String componentId, final String componentInstanceId,
final InterfaceDefinition interfaceDefinition,
final ComponentTypeEnum componentTypeEnum,
- final Wrapper<ResponseFormat> errorWrapper,
- final boolean shouldLock)
+ final Wrapper<ResponseFormat> errorWrapper, final boolean shouldLock)
throws BusinessLogicException {
-
final Component component = getComponent(componentId);
- final Optional<ComponentInstance> componentInstanceOptional = componentValidations
- .getComponentInstance(component, componentInstanceId);
+ final Optional<ComponentInstance> componentInstanceOptional = componentValidations.getComponentInstance(component, componentInstanceId);
ResponseFormat responseFormat;
if (componentInstanceOptional.isEmpty()) {
responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND);
- LOGGER.debug("Failed to found component instance with id {}, error: {}",
- componentInstanceId, responseFormat);
+ LOGGER.debug("Failed to found component instance with id {}, error: {}", componentInstanceId, responseFormat);
errorWrapper.setInnerElement(responseFormat);
return Optional.empty();
}
-
- Map<String, List<ComponentInstanceInterface>> componentInstancesInterfaceMap = component
- .getComponentInstancesInterfaces();
+ Map<String, List<ComponentInstanceInterface>> componentInstancesInterfaceMap = component.getComponentInstancesInterfaces();
if (MapUtils.isEmpty(componentInstancesInterfaceMap)) {
componentInstancesInterfaceMap = new HashMap<>();
component.setComponentInstancesInterfaces(componentInstancesInterfaceMap);
}
- final List<ComponentInstanceInterface> componentInstanceInterfaceList = componentInstancesInterfaceMap
- .get(componentInstanceId);
-
+ final List<ComponentInstanceInterface> componentInstanceInterfaceList = componentInstancesInterfaceMap.get(componentInstanceId);
if (CollectionUtils.isEmpty(componentInstanceInterfaceList)) {
responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND);
- LOGGER.debug("Failed to found component instance with id {}, error: {}",
- componentInstanceId, responseFormat);
+ LOGGER.debug("Failed to found component instance with id {}, error: {}", componentInstanceId, responseFormat);
errorWrapper.setInnerElement(responseFormat);
return Optional.empty();
}
-
- final Optional<OperationDataDefinition> optionalOperationDataDefinition = interfaceDefinition
- .getOperations().values().stream().findFirst();
+ final Optional<OperationDataDefinition> optionalOperationDataDefinition = interfaceDefinition.getOperations().values().stream().findFirst();
if (optionalOperationDataDefinition.isEmpty()) {
responseFormat = componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND);
- LOGGER.debug("Failed to found interface operation on component instance with id {}, error: {}",
- componentInstanceId, responseFormat);
+ LOGGER.debug("Failed to found interface operation on component instance with id {}, error: {}", componentInstanceId, responseFormat);
errorWrapper.setInnerElement(responseFormat);
return Optional.empty();
}
final OperationDataDefinition updatedOperationDataDefinition = optionalOperationDataDefinition.get();
- final Optional<ComponentInstanceInterface> optionalComponentInstanceInterface = componentInstanceInterfaceList
- .stream().filter(ci -> ci.getOperations().values().stream().anyMatch(operationDataDefinition ->
- operationDataDefinition.getUniqueId()
- .equalsIgnoreCase(updatedOperationDataDefinition.getUniqueId()))).findFirst();
-
+ final Optional<ComponentInstanceInterface> optionalComponentInstanceInterface = componentInstanceInterfaceList.stream().filter(
+ ci -> ci.getOperations().values().stream().anyMatch(
+ operationDataDefinition -> operationDataDefinition.getUniqueId().equalsIgnoreCase(updatedOperationDataDefinition.getUniqueId())))
+ .findFirst();
if (optionalComponentInstanceInterface.isEmpty()) {
responseFormat = componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT);
- LOGGER.debug("Failed to found ComponentInstanceInterface on component instance with id {}, error: {}",
- componentInstanceId, responseFormat);
+ LOGGER
+ .debug("Failed to found ComponentInstanceInterface on component instance with id {}, error: {}", componentInstanceId, responseFormat);
errorWrapper.setInnerElement(responseFormat);
return Optional.empty();
}
-
updateOperationDefinitionImplementation(updatedOperationDataDefinition);
-
- optionalComponentInstanceInterface.get().getOperations()
- .replace(updatedOperationDataDefinition.getName(), updatedOperationDataDefinition);
-
+ optionalComponentInstanceInterface.get().getOperations().replace(updatedOperationDataDefinition.getName(), updatedOperationDataDefinition);
boolean wasLocked = false;
try {
if (shouldLock) {
lockComponent(componentId, component, "Update Interface Operation on Component instance");
wasLocked = true;
}
-
- final StorageOperationStatus status = toscaOperationFacade
- .updateComponentInstanceInterfaces(component, componentInstanceId);
-
+ final StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceInterfaces(component, componentInstanceId);
if (status != StorageOperationStatus.OK) {
janusGraphDao.rollback();
- responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.GENERAL_ERROR);
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
LOGGER.error("Exception occurred when updating Component Instance Interfaces {}", responseFormat);
errorWrapper.setInnerElement(responseFormat);
return Optional.empty();
}
-
final ComponentParametersView componentFilter = new ComponentParametersView();
componentFilter.disableAll();
componentFilter.setIgnoreUsers(false);
componentFilter.setIgnoreComponentInstances(false);
componentFilter.setIgnoreInterfaces(false);
componentFilter.setIgnoreComponentInstancesInterfaces(false);
-
final Either<Component, StorageOperationStatus> operationStatusEither = toscaOperationFacade
.updateComponentInstanceMetadataOfTopologyTemplate(component, componentFilter);
-
if (operationStatusEither.isRight()) {
janusGraphDao.rollback();
- responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.GENERAL_ERROR);
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
LOGGER.error("Exception occurred when updating Component Instance Topology template {}", responseFormat);
errorWrapper.setInnerElement(responseFormat);
return Optional.empty();
}
janusGraphDao.commit();
-
} catch (final Exception e) {
janusGraphDao.rollback();
- LOGGER.error("Exception occurred when updating Interface Operation on Component Instance: {}",
- e.getMessage(), e);
+ LOGGER.error("Exception occurred when updating Interface Operation on Component Instance: {}", e.getMessage(), e);
responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
errorWrapper.setInnerElement(responseFormat);
throw new BusinessLogicException(responseFormat);
-
} finally {
if (wasLocked) {
unlockComponent(component.getUniqueId(), componentTypeEnum);
}
}
-
return componentInstanceOptional;
-
}
public User validateUser(final String userId) {
final User user = userValidations.validateUserExists(userId);
- userValidations
- .validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN));
+ userValidations.validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN));
return user;
}
- private void unlockComponent(final String componentUniqueId,
- final ComponentTypeEnum componentType) {
+ private void unlockComponent(final String componentUniqueId, final ComponentTypeEnum componentType) {
graphLockOperation.unlockComponent(componentUniqueId, componentType.getNodeType());
}
private void updateOperationDefinitionImplementation(final OperationDataDefinition updatedOperationDataDefinition) {
final ArtifactDataDefinition artifactInfo = new ArtifactDataDefinition();
- artifactInfo.setArtifactName(
- String.format("'%s'", updatedOperationDataDefinition.getImplementation().getArtifactName())
- );
+ artifactInfo.setArtifactName(String.format("'%s'", updatedOperationDataDefinition.getImplementation().getArtifactName()));
updatedOperationDataDefinition.setImplementation(artifactInfo);
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentLocker.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentLocker.java
index 5358cf5be4..c7fb395db1 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentLocker.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentLocker.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
@@ -28,9 +27,8 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
import org.openecomp.sdc.common.log.wrappers.Logger;
-
@org.springframework.stereotype.Component
-public class ComponentLocker {
+public class ComponentLocker {
private static final Logger log = Logger.getLogger(ComponentLocker.class.getName());
private final GraphLockOperation graphLockOperation;
@@ -55,7 +53,7 @@ public class ComponentLocker {
log.debug("#doLockComponent - locking component {} of type {}", id, nodeTypeEnum);
StorageOperationStatus storageOperationStatus = graphLockOperation.lockComponent(id, nodeTypeEnum);
if (storageOperationStatus != StorageOperationStatus.OK) {
- log.debug("#doLockComponent - failed to lock component {} with status {}", id, storageOperationStatus);
+ log.debug("#doLockComponent - failed to lock component {} with status {}", id, storageOperationStatus);
throw new StorageException(storageOperationStatus);
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentNodeFilterBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentNodeFilterBusinessLogic.java
index f547dcf19c..e5bb817d98 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentNodeFilterBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentNodeFilterBusinessLogic.java
@@ -16,7 +16,6 @@
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import static org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR;
@@ -59,32 +58,25 @@ import org.springframework.beans.factory.annotation.Autowired;
public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic {
private static final Logger LOGGER = Logger.getLogger(ComponentNodeFilterBusinessLogic.class.getName());
-
private final NodeFilterOperation nodeFilterOperation;
private final NodeFilterValidator nodeFilterValidator;
@Autowired
- public ComponentNodeFilterBusinessLogic(final IElementOperation elementDao,
- final IGroupOperation groupOperation,
- final IGroupInstanceOperation groupInstanceOperation,
- final IGroupTypeOperation groupTypeOperation,
+ public ComponentNodeFilterBusinessLogic(final IElementOperation elementDao, final IGroupOperation groupOperation,
+ final IGroupInstanceOperation groupInstanceOperation, final IGroupTypeOperation groupTypeOperation,
final InterfaceOperation interfaceOperation,
final InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
- final ArtifactsOperations artifactToscaOperation,
- final NodeFilterOperation nodeFilterOperation,
+ final ArtifactsOperations artifactToscaOperation, final NodeFilterOperation nodeFilterOperation,
final NodeFilterValidator nodeFilterValidator) {
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation,
- interfaceLifecycleTypeOperation, artifactToscaOperation);
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+ artifactToscaOperation);
this.nodeFilterOperation = nodeFilterOperation;
this.nodeFilterValidator = nodeFilterValidator;
}
- public Optional<CINodeFilterDataDefinition> createNodeFilterIfNotExist(final String componentId,
- final String componentInstanceId,
- final boolean shouldLock,
- final ComponentTypeEnum componentTypeEnum)
+ public Optional<CINodeFilterDataDefinition> createNodeFilterIfNotExist(final String componentId, final String componentInstanceId,
+ final boolean shouldLock, final ComponentTypeEnum componentTypeEnum)
throws BusinessLogicException {
-
final Component component = getComponent(componentId);
final Optional<ComponentInstance> componentInstance = getComponentInstance(componentInstanceId, component);
Optional<CINodeFilterDataDefinition> filterDataDefinition = getCiNodeFilterDataDefinition(componentInstance);
@@ -95,28 +87,24 @@ public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic {
boolean wasLocked = false;
try {
if (shouldLock) {
- lockComponent(component.getUniqueId(), component,"Create Node Filter on component");
+ lockComponent(component.getUniqueId(), component, "Create Node Filter on component");
wasLocked = true;
}
result = nodeFilterOperation.createNodeFilter(componentId, componentInstanceId);
if (result.isRight()) {
janusGraphDao.rollback();
- LOGGER.error(BUSINESS_PROCESS_ERROR,
- "Failed to Create Node filter on component with id {}", componentId);
- throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils
- .convertFromStorageResponse(result.right().value()), component.getSystemName()));
+ LOGGER.error(BUSINESS_PROCESS_ERROR, "Failed to Create Node filter on component with id {}", componentId);
+ throw new BusinessLogicException(componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(result.right().value()), component.getSystemName()));
} else {
filterDataDefinition = Optional.ofNullable(result.left().value());
}
janusGraphDao.commit();
LOGGER.debug("Node filter successfully created in component {} . ", component.getSystemName());
-
} catch (final Exception e) {
janusGraphDao.rollback();
- LOGGER.error(BUSINESS_PROCESS_ERROR,
- "Exception occurred during add Component node filter property values: {}", e.getMessage(), e);
+ LOGGER.error(BUSINESS_PROCESS_ERROR, "Exception occurred during add Component node filter property values: {}", e.getMessage(), e);
throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-
} finally {
if (wasLocked) {
unlockComponent(component.getUniqueId(), componentTypeEnum);
@@ -125,41 +113,32 @@ public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic {
return filterDataDefinition;
}
- public Optional<String> deleteNodeFilterIfExists(final String componentId,
- final String componentInstanceId,
- final boolean shouldLock,
- final ComponentTypeEnum componentTypeEnum)
- throws BusinessLogicException {
-
+ public Optional<String> deleteNodeFilterIfExists(final String componentId, final String componentInstanceId, final boolean shouldLock,
+ final ComponentTypeEnum componentTypeEnum) throws BusinessLogicException {
final Component component = getComponent(componentId);
- final Optional<CINodeFilterDataDefinition> nodeFilterDataDefinition =
- getCiNodeFilterDataDefinition(componentInstanceId, component);
+ final Optional<CINodeFilterDataDefinition> nodeFilterDataDefinition = getCiNodeFilterDataDefinition(componentInstanceId, component);
if (!nodeFilterDataDefinition.isPresent()) {
return Optional.ofNullable(componentInstanceId);
}
-
final Either<String, StorageOperationStatus> result;
boolean wasLocked = false;
try {
if (shouldLock) {
- lockComponent(component.getUniqueId(), component,"Delete Node Filter from component");
+ lockComponent(component.getUniqueId(), component, "Delete Node Filter from component");
wasLocked = true;
}
result = nodeFilterOperation.deleteNodeFilter(component, componentInstanceId);
if (result.isRight()) {
- LOGGER.error(BUSINESS_PROCESS_ERROR,
- "Failed to delete node filter in component {}. Response is {}. ", component.getName(),
+ LOGGER.error(BUSINESS_PROCESS_ERROR, "Failed to delete node filter in component {}. Response is {}. ", component.getName(),
result.right().value());
janusGraphDao.rollback();
- throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils
- .convertFromStorageResponse(result.right().value()), component.getSystemName()));
+ throw new BusinessLogicException(componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(result.right().value()), component.getSystemName()));
}
janusGraphDao.commit();
LOGGER.debug("Node filter successfully deleted in component {} . ", component.getSystemName());
-
} catch (final Exception e) {
- LOGGER.error(BUSINESS_PROCESS_ERROR,"Exception occurred during delete deleting node filter: {}",
- e.getMessage(), e);
+ LOGGER.error(BUSINESS_PROCESS_ERROR, "Exception occurred during delete deleting node filter: {}", e.getMessage(), e);
janusGraphDao.rollback();
throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
} finally {
@@ -170,50 +149,39 @@ public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic {
return Optional.ofNullable(result.left().value());
}
- public Optional<CINodeFilterDataDefinition> addNodeFilter(final String componentId,
- final String componentInstanceId,
- final NodeFilterConstraintAction action,
- final String propertyName,
- final String constraint,
- final boolean shouldLock,
+ public Optional<CINodeFilterDataDefinition> addNodeFilter(final String componentId, final String componentInstanceId,
+ final NodeFilterConstraintAction action, final String propertyName,
+ final String constraint, final boolean shouldLock,
final ComponentTypeEnum componentTypeEnum,
- final NodeFilterConstraintType nodeFilterConstraintType,
- final String capabilityName)
+ final NodeFilterConstraintType nodeFilterConstraintType, final String capabilityName)
throws BusinessLogicException {
-
final Component component = getComponent(componentId);
- CINodeFilterDataDefinition nodeFilterDataDefinition = validateAndReturnNodeFilterDefinition(componentInstanceId,
- action, constraint, component, nodeFilterConstraintType);
+ CINodeFilterDataDefinition nodeFilterDataDefinition = validateAndReturnNodeFilterDefinition(componentInstanceId, action, constraint,
+ component, nodeFilterConstraintType);
boolean wasLocked = false;
try {
if (shouldLock) {
- lockComponent(component.getUniqueId(), component,"Add Node Filter on Component");
+ lockComponent(component.getUniqueId(), component, "Add Node Filter on Component");
wasLocked = true;
}
- final RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition =
- new RequirementNodeFilterPropertyDataDefinition();
+ final RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition = new RequirementNodeFilterPropertyDataDefinition();
requirementNodeFilterPropertyDataDefinition.setName(propertyName);
requirementNodeFilterPropertyDataDefinition.setConstraints(Collections.singletonList(constraint));
-
- final Either<CINodeFilterDataDefinition, StorageOperationStatus> result = addNewNodeFilter(componentId,
- componentInstanceId, nodeFilterConstraintType, nodeFilterDataDefinition,
- requirementNodeFilterPropertyDataDefinition, capabilityName);
+ final Either<CINodeFilterDataDefinition, StorageOperationStatus> result = addNewNodeFilter(componentId, componentInstanceId,
+ nodeFilterConstraintType, nodeFilterDataDefinition, requirementNodeFilterPropertyDataDefinition, capabilityName);
if (result.isRight()) {
janusGraphDao.rollback();
- throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils
- .convertFromStorageResponse(result.right().value()), component.getSystemName()));
+ throw new BusinessLogicException(componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(result.right().value()), component.getSystemName()));
} else {
nodeFilterDataDefinition = result.left().value();
}
janusGraphDao.commit();
LOGGER.debug("Node filter successfully created in component {} . ", component.getSystemName());
-
} catch (final Exception e) {
janusGraphDao.rollback();
- LOGGER.error(BUSINESS_PROCESS_ERROR,
- "Exception occurred during add component node filter property values: {}", e.getMessage(), e);
+ LOGGER.error(BUSINESS_PROCESS_ERROR, "Exception occurred during add component node filter property values: {}", e.getMessage(), e);
throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-
} finally {
if (wasLocked) {
unlockComponent(component.getUniqueId(), componentTypeEnum);
@@ -222,44 +190,35 @@ public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic {
return Optional.ofNullable(nodeFilterDataDefinition);
}
- public Optional<CINodeFilterDataDefinition> deleteNodeFilter(final String componentId,
- final String componentInstanceId,
- final NodeFilterConstraintAction action,
- final String constraint,
- final int position,
- final boolean shouldLock,
- final ComponentTypeEnum componentTypeEnum,
+ public Optional<CINodeFilterDataDefinition> deleteNodeFilter(final String componentId, final String componentInstanceId,
+ final NodeFilterConstraintAction action, final String constraint, final int position,
+ final boolean shouldLock, final ComponentTypeEnum componentTypeEnum,
final NodeFilterConstraintType nodeFilterConstraintType)
throws BusinessLogicException {
-
final Component component = getComponent(componentId);
- CINodeFilterDataDefinition nodeFilterDataDefinition =
- validateAndReturnNodeFilterDefinition(componentInstanceId, action, constraint, component, nodeFilterConstraintType);
+ CINodeFilterDataDefinition nodeFilterDataDefinition = validateAndReturnNodeFilterDefinition(componentInstanceId, action, constraint,
+ component, nodeFilterConstraintType);
boolean wasLocked = false;
try {
if (shouldLock) {
- lockComponent(component.getUniqueId(), component,"Add Node Filter on Component");
+ lockComponent(component.getUniqueId(), component, "Add Node Filter on Component");
wasLocked = true;
}
final Either<CINodeFilterDataDefinition, StorageOperationStatus> result = nodeFilterOperation
- .deleteConstraint(componentId, componentInstanceId, nodeFilterDataDefinition, position,
- nodeFilterConstraintType);
+ .deleteConstraint(componentId, componentInstanceId, nodeFilterDataDefinition, position, nodeFilterConstraintType);
if (result.isRight()) {
janusGraphDao.rollback();
- throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils
- .convertFromStorageResponse(result.right().value()), component.getSystemName()));
+ throw new BusinessLogicException(componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(result.right().value()), component.getSystemName()));
} else {
nodeFilterDataDefinition = result.left().value();
}
janusGraphDao.commit();
LOGGER.debug("Node filter successfully deleted in component {} . ", component.getSystemName());
-
} catch (final Exception e) {
janusGraphDao.rollback();
- LOGGER.error(BUSINESS_PROCESS_ERROR,
- "Exception occurred during delete component node filter property values: {}", e.getMessage(), e);
+ LOGGER.error(BUSINESS_PROCESS_ERROR, "Exception occurred during delete component node filter property values: {}", e.getMessage(), e);
throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-
} finally {
if (wasLocked) {
unlockComponent(component.getUniqueId(), componentTypeEnum);
@@ -268,33 +227,26 @@ public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic {
return Optional.ofNullable(nodeFilterDataDefinition);
}
- private Either<CINodeFilterDataDefinition, StorageOperationStatus> addNewNodeFilter(
- final String componentId,
- final String componentInstanceId,
- final NodeFilterConstraintType nodeFilterConstraintType,
- final CINodeFilterDataDefinition nodeFilterDataDefinition,
- final RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition,
- final String capabilityName) {
-
+ private Either<CINodeFilterDataDefinition, StorageOperationStatus> addNewNodeFilter(final String componentId, final String componentInstanceId,
+ final NodeFilterConstraintType nodeFilterConstraintType,
+ final CINodeFilterDataDefinition nodeFilterDataDefinition,
+ final RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition,
+ final String capabilityName) {
if (NodeFilterConstraintType.PROPERTIES.equals(nodeFilterConstraintType)) {
- return nodeFilterOperation.addNewProperty(componentId, componentInstanceId, nodeFilterDataDefinition,
- requirementNodeFilterPropertyDataDefinition);
+ return nodeFilterOperation
+ .addNewProperty(componentId, componentInstanceId, nodeFilterDataDefinition, requirementNodeFilterPropertyDataDefinition);
}
- final RequirementNodeFilterCapabilityDataDefinition requirementNodeFilterCapabilityDataDefinition =
- new RequirementNodeFilterCapabilityDataDefinition();
+ final RequirementNodeFilterCapabilityDataDefinition requirementNodeFilterCapabilityDataDefinition = new RequirementNodeFilterCapabilityDataDefinition();
requirementNodeFilterCapabilityDataDefinition.setName(capabilityName);
- final ListDataDefinition<RequirementNodeFilterPropertyDataDefinition>
- propertyDataDefinitionListDataDefinition = new ListDataDefinition<>();
- propertyDataDefinitionListDataDefinition.getListToscaDataDefinition().addAll(
- Collections.singleton(requirementNodeFilterPropertyDataDefinition));
+ final ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> propertyDataDefinitionListDataDefinition = new ListDataDefinition<>();
+ propertyDataDefinitionListDataDefinition.getListToscaDataDefinition()
+ .addAll(Collections.singleton(requirementNodeFilterPropertyDataDefinition));
requirementNodeFilterCapabilityDataDefinition.setProperties(propertyDataDefinitionListDataDefinition);
- return nodeFilterOperation.addNewCapabilities(componentId, componentInstanceId, nodeFilterDataDefinition,
- requirementNodeFilterCapabilityDataDefinition);
+ return nodeFilterOperation
+ .addNewCapabilities(componentId, componentInstanceId, nodeFilterDataDefinition, requirementNodeFilterCapabilityDataDefinition);
}
-
- private void unlockComponent(final String componentUniqueId,
- final ComponentTypeEnum componentType) {
+ private void unlockComponent(final String componentUniqueId, final ComponentTypeEnum componentType) {
graphLockOperation.unlockComponent(componentUniqueId, componentType.getNodeType());
}
@@ -304,29 +256,23 @@ public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic {
return user;
}
- private Optional<ComponentInstance> getComponentInstance(final String componentInstanceId,
- final Component component) {
+ private Optional<ComponentInstance> getComponentInstance(final String componentInstanceId, final Component component) {
return component.getComponentInstanceById(componentInstanceId);
}
- private Optional<CINodeFilterDataDefinition> getCiNodeFilterDataDefinition(
- final Optional<ComponentInstance> componentInstance) {
-
+ private Optional<CINodeFilterDataDefinition> getCiNodeFilterDataDefinition(final Optional<ComponentInstance> componentInstance) {
if (componentInstance.isPresent()) {
return Optional.ofNullable(componentInstance.get().getNodeFilter());
}
return Optional.empty();
}
- private Optional<CINodeFilterDataDefinition> getCiNodeFilterDataDefinition(final String componentInstanceId,
- final Component component)
+ private Optional<CINodeFilterDataDefinition> getCiNodeFilterDataDefinition(final String componentInstanceId, final Component component)
throws BusinessLogicException {
-
- final Either<Boolean, ResponseFormat> response = nodeFilterValidator
- .validateComponentInstanceExist(component, componentInstanceId);
+ final Either<Boolean, ResponseFormat> response = nodeFilterValidator.validateComponentInstanceExist(component, componentInstanceId);
if (response.isRight()) {
- throw new BusinessLogicException(componentsUtils
- .getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND, response.right().value().getFormattedMessage()));
+ throw new BusinessLogicException(
+ componentsUtils.getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND, response.right().value().getFormattedMessage()));
}
final Optional<ComponentInstance> componentInstance = getComponentInstance(componentInstanceId, component);
if (componentInstance.isPresent()) {
@@ -336,55 +282,40 @@ public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic {
}
private CINodeFilterDataDefinition validateAndReturnNodeFilterDefinition(final String componentInstanceId,
- final NodeFilterConstraintAction action,
- final String constraint,
+ final NodeFilterConstraintAction action, final String constraint,
final Component component,
final NodeFilterConstraintType nodeFilterConstraintType)
throws BusinessLogicException {
-
validateNodeFilter(component, componentInstanceId, action, constraint, nodeFilterConstraintType);
- final Optional<CINodeFilterDataDefinition> cINodeFilterDataDefinition = getCiNodeFilterDataDefinition(
- componentInstanceId, component);
+ final Optional<CINodeFilterDataDefinition> cINodeFilterDataDefinition = getCiNodeFilterDataDefinition(componentInstanceId, component);
if (!cINodeFilterDataDefinition.isPresent()) {
throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND));
}
return cINodeFilterDataDefinition.get();
}
- private void validateNodeFilter(final Component component,
- final String componentInstanceId,
- final NodeFilterConstraintAction action,
- final String constraint,
- final NodeFilterConstraintType nodeFilterConstraintType) throws BusinessLogicException {
+ private void validateNodeFilter(final Component component, final String componentInstanceId, final NodeFilterConstraintAction action,
+ final String constraint, final NodeFilterConstraintType nodeFilterConstraintType) throws BusinessLogicException {
final Either<Boolean, ResponseFormat> response = nodeFilterValidator
.validateFilter(component, componentInstanceId, Collections.singletonList(constraint), action, nodeFilterConstraintType);
if (response.isRight()) {
- throw new BusinessLogicException(componentsUtils
- .getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND, response.right().value().getFormattedMessage()));
+ throw new BusinessLogicException(
+ componentsUtils.getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND, response.right().value().getFormattedMessage()));
}
}
- public Optional<CINodeFilterDataDefinition> updateNodeFilter(final String componentId,
- final String componentInstanceId,
- final UIConstraint uiConstraint,
- final ComponentTypeEnum componentTypeEnum,
- final NodeFilterConstraintType nodeFilterConstraintType,
- final int index)
+ public Optional<CINodeFilterDataDefinition> updateNodeFilter(final String componentId, final String componentInstanceId,
+ final UIConstraint uiConstraint, final ComponentTypeEnum componentTypeEnum,
+ final NodeFilterConstraintType nodeFilterConstraintType, final int index)
throws BusinessLogicException {
-
- final Optional<CINodeFilterDataDefinition> deleteActionResponse = deleteNodeFilter(componentId,
- componentInstanceId,
- NodeFilterConstraintAction.DELETE, null, index, true, componentTypeEnum,
- nodeFilterConstraintType);
-
+ final Optional<CINodeFilterDataDefinition> deleteActionResponse = deleteNodeFilter(componentId, componentInstanceId,
+ NodeFilterConstraintAction.DELETE, null, index, true, componentTypeEnum, nodeFilterConstraintType);
if (!deleteActionResponse.isPresent()) {
- throw new BusinessLogicException(componentsUtils
- .getResponseFormat(ActionStatus.GENERAL_ERROR, "Failed to delete node filter capabilities"));
+ throw new BusinessLogicException(
+ componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, "Failed to delete node filter capabilities"));
}
-
- return addNodeFilter(componentId.toLowerCase(), componentInstanceId, NodeFilterConstraintAction.ADD,
- uiConstraint.getServicePropertyName(), new ConstraintConvertor().convert(uiConstraint), true,
- componentTypeEnum, nodeFilterConstraintType,
+ return addNodeFilter(componentId.toLowerCase(), componentInstanceId, NodeFilterConstraintAction.ADD, uiConstraint.getServicePropertyName(),
+ new ConstraintConvertor().convert(uiConstraint), true, componentTypeEnum, nodeFilterConstraintType,
StringUtils.isEmpty(uiConstraint.getCapabilityName()) ? "" : uiConstraint.getCapabilityName());
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentSubstitutionFilterBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentSubstitutionFilterBusinessLogic.java
index 0f55ddfff1..c88746347e 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentSubstitutionFilterBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentSubstitutionFilterBusinessLogic.java
@@ -16,7 +16,6 @@
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import static org.openecomp.sdc.be.dao.api.ActionStatus.SUBSTITUTION_FILTER_NOT_FOUND;
@@ -55,31 +54,26 @@ import org.springframework.beans.factory.annotation.Autowired;
public class ComponentSubstitutionFilterBusinessLogic extends BaseBusinessLogic {
private static final Logger LOGGER = Logger.getLogger(ComponentSubstitutionFilterBusinessLogic.class);
-
private final SubstitutionFilterOperation substitutionFilterOperation;
private final NodeFilterValidator nodeFilterValidator;
@Autowired
- public ComponentSubstitutionFilterBusinessLogic(final IElementOperation elementDao,
- final IGroupOperation groupOperation,
+ public ComponentSubstitutionFilterBusinessLogic(final IElementOperation elementDao, final IGroupOperation groupOperation,
final IGroupInstanceOperation groupInstanceOperation,
- final IGroupTypeOperation groupTypeOperation,
- final InterfaceOperation interfaceOperation,
+ final IGroupTypeOperation groupTypeOperation, final InterfaceOperation interfaceOperation,
final InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
final ArtifactsOperations artifactToscaOperation,
final SubstitutionFilterOperation substitutionFilterOperation,
final NodeFilterValidator nodeFilterValidator) {
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation,
- interfaceLifecycleTypeOperation, artifactToscaOperation);
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+ artifactToscaOperation);
this.substitutionFilterOperation = substitutionFilterOperation;
this.nodeFilterValidator = nodeFilterValidator;
}
- public Optional<SubstitutionFilterDataDefinition> createSubstitutionFilterIfNotExist(final String componentId,
- final boolean shouldLock,
+ public Optional<SubstitutionFilterDataDefinition> createSubstitutionFilterIfNotExist(final String componentId, final boolean shouldLock,
final ComponentTypeEnum componentTypeEnum)
- throws BusinessLogicException {
-
+ throws BusinessLogicException {
final Component component = getComponent(componentId);
Optional<SubstitutionFilterDataDefinition> substitutionFilterDataDefinition = Optional.ofNullable(component.getSubstitutionFilter());
if (substitutionFilterDataDefinition.isPresent()) {
@@ -92,13 +86,12 @@ public class ComponentSubstitutionFilterBusinessLogic extends BaseBusinessLogic
wasLocked = true;
}
final Either<SubstitutionFilterDataDefinition, StorageOperationStatus> result = substitutionFilterOperation
- .createSubstitutionFilter(componentId);
+ .createSubstitutionFilter(componentId);
if (result.isRight()) {
janusGraphDao.rollback();
- LOGGER.error(BUSINESS_PROCESS_ERROR,
- "Failed to Create Substitution filter on component with id {}", componentId);
- throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils
- .convertFromStorageResponse(result.right().value()), component.getSystemName()));
+ LOGGER.error(BUSINESS_PROCESS_ERROR, "Failed to Create Substitution filter on component with id {}", componentId);
+ throw new BusinessLogicException(componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(result.right().value()), component.getSystemName()));
}
substitutionFilterDataDefinition = Optional.ofNullable(result.left().value());
component.setSubstitutionFilter(substitutionFilterDataDefinition.get());
@@ -106,87 +99,69 @@ public class ComponentSubstitutionFilterBusinessLogic extends BaseBusinessLogic
LOGGER.debug("Substitution filter successfully created in component {} . ", component.getSystemName());
} catch (final Exception e) {
janusGraphDao.rollback();
- LOGGER.error(BUSINESS_PROCESS_ERROR,
- "Exception occurred during add Component Substitution filter property values: {}", e.getMessage(), e);
+ LOGGER
+ .error(BUSINESS_PROCESS_ERROR, "Exception occurred during add Component Substitution filter property values: {}", e.getMessage(), e);
throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-
} finally {
if (wasLocked) {
unlockComponent(component.getUniqueId(), componentTypeEnum);
}
}
-
return substitutionFilterDataDefinition;
}
- public Optional<SubstitutionFilterDataDefinition> addSubstitutionFilter(final String componentId,
- final String propertyName,
- final String constraint,
- final boolean shouldLock,
- final ComponentTypeEnum componentTypeEnum)
- throws BusinessLogicException {
-
+ public Optional<SubstitutionFilterDataDefinition> addSubstitutionFilter(final String componentId, final String propertyName,
+ final String constraint, final boolean shouldLock,
+ final ComponentTypeEnum componentTypeEnum) throws BusinessLogicException {
final Component component = getComponent(componentId);
-
final Either<Boolean, ResponseFormat> response = nodeFilterValidator
- .validateComponentFilter(component, Collections.singletonList(constraint), NodeFilterConstraintAction.ADD);
+ .validateComponentFilter(component, Collections.singletonList(constraint), NodeFilterConstraintAction.ADD);
if (response.isRight()) {
- throw new BusinessLogicException(componentsUtils
- .getResponseFormat(ActionStatus.SUBSTITUTION_FILTER_NOT_FOUND, response.right().value().getFormattedMessage()));
+ throw new BusinessLogicException(
+ componentsUtils.getResponseFormat(ActionStatus.SUBSTITUTION_FILTER_NOT_FOUND, response.right().value().getFormattedMessage()));
}
-
boolean wasLocked = false;
try {
if (shouldLock) {
lockComponent(component.getUniqueId(), component, "Add Substitution Filter on Component");
wasLocked = true;
}
- final RequirementSubstitutionFilterPropertyDataDefinition newProperty =
- new RequirementSubstitutionFilterPropertyDataDefinition();
+ final RequirementSubstitutionFilterPropertyDataDefinition newProperty = new RequirementSubstitutionFilterPropertyDataDefinition();
newProperty.setName(propertyName);
newProperty.setConstraints(Collections.singletonList(constraint));
- final Either<SubstitutionFilterDataDefinition, StorageOperationStatus> resultEither =
- substitutionFilterOperation
- .addPropertyFilter(componentId, component.getSubstitutionFilter(), newProperty);
-
+ final Either<SubstitutionFilterDataDefinition, StorageOperationStatus> resultEither = substitutionFilterOperation
+ .addPropertyFilter(componentId, component.getSubstitutionFilter(), newProperty);
if (resultEither.isRight()) {
janusGraphDao.rollback();
- throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils
- .convertFromStorageResponse(resultEither.right().value()), component.getSystemName()));
+ throw new BusinessLogicException(componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resultEither.right().value()),
+ component.getSystemName()));
}
-
janusGraphDao.commit();
LOGGER.debug("Substitution filter successfully created in component {} . ", component.getSystemName());
return Optional.ofNullable(resultEither.left().value());
} catch (final Exception e) {
janusGraphDao.rollback();
- LOGGER.error(BUSINESS_PROCESS_ERROR,
- "Exception occurred during add component substitution filter property values: {}", e.getMessage(), e);
+ LOGGER
+ .error(BUSINESS_PROCESS_ERROR, "Exception occurred during add component substitution filter property values: {}", e.getMessage(), e);
throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-
} finally {
if (wasLocked) {
unlockComponent(component.getUniqueId(), componentTypeEnum);
}
}
-
}
- public Optional<SubstitutionFilterDataDefinition> updateSubstitutionFilter(final String componentId,
- final List<String> constraints,
- final boolean shouldLock,
- final ComponentTypeEnum componentTypeEnum)
+ public Optional<SubstitutionFilterDataDefinition> updateSubstitutionFilter(final String componentId, final List<String> constraints,
+ final boolean shouldLock, final ComponentTypeEnum componentTypeEnum)
throws BusinessLogicException {
-
final Component component = getComponent(componentId);
-
final Either<Boolean, ResponseFormat> response = nodeFilterValidator
- .validateComponentFilter(component, constraints, NodeFilterConstraintAction.UPDATE);
+ .validateComponentFilter(component, constraints, NodeFilterConstraintAction.UPDATE);
if (response.isRight()) {
- throw new BusinessLogicException(componentsUtils
- .getResponseFormat(ActionStatus.SUBSTITUTION_FILTER_NOT_FOUND, response.right().value().getFormattedMessage()));
+ throw new BusinessLogicException(
+ componentsUtils.getResponseFormat(ActionStatus.SUBSTITUTION_FILTER_NOT_FOUND, response.right().value().getFormattedMessage()));
}
-
SubstitutionFilterDataDefinition substitutionFilterDataDefinition = component.getSubstitutionFilter();
if (substitutionFilterDataDefinition == null) {
throw new BusinessLogicException(componentsUtils.getResponseFormat(SUBSTITUTION_FILTER_NOT_FOUND));
@@ -198,26 +173,23 @@ public class ComponentSubstitutionFilterBusinessLogic extends BaseBusinessLogic
wasLocked = true;
}
final List<RequirementSubstitutionFilterPropertyDataDefinition> properties = constraints.stream()
- .map(this::getRequirementSubstitutionFilterPropertyDataDefinition).collect(Collectors.toList());
+ .map(this::getRequirementSubstitutionFilterPropertyDataDefinition).collect(Collectors.toList());
final Either<SubstitutionFilterDataDefinition, StorageOperationStatus> result = substitutionFilterOperation
- .updateProperties(componentId, substitutionFilterDataDefinition, properties);
-
+ .updateProperties(componentId, substitutionFilterDataDefinition, properties);
if (result.isRight()) {
janusGraphDao.rollback();
- throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils
- .convertFromStorageResponse(result.right().value()), component.getSystemName()));
+ throw new BusinessLogicException(componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(result.right().value()), component.getSystemName()));
} else {
substitutionFilterDataDefinition = result.left().value();
}
janusGraphDao.commit();
LOGGER.debug("Substitution filter successfully updated in component {} . ", component.getSystemName());
-
} catch (final Exception e) {
janusGraphDao.rollback();
LOGGER.error(BUSINESS_PROCESS_ERROR, this.getClass().getName(),
"Exception occurred during update component substitution filter property values: {}", e);
throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-
} finally {
if (wasLocked) {
unlockComponent(component.getUniqueId(), componentTypeEnum);
@@ -226,39 +198,33 @@ public class ComponentSubstitutionFilterBusinessLogic extends BaseBusinessLogic
return Optional.ofNullable(substitutionFilterDataDefinition);
}
- public Optional<SubstitutionFilterDataDefinition> deleteSubstitutionFilter(final String componentId,
- final int position,
- final boolean shouldLock,
+ public Optional<SubstitutionFilterDataDefinition> deleteSubstitutionFilter(final String componentId, final int position, final boolean shouldLock,
final ComponentTypeEnum componentTypeEnum)
throws BusinessLogicException {
-
final Component component = getComponent(componentId);
SubstitutionFilterDataDefinition substitutionFilterDataDefinition = component.getSubstitutionFilter();
boolean wasLocked = false;
try {
if (shouldLock) {
- lockComponent(component.getUniqueId(), component,"Delete substitution Filter on Component");
+ lockComponent(component.getUniqueId(), component, "Delete substitution Filter on Component");
wasLocked = true;
}
final Either<SubstitutionFilterDataDefinition, StorageOperationStatus> result = substitutionFilterOperation
.deleteConstraint(componentId, substitutionFilterDataDefinition, position);
if (result.isRight()) {
janusGraphDao.rollback();
- throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils
- .convertFromStorageResponse(result.right().value()), component.getSystemName()));
+ throw new BusinessLogicException(componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(result.right().value()), component.getSystemName()));
} else {
substitutionFilterDataDefinition = result.left().value();
}
janusGraphDao.commit();
LOGGER.debug("Substitution filter successfully deleted in component {} . ", component.getSystemName());
-
} catch (final Exception e) {
janusGraphDao.rollback();
- LOGGER.error(BUSINESS_PROCESS_ERROR,
- "Exception occurred during delete component substitution filter property values: {}",
- e.getMessage(), e);
+ LOGGER.error(BUSINESS_PROCESS_ERROR, "Exception occurred during delete component substitution filter property values: {}", e.getMessage(),
+ e);
throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-
} finally {
if (wasLocked) {
unlockComponent(component.getUniqueId(), componentTypeEnum);
@@ -267,8 +233,7 @@ public class ComponentSubstitutionFilterBusinessLogic extends BaseBusinessLogic
return Optional.ofNullable(substitutionFilterDataDefinition);
}
- private void unlockComponent(final String componentUniqueId,
- final ComponentTypeEnum componentType) {
+ private void unlockComponent(final String componentUniqueId, final ComponentTypeEnum componentType) {
graphLockOperation.unlockComponent(componentUniqueId, componentType.getNodeType());
}
@@ -278,11 +243,8 @@ public class ComponentSubstitutionFilterBusinessLogic extends BaseBusinessLogic
return user;
}
- private RequirementSubstitutionFilterPropertyDataDefinition getRequirementSubstitutionFilterPropertyDataDefinition(
- final String constraint) {
-
- final RequirementSubstitutionFilterPropertyDataDefinition requirementSubstitutionFilterPropertyDataDefinition =
- new RequirementSubstitutionFilterPropertyDataDefinition();
+ private RequirementSubstitutionFilterPropertyDataDefinition getRequirementSubstitutionFilterPropertyDataDefinition(final String constraint) {
+ final RequirementSubstitutionFilterPropertyDataDefinition requirementSubstitutionFilterPropertyDataDefinition = new RequirementSubstitutionFilterPropertyDataDefinition();
requirementSubstitutionFilterPropertyDataDefinition.setConstraints(Arrays.asList(constraint));
return requirementSubstitutionFilterPropertyDataDefinition;
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java
index 20e796e1fa..645eb96253 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,9 +19,18 @@
* Modifications copyright (c) 2019 Nokia
* ================================================================================
*/
-
package org.openecomp.sdc.be.components.impl;
+import java.security.SecureRandom;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
@@ -34,26 +43,14 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import java.security.SecureRandom;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.Set;
-import java.util.stream.Collectors;
-
/**
* This class holds the logic of arranging resource instance on the canvas for imported VF
- *
- * @author mshitrit
*
+ * @author mshitrit
*/
@Component("compositionBusinessLogic")
public class CompositionBusinessLogic {
- private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
+
private static final Logger log = Logger.getLogger(CompositionBusinessLogic.class.getName());
private static final int VFC_CANVAS_ELEMENT_SIZE = 50;
private static final int CP_CANVAS_ELEMENT_SIZE = 21;
@@ -61,48 +58,48 @@ public class CompositionBusinessLogic {
private static final int CANVAS_HEIGHT = 700;
private static final int SPACE_BETWEEN_ELEMENTS = VFC_CANVAS_ELEMENT_SIZE * 4;
private static final double CP_RADIUS_FACTOR = 0.4;
+ private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
@Autowired
public CompositionBusinessLogic(ComponentInstanceBusinessLogic componentInstanceBusinessLogic) {
this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
}
- enum RelativePosition {
- LEFT, RIGHT, UP, DOWN
- };
-
protected void setPositionsForComponentInstances(Resource resource, String userId) {
- boolean isNotAllPositionsCalculated = resource.getComponentInstances() == null
- || resource.getComponentInstances().stream().anyMatch(p -> (p.getPosX() == null || p.getPosX().isEmpty()) || (p.getPosY() == null || p.getPosY().isEmpty()));
- if (isNotAllPositionsCalculated && resource.getComponentInstances() != null) {
+ boolean isNotAllPositionsCalculated = resource.getComponentInstances() == null || resource.getComponentInstances().stream()
+ .anyMatch(p -> (p.getPosX() == null || p.getPosX().isEmpty()) || (p.getPosY() == null || p.getPosY().isEmpty()));
+ if (isNotAllPositionsCalculated && resource.getComponentInstances() != null) {
// Arrange Icons In Spiral Pattern
- Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations = buildSpiralPatternPositioningForComponentInstances(resource);
+ Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations = buildSpiralPatternPositioningForComponentInstances(
+ resource);
// Set Relative Locations According to Canvas Size
componentInstanceLocations.entrySet().forEach(this::setRelativePosition);
// Update in DB
- componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME,resource, resource.getUniqueId(),
- userId, resource.getComponentInstances(), false);
+ componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME, resource, resource.getUniqueId(), userId,
+ resource.getComponentInstances(), false);
}
}
-
+
+ ;
+
protected void setPositionsForComponentInstances(Service service, String userId) {
- boolean isNotAllPositionsCalculated = service.getComponentInstances() == null
- || service.getComponentInstances().stream().anyMatch(p -> (p.getPosX() == null || p.getPosX().isEmpty()) || (p.getPosY() == null || p.getPosY().isEmpty()));
- if (isNotAllPositionsCalculated && service.getComponentInstances() != null) {
+ boolean isNotAllPositionsCalculated = service.getComponentInstances() == null || service.getComponentInstances().stream()
+ .anyMatch(p -> (p.getPosX() == null || p.getPosX().isEmpty()) || (p.getPosY() == null || p.getPosY().isEmpty()));
+ if (isNotAllPositionsCalculated && service.getComponentInstances() != null) {
// Arrange Icons In Spiral Pattern
- Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations = buildSpiralPatternPositioningForComponentInstances(service);
+ Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations = buildSpiralPatternPositioningForComponentInstances(
+ service);
// Set Relative Locations According to Canvas Size
componentInstanceLocations.entrySet().forEach(this::setRelativePosition);
// Update in DB
- componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, service, service.getUniqueId(),
- userId, service.getComponentInstances(), false);
+ componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, service, service.getUniqueId(), userId,
+ service.getComponentInstances(), false);
}
}
private void setRelativePosition(Entry<ImmutablePair<Double, Double>, ComponentInstance> entry) {
int xCenter = CANVAS_WIDTH / 2;
int yCenter = CANVAS_HEIGHT / 2;
-
ImmutablePair<Double, Double> matrixPosition = entry.getKey();
ComponentInstance componentInstance = entry.getValue();
componentInstance.setPosX(calculateCompositionPosition(xCenter, matrixPosition.getLeft(), componentInstance));
@@ -113,67 +110,59 @@ public class CompositionBusinessLogic {
final double topLeftCanvasPosition = center + relativePosition * CompositionBusinessLogic.SPACE_BETWEEN_ELEMENTS;
double offsetedCanvasPosition;
switch (componentInstance.getOriginType()) {
- case CP:
- offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2.0;
- break;
- case VL:
- offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2.0;
- break;
- case VF:
- offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0;
- break;
- case VFC:
- offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0;
- break;
- case VFCMT:
- offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0;
- break;
- default:
- offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0;
- break;
+ case CP:
+ offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2.0;
+ break;
+ case VL:
+ offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2.0;
+ break;
+ case VF:
+ offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0;
+ break;
+ case VFC:
+ offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0;
+ break;
+ case VFCMT:
+ offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0;
+ break;
+ default:
+ offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0;
+ break;
}
return String.valueOf(offsetedCanvasPosition);
}
protected Map<ImmutablePair<Double, Double>, ComponentInstance> buildSpiralPatternPositioningForComponentInstances(
- org.openecomp.sdc.be.model.Component component) {
-
+ org.openecomp.sdc.be.model.Component component) {
Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations = new HashMap<>();
-
List<ComponentInstance> componentInstances = new ArrayList<>();
- if (component instanceof Resource){
+ if (component instanceof Resource) {
Resource resource = (Resource) component;
List<ComponentInstance> componentInstanceList = resource.getComponentInstances();
componentInstances.addAll(componentInstanceList);
- }else if (component instanceof Service){
+ } else if (component instanceof Service) {
Service service = (Service) component;
List<ComponentInstance> componentInstanceList = service.getComponentInstances();
componentInstances.addAll(componentInstanceList);
}
-
Map<ComponentInstance, List<ComponentInstance>> connectededCps = getCpsConnectedToVFC(componentInstances, component);
// Remove all cp that are connected from the list
componentInstances.removeAll(connectededCps.values().stream().flatMap(Collection::stream).collect(Collectors.toList()));
-
buildSpiralPatternForMajorComponents(componentInstanceLocations, componentInstances);
buildCirclePatternForCps(componentInstanceLocations, connectededCps);
-
return componentInstanceLocations;
}
- protected void buildCirclePatternForCps(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations, Map<ComponentInstance, List<ComponentInstance>> connectedCps) {
-
+ protected void buildCirclePatternForCps(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations,
+ Map<ComponentInstance, List<ComponentInstance>> connectedCps) {
for (Entry<ComponentInstance, List<ComponentInstance>> vfcCpList : connectedCps.entrySet()) {
- componentInstLocations.entrySet().stream()
- .filter(p -> p.getValue().getUniqueId().equals(vfcCpList.getKey().getUniqueId()))
- .findAny()
- .ifPresent(vfcOfTheCps ->
- buildCirclePatternForOneGroupOfCps(vfcOfTheCps.getKey(), vfcCpList.getValue(),
- componentInstLocations));
+ componentInstLocations.entrySet().stream().filter(p -> p.getValue().getUniqueId().equals(vfcCpList.getKey().getUniqueId())).findAny()
+ .ifPresent(vfcOfTheCps -> buildCirclePatternForOneGroupOfCps(vfcOfTheCps.getKey(), vfcCpList.getValue(), componentInstLocations));
}
}
- private void buildCirclePatternForOneGroupOfCps(ImmutablePair<Double, Double> vfcLocation, List<ComponentInstance> cpsGroup, Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations) {
+ private void buildCirclePatternForOneGroupOfCps(ImmutablePair<Double, Double> vfcLocation, List<ComponentInstance> cpsGroup,
+ Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations) {
final int numberOfCps = cpsGroup.size();
double angleBetweenCps = (!cpsGroup.isEmpty()) ? Math.toRadians(360) / numberOfCps : 0;
double currentAngle = 0;
@@ -185,10 +174,10 @@ public class CompositionBusinessLogic {
componentInstLocations.put(new ImmutablePair<>(cpXposition, cpYposition), currCp);
currentAngle += angleBetweenCps;
}
-
}
- private void buildSpiralPatternForMajorComponents(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations, List<ComponentInstance> componentInstances) {
+ private void buildSpiralPatternForMajorComponents(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations,
+ List<ComponentInstance> componentInstances) {
int elementsCounter = 0;
ImmutablePair<Double, Double> currPlacement;
ImmutablePair<Double, Double> prevPlacement = null;
@@ -203,30 +192,29 @@ public class CompositionBusinessLogic {
} else {
relationToPrevElement = getRelativePositionForCurrentElement(componentInstanceLocations, relationToPrevElement, prevPlacement);
currPlacement = getRelativeElementLocation(prevPlacement, relationToPrevElement);
-
}
-
componentInstanceLocations.put(currPlacement, curr);
prevPlacement = currPlacement;
}
}
- protected Map<ComponentInstance, List<ComponentInstance>> getCpsConnectedToVFC(List<ComponentInstance> allComponentInstances, org.openecomp.sdc.be.model.Component component) {
+ protected Map<ComponentInstance, List<ComponentInstance>> getCpsConnectedToVFC(List<ComponentInstance> allComponentInstances,
+ org.openecomp.sdc.be.model.Component component) {
Map<ComponentInstance, List<ComponentInstance>> vfcWithItsCps = new HashMap<>();
List<RequirementCapabilityRelDef> allRelations = new ArrayList<>();
- if (component instanceof Resource){
+ if (component instanceof Resource) {
Resource vf = (Resource) component;
allRelations = vf.getComponentInstancesRelations();
- }else if (component instanceof Service){
+ } else if (component instanceof Service) {
Service sv = (Service) component;
allRelations = sv.getComponentInstancesRelations();
}
-
for (ComponentInstance curr : allComponentInstances) {
// Filters Only CPs
if (curr.getOriginType() == OriginTypeEnum.CP) {
// List Of elements the CP is connected to
- List<RequirementCapabilityRelDef> connectedToList = allRelations.stream().filter(p -> p.getFromNode().equals(curr.getUniqueId()) || p.getToNode().equals(curr.getUniqueId())).collect(Collectors.toList());
+ List<RequirementCapabilityRelDef> connectedToList = allRelations.stream()
+ .filter(p -> p.getFromNode().equals(curr.getUniqueId()) || p.getToNode().equals(curr.getUniqueId())).collect(Collectors.toList());
// Adds Only CPs Which are connected to VFC
filterCpConnectedToVFC(allComponentInstances, vfcWithItsCps, curr, connectedToList);
}
@@ -234,18 +222,19 @@ public class CompositionBusinessLogic {
return vfcWithItsCps;
}
- private void filterCpConnectedToVFC(List<ComponentInstance> allComponentInstances, Map<ComponentInstance, List<ComponentInstance>> vfcWithItsCps, ComponentInstance currCP, List<RequirementCapabilityRelDef> connectedToTheCPList) {
+ private void filterCpConnectedToVFC(List<ComponentInstance> allComponentInstances, Map<ComponentInstance, List<ComponentInstance>> vfcWithItsCps,
+ ComponentInstance currCP, List<RequirementCapabilityRelDef> connectedToTheCPList) {
if (!connectedToTheCPList.isEmpty()) {
// Set Of Ids Of components Instances which are connected certain CP
- Set<String> mateIds = connectedToTheCPList.stream().map(cpRelation -> cpRelation.getFromNode().equals(currCP.getUniqueId()) ? cpRelation.getToNode() : cpRelation.getFromNode()).collect(Collectors.toSet());
-
+ Set<String> mateIds = connectedToTheCPList.stream()
+ .map(cpRelation -> cpRelation.getFromNode().equals(currCP.getUniqueId()) ? cpRelation.getToNode() : cpRelation.getFromNode())
+ .collect(Collectors.toSet());
// Vfc Component instance Connected to the CP
Optional<ComponentInstance> optionalVfcConnectedToCP = allComponentInstances.stream().
- // All instances connected to CP
+ // All instances connected to CP
filter(p -> mateIds.contains(p.getUniqueId())).
- // Filter in only VFC connected to the CP
+ // Filter in only VFC connected to the CP
filter(p -> p.getOriginType() == OriginTypeEnum.VFC).findAny();
-
if (optionalVfcConnectedToCP.isPresent()) {
final ComponentInstance vfcWithCps = optionalVfcConnectedToCP.get();
if (vfcWithItsCps.containsKey(vfcWithCps)) {
@@ -259,37 +248,39 @@ public class CompositionBusinessLogic {
}
}
- private RelativePosition getRelativePositionForCurrentElement(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations, RelativePosition relationToPrevElement, ImmutablePair<Double, Double> prevPlacement) {
+ private RelativePosition getRelativePositionForCurrentElement(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations,
+ RelativePosition relationToPrevElement,
+ ImmutablePair<Double, Double> prevPlacement) {
switch (relationToPrevElement) {
- case LEFT: {
- boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.UP, componentInstanceLocations);
- relationToPrevElement = isOccupied ? RelativePosition.LEFT : RelativePosition.UP;
- break;
- }
- case RIGHT: {
- boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.DOWN, componentInstanceLocations);
- relationToPrevElement = isOccupied ? RelativePosition.RIGHT : RelativePosition.DOWN;
- break;
- }
- case UP: {
- boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.RIGHT, componentInstanceLocations);
- relationToPrevElement = isOccupied ? RelativePosition.UP : RelativePosition.RIGHT;
- break;
- }
- case DOWN: {
- boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.LEFT, componentInstanceLocations);
- relationToPrevElement = isOccupied ? RelativePosition.DOWN : RelativePosition.LEFT;
- break;
- }
- default: {
- throw new UnsupportedOperationException();
- }
+ case LEFT: {
+ boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.UP, componentInstanceLocations);
+ relationToPrevElement = isOccupied ? RelativePosition.LEFT : RelativePosition.UP;
+ break;
+ }
+ case RIGHT: {
+ boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.DOWN, componentInstanceLocations);
+ relationToPrevElement = isOccupied ? RelativePosition.RIGHT : RelativePosition.DOWN;
+ break;
+ }
+ case UP: {
+ boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.RIGHT, componentInstanceLocations);
+ relationToPrevElement = isOccupied ? RelativePosition.UP : RelativePosition.RIGHT;
+ break;
+ }
+ case DOWN: {
+ boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.LEFT, componentInstanceLocations);
+ relationToPrevElement = isOccupied ? RelativePosition.DOWN : RelativePosition.LEFT;
+ break;
+ }
+ default: {
+ throw new UnsupportedOperationException();
+ }
}
return relationToPrevElement;
}
- private boolean isAdjacentElementOccupied(ImmutablePair<Double, Double> currElement, RelativePosition adjacentElementRelationToCurrElement, Map<ImmutablePair<Double, Double>, ComponentInstance> allElements) {
-
+ private boolean isAdjacentElementOccupied(ImmutablePair<Double, Double> currElement, RelativePosition adjacentElementRelationToCurrElement,
+ Map<ImmutablePair<Double, Double>, ComponentInstance> allElements) {
ImmutablePair<Double, Double> adjacentElementPosition = getRelativeElementLocation(currElement, adjacentElementRelationToCurrElement);
return allElements.containsKey(adjacentElementPosition);
}
@@ -297,42 +288,42 @@ public class CompositionBusinessLogic {
private ImmutablePair<Double, Double> getRelativeElementLocation(ImmutablePair<Double, Double> currElement, RelativePosition relativeLocation) {
ImmutablePair<Double, Double> relativeElementPosition;
switch (relativeLocation) {
-
- case LEFT: {
- relativeElementPosition = new ImmutablePair<>(currElement.getLeft() - 1, currElement.getRight());
- break;
- }
- case RIGHT: {
- relativeElementPosition = new ImmutablePair<>(currElement.getLeft() + 1, currElement.getRight());
- break;
- }
- case UP: {
- relativeElementPosition = new ImmutablePair<>(currElement.getLeft(), currElement.getRight() + 1);
- break;
- }
- case DOWN: {
- relativeElementPosition = new ImmutablePair<>(currElement.getLeft(), currElement.getRight() - 1);
- break;
- }
- default: {
- throw new UnsupportedOperationException();
- }
+ case LEFT: {
+ relativeElementPosition = new ImmutablePair<>(currElement.getLeft() - 1, currElement.getRight());
+ break;
+ }
+ case RIGHT: {
+ relativeElementPosition = new ImmutablePair<>(currElement.getLeft() + 1, currElement.getRight());
+ break;
+ }
+ case UP: {
+ relativeElementPosition = new ImmutablePair<>(currElement.getLeft(), currElement.getRight() + 1);
+ break;
+ }
+ case DOWN: {
+ relativeElementPosition = new ImmutablePair<>(currElement.getLeft(), currElement.getRight() - 1);
+ break;
+ }
+ default: {
+ throw new UnsupportedOperationException();
+ }
}
return relativeElementPosition;
}
+
protected void validateAndSetDefaultCoordinates(ComponentInstance resourceInstance) {
- int xCenter = CANVAS_WIDTH / 2;
+ int xCenter = CANVAS_WIDTH / 2;
int yCenter = CANVAS_HEIGHT / 2;
double leftLimit = -10D;
double rightLimit = -1D;
double generatedDouble = leftLimit + new SecureRandom().nextDouble() * (rightLimit - leftLimit);
-
- if (StringUtils.isEmpty(resourceInstance.getPosX())|| StringUtils.isEmpty(resourceInstance.getPosY())){
+ if (StringUtils.isEmpty(resourceInstance.getPosX()) || StringUtils.isEmpty(resourceInstance.getPosY())) {
resourceInstance.setPosX(calculateCompositionPosition(xCenter, generatedDouble, resourceInstance));
resourceInstance.setPosY(calculateCompositionPosition(yCenter, generatedDouble, resourceInstance));
- log.debug("Missing Failed PosX/PosY values. new values generated automatically. PosX = {} and PosY = {}", resourceInstance.getPosX(), resourceInstance.getPosY());
+ log.debug("Missing Failed PosX/PosY values. new values generated automatically. PosX = {} and PosY = {}", resourceInstance.getPosX(),
+ resourceInstance.getPosY());
}
}
-
+ enum RelativePosition {LEFT, RIGHT, UP, DOWN}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java
index 8b4c1c3e8b..4db24c1a25 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java
@@ -17,10 +17,10 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
+import java.util.Date;
import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -45,8 +45,6 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import java.util.Date;
-
@Component("ConsumerBusinessLogic")
public class ConsumerBusinessLogic extends BaseBusinessLogic {
@@ -54,35 +52,26 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
private static final String CONSUMER_SALT = "Consumer salt";
private static final String CONSUMER_PW = "Consumer password";
private static final String AUDIT_BEFORE_SENDING_RESPONSE = "audit before sending response";
-
+ private static final Logger log = Logger.getLogger(ConsumerBusinessLogic.class.getName());
@javax.annotation.Resource
private ConsumerOperation consumerOperation;
- private static final Logger log = Logger.getLogger(ConsumerBusinessLogic.class.getName());
-
@Autowired
- public ConsumerBusinessLogic(IElementOperation elementDao,
- IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation,
- IGroupTypeOperation groupTypeOperation,
- InterfaceOperation interfaceOperation,
- InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
- ArtifactsOperations artifactToscaOperation) {
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
- interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+ public ConsumerBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+ IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
+ InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+ artifactToscaOperation);
}
public Either<ConsumerDefinition, ResponseFormat> createConsumer(User user, ConsumerDefinition consumer) {
-
Either<User, ResponseFormat> userValidation = validateUser(user, consumer, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS);
-
if (userValidation.isRight()) {
return Either.right(userValidation.right().value());
}
checkFieldsForOverrideAttempt(consumer);
user = userValidation.left().value();
consumer.setLastModfierAtuid(user.getUserId());
-
Either<ConsumerDefinition, ResponseFormat> consumerValidationResponse = validateConsumer(consumer);
if (consumerValidationResponse.isRight()) {
ResponseFormat responseFormat = consumerValidationResponse.right().value();
@@ -95,7 +84,6 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
BeEcompErrorManager.getInstance().logBeFailedLockObjectError("createConsumer", NodeTypeEnum.ConsumerCredentials.getName(), consumerName);
log.debug("Failed to lock consumer: {} error - {}", consumerName, lockResult);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
-
componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
return Either.right(responseFormat);
}
@@ -104,15 +92,13 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
if (getResponse.isLeft() && getResponse.left().value() != null) {
return updateConsumer(consumer);
}
-
Date date = new Date();
consumer.setConsumerDetailsLastupdatedtime(date.getTime());
consumer.setConsumerLastAuthenticationTime(Long.valueOf(0));
-
Either<ConsumerData, StorageOperationStatus> createResponse = consumerOperation.createCredentials(new ConsumerData(consumer));
-
if (createResponse.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(createResponse.right().value()));
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(createResponse.right().value()));
componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
return Either.right(responseFormat);
}
@@ -127,7 +113,6 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
}
private Either<User, ResponseFormat> validateUser(User user, ConsumerDefinition consumer, AuditingActionEnum auditAction) {
-
if (user.getUserId() == null || user.getUserId().trim().isEmpty()) {
log.debug("createEcompUser method - user is missing. userId= {}", user.getUserId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
@@ -139,14 +124,13 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
User userFromDB;
try {
userFromDB = userAdmin.getUser(user.getUserId(), false);
- }catch (ByActionStatusComponentException e){
+ } catch (ByActionStatusComponentException e) {
log.debug("createEcompUser method - user is not listed. userId= {}", user.getUserId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS);
log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user);
return Either.right(responseFormat);
}
-
user = userFromDB;
// validate user role
log.debug("validate user role");
@@ -175,7 +159,6 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
return Either.right(validateEcompUserSalt.right().value());
}
return Either.left(consumer);
-
}
private Either<ConsumerDefinition, ResponseFormat> validateConsumerName(ConsumerDefinition consumer) {
@@ -190,13 +173,13 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
}
if (!ValidationUtils.validateLength(name, ValidationUtils.CONSUMER_NAME_MAX_LENGTH)) {
log.debug("Consumer name exceeds limit.");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, CONSUMER_NAME, String.valueOf(ValidationUtils.CONSUMER_NAME_MAX_LENGTH)));
+ return Either.right(componentsUtils
+ .getResponseFormat(ActionStatus.EXCEEDS_LIMIT, CONSUMER_NAME, String.valueOf(ValidationUtils.CONSUMER_NAME_MAX_LENGTH)));
}
if (!ValidationUtils.isUTF8Str(name)) {
log.debug("Consumer name includes non UTF 8 characters.");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_NAME));
}
-
return Either.left(consumer);
}
@@ -215,7 +198,6 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
log.debug("Consumer password is invalid.");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_PW));
}
-
return Either.left(consumer);
}
@@ -233,7 +215,6 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
log.debug("Consumer salt is invalid.");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_SALT));
}
-
return Either.left(consumer);
}
@@ -299,7 +280,8 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
public Either<ConsumerDefinition, ResponseFormat> updateConsumer(ConsumerDefinition consumer) {
Either<ConsumerData, StorageOperationStatus> updateResult = consumerOperation.updateCredentials(new ConsumerData(consumer));
if (updateResult.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(updateResult.right().value()));
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(updateResult.right().value()));
return Either.right(responseFormat);
}
consumer = new ConsumerDefinition(updateResult.left().value().getConsumerDataDefinition());
@@ -317,5 +299,4 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
log.info("Consumer Last Modifier USER_ID cannot be defined by user. This field will be overridden by the application");
}
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java
index 1757fcdf01..fad72ccd14 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java
@@ -17,20 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.tosca.CsarUtils;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.common.util.GeneralUtility;
-import org.openecomp.sdc.exception.ResponseFormat;
-
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringReader;
@@ -43,11 +32,19 @@ import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.tosca.CsarUtils;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.openecomp.sdc.common.util.GeneralUtility;
+import org.openecomp.sdc.exception.ResponseFormat;
public class CsarValidationUtils {
private static final Logger log = Logger.getLogger(CsarValidationUtils.class.getName());
-
private static final String TOSCA_META_FILE_VERSION = "TOSCA-Meta-File-Version";
private static final String CSAR_VERSION = "CSAR-Version";
private static final String CREATED_BY = "Created-By";
@@ -56,11 +53,10 @@ public class CsarValidationUtils {
private static final String TOSCA_FILE = "TOSCA.meta";
private static final String DEL_PATTERN = "([/\\\\]+)";
private static final String TOSCA_METADATA_PATH_PATTERN = TOSCA_METADATA +
- // Artifact Group (i.e Deployment/Informational)
- DEL_PATTERN + TOSCA_FILE;
-
+ // Artifact Group (i.e Deployment/Informational)
+ DEL_PATTERN + TOSCA_FILE;
private static final String TOSCA_META_ENTRY_DEFINITIONS = "Entry-Definitions";
- private static final String[] TOSCA_METADATA_FIELDS = { TOSCA_META_FILE_VERSION, CSAR_VERSION, CREATED_BY, TOSCA_META_ENTRY_DEFINITIONS };
+ private static final String[] TOSCA_METADATA_FIELDS = {TOSCA_META_FILE_VERSION, CSAR_VERSION, CREATED_BY, TOSCA_META_ENTRY_DEFINITIONS};
private static final String ARTIFACTS_METADATA_FILE = "HEAT.meta";
private static final String TOSCA_CSAR_EXTENSION = ".csar";
private static final String TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID = "TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}";
@@ -74,6 +70,7 @@ public class CsarValidationUtils {
/**
* Validates Csar
+ *
* @param csar
* @param csarUUID
* @param componentsUtils
@@ -84,9 +81,7 @@ public class CsarValidationUtils {
if (validateStatus.isRight()) {
return Either.right(validateStatus.right().value());
}
-
removeNonUniqueArtifactsFromCsar(csar);
-
log.trace("TOSCA-Metadata/TOSCA.meta file found, CSAR id {}", csarUUID);
validateStatus = validateTOSCAMetadataFile(csar, csarUUID, componentsUtils);
if (validateStatus.isRight()) {
@@ -96,26 +91,25 @@ public class CsarValidationUtils {
}
private static void removeNonUniqueArtifactsFromCsar(Map<String, byte[]> csar) {
-
List<String> nonUniqueArtifactsToRemove = new ArrayList<>();
String[] paths = csar.keySet().toArray(new String[csar.keySet().size()]);
int numberOfArtifacts = paths.length;
- for(int i = 0; i < numberOfArtifacts; ++i ){
+ for (int i = 0; i < numberOfArtifacts; ++i) {
collectNonUniqueArtifact(paths, i, numberOfArtifacts, nonUniqueArtifactsToRemove);
}
nonUniqueArtifactsToRemove.stream().forEach(csar::remove);
}
- private static void collectNonUniqueArtifact( String[] paths, int currInd, int numberOfArtifacts, List<String> nonUniqueArtifactsToRemove) {
-
+ private static void collectNonUniqueArtifact(String[] paths, int currInd, int numberOfArtifacts, List<String> nonUniqueArtifactsToRemove) {
String[] parsedPath = paths[currInd].split("/");
String[] otherParsedPath;
int artifactNameInd = parsedPath.length - 1;
- for(int j = currInd + 1; j < numberOfArtifacts; ++j ){
+ for (int j = currInd + 1; j < numberOfArtifacts; ++j) {
otherParsedPath = paths[j].split("/");
- if(parsedPath.length == otherParsedPath.length && parsedPath.length > 3 && isEqualArtifactNames(parsedPath, otherParsedPath)){
- log.error("Can't upload two artifact with the same name {}. The artifact with path {} will be handled, and the artifact with path {} will be ignored. ",
- parsedPath[artifactNameInd], paths[currInd], paths[j]);
+ if (parsedPath.length == otherParsedPath.length && parsedPath.length > 3 && isEqualArtifactNames(parsedPath, otherParsedPath)) {
+ log.error(
+ "Can't upload two artifact with the same name {}. The artifact with path {} will be handled, and the artifact with path {} will be ignored. ",
+ parsedPath[artifactNameInd], paths[currInd], paths[j]);
nonUniqueArtifactsToRemove.add(paths[j]);
}
}
@@ -130,158 +124,175 @@ public class CsarValidationUtils {
String otherGroupType = otherParsedPath[artifactGroupTypeInd];
String otherArtifactName = otherParsedPath[artifactNameInd];
String vfcToscaName = parsedPath.length == 5 ? parsedPath[1] : null;
-
- if(artifactName.equalsIgnoreCase(otherArtifactName) && groupType.equalsIgnoreCase(otherGroupType)){
+ if (artifactName.equalsIgnoreCase(otherArtifactName) && groupType.equalsIgnoreCase(otherGroupType)) {
isEqualArtifactNames = vfcToscaName == null || vfcToscaName.equalsIgnoreCase(otherParsedPath[1]);
}
return isEqualArtifactNames;
}
- public static Either<ImmutablePair<String, String>, ResponseFormat> getToscaYaml(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
+ public static Either<ImmutablePair<String, String>, ResponseFormat> getToscaYaml(Map<String, byte[]> csar, String csarUUID,
+ ComponentsUtils componentsUtils) {
Either<Boolean, ResponseFormat> validateStatus = validateIsTOSCAMetadataExist(csar, csarUUID, componentsUtils);
if (validateStatus.isRight()) {
return Either.right(validateStatus.right().value());
}
Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN);
Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny();
- if(!keyOp.isPresent()){
+ if (!keyOp.isPresent()) {
log.debug(TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID, csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID,
+ CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
}
byte[] toscaMetaBytes = csar.get(keyOp.get());
Properties props = new Properties();
try {
String propStr = new String(toscaMetaBytes);
- props.load(new StringReader(propStr.replace("\\","\\\\")));
+ props.load(new StringReader(propStr.replace("\\", "\\\\")));
} catch (IOException e) {
log.debug(TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID, csarUUID, e);
- BeEcompErrorManager.getInstance().logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID,
+ CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
}
-
String yamlFileName = props.getProperty(TOSCA_META_ENTRY_DEFINITIONS);
String[] ops = yamlFileName.split(DEL_PATTERN);
List<String> list = Arrays.asList(ops);
String result = list.stream().map(x -> x).collect(Collectors.joining(DEL_PATTERN));
keyOp = csar.keySet().stream().filter(k -> Pattern.compile(result).matcher(k).matches()).findAny();
- if(!keyOp.isPresent()){
+ if (!keyOp.isPresent()) {
log.debug(ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_ID, csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError(ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_ID + csarUUID,
+ CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, yamlFileName));
}
-
log.trace("Found Entry-Definitions property in TOSCA-Metadata/TOSCA.meta, Entry-Definitions: {}, CSAR id: {}", yamlFileName, csarUUID);
byte[] yamlFileBytes = csar.get(yamlFileName);
if (yamlFileBytes == null) {
log.debug("Entry-Definitions {} file not found in csar, csar ID {}", yamlFileName, csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError(ENTRY_DEFINITIONS + yamlFileName + FILE_NOT_FOUND_IN_CSAR_WITH_ID + csarUUID, CSAR_STRUCTURE_IS_INVALID, ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(ENTRY_DEFINITIONS + yamlFileName + FILE_NOT_FOUND_IN_CSAR_WITH_ID + csarUUID, CSAR_STRUCTURE_IS_INVALID,
+ ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, yamlFileName));
}
-
String yamlFileContents = new String(yamlFileBytes);
-
return Either.left(new ImmutablePair<>(yamlFileName, yamlFileContents));
}
- public static Either<ImmutablePair<String, String>, ResponseFormat> getArtifactsMeta(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
-
- if( !csar.containsKey(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE) ) {
+ public static Either<ImmutablePair<String, String>, ResponseFormat> getArtifactsMeta(Map<String, byte[]> csar, String csarUUID,
+ ComponentsUtils componentsUtils) {
+ if (!csar.containsKey(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE)) {
log.debug(ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_ID, csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError(ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_ID + csarUUID,
+ CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, ARTIFACTS_METADATA_FILE));
}
-
- log.trace("Found Entry-Definitions property in TOSCA-Metadata/TOSCA.meta, Entry-Definitions: {}, CSAR id: {}", ARTIFACTS_METADATA_FILE, csarUUID);
+ log.trace("Found Entry-Definitions property in TOSCA-Metadata/TOSCA.meta, Entry-Definitions: {}, CSAR id: {}", ARTIFACTS_METADATA_FILE,
+ csarUUID);
byte[] artifactsMetaBytes = csar.get(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE);
if (artifactsMetaBytes == null) {
log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, ARTIFACTS_METADATA_FILE, csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError(ENTRY_DEFINITIONS + CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE + FILE_NOT_FOUND_IN_CSAR_WITH_ID + csarUUID, CSAR_STRUCTURE_IS_INVALID, ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE));
+ BeEcompErrorManager.getInstance().logInternalDataError(
+ ENTRY_DEFINITIONS + CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE + FILE_NOT_FOUND_IN_CSAR_WITH_ID + csarUUID,
+ CSAR_STRUCTURE_IS_INVALID, ErrorSeverity.ERROR);
+ return Either.right(
+ componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE));
}
-
String artifactsFileContents = new String(artifactsMetaBytes);
-
return Either.left(new ImmutablePair<>(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE, artifactsFileContents));
}
- public static Either<ImmutablePair<String, byte[]>, ResponseFormat> getArtifactContent(String csarUUID, Map<String, byte[]> csar, String artifactPath, String artifactName, ComponentsUtils componentsUtils) {
+ public static Either<ImmutablePair<String, byte[]>, ResponseFormat> getArtifactContent(String csarUUID, Map<String, byte[]> csar,
+ String artifactPath, String artifactName,
+ ComponentsUtils componentsUtils) {
if (!csar.containsKey(artifactPath)) {
log.debug("Entry-Definitions entry not found in Artifacts/HEAT.meta file, csar ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError(ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, CsarUtils.ARTIFACTS_PATH + artifactName, csarUUID));
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_ID + csarUUID,
+ CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+ return Either
+ .right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, CsarUtils.ARTIFACTS_PATH + artifactName, csarUUID));
}
-
log.trace("Found Entry-Definitions property in Artifacts/HEAT.meta, Entry-Definitions: {}, CSAR id: {}", artifactPath, csarUUID);
byte[] artifactFileBytes = csar.get(artifactPath);
if (artifactFileBytes == null) {
log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, artifactName, csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError(ENTRY_DEFINITIONS + artifactPath + FILE_NOT_FOUND_IN_CSAR_WITH_ID + csarUUID, CSAR_STRUCTURE_IS_INVALID, ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(ENTRY_DEFINITIONS + artifactPath + FILE_NOT_FOUND_IN_CSAR_WITH_ID + csarUUID, CSAR_STRUCTURE_IS_INVALID,
+ ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, artifactPath, csarUUID));
}
-
return Either.left(new ImmutablePair<>(artifactName, artifactFileBytes));
}
- private static Either<Boolean, ResponseFormat> validateTOSCAMetadataFile(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
-
+ private static Either<Boolean, ResponseFormat> validateTOSCAMetadataFile(Map<String, byte[]> csar, String csarUUID,
+ ComponentsUtils componentsUtils) {
Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN);
Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny();
- if(!keyOp.isPresent()){
+ if (!keyOp.isPresent()) {
log.debug(TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID, csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID,
+ CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
}
-
byte[] toscaMetaBytes = csar.get(keyOp.get());
String toscaMetadata = new String(toscaMetaBytes);
String[] splited = toscaMetadata.split(NEW_LINE_DELM);
if (splited == null || splited.length < TOSCA_METADATA_FIELDS.length) {
log.debug(TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID, csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID,
+ CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
}
-
Either<Boolean, ResponseFormat> blockStatus = validateBlock(csarUUID, splited, componentsUtils);
if (blockStatus.isRight()) {
return Either.right(blockStatus.right().value());
}
-
return Either.left(true);
-
}
private static Either<Boolean, ResponseFormat> validateBlock(String csarUUID, String[] splited, ComponentsUtils componentsUtils) {
int index = 0;
for (String toscaField : TOSCA_METADATA_FIELDS) {
-
Properties props = new Properties();
-
try {
props.load(new ByteArrayInputStream(splited[index].getBytes()));
} catch (IOException e) {
log.debug(TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID, csarUUID, e);
- BeEcompErrorManager.getInstance().logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID,
+ CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
}
if (!props.containsKey(toscaField)) {
log.debug("TOSCA.meta file format is invalid: No new line after block_0 as expected in csar, csar ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID,
+ CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
}
String value = props.getProperty(toscaField);
if (value == null || value.isEmpty()) {
log.debug(TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID, csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID,
+ CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
}
-
// TOSCA-Meta-File-Version & CSAR-Version : digit.digit - format
+
// validation
if ((toscaField.equals(TOSCA_META_FILE_VERSION) || toscaField.equals(CSAR_VERSION)) && !validateTOSCAMetaProperty(value)) {
log.debug("TOSCA-Metadata/TOSCA.meta file contains {} in wrong format (digit.digit), csar ID {}", toscaField, csarUUID);
BeEcompErrorManager.getInstance()
- .logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+ .logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID,
+ CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
}
index++;
@@ -294,48 +305,45 @@ public class CsarValidationUtils {
return floatMatcher.matches();
}
- private static Either<Boolean, ResponseFormat> validateIsTOSCAMetadataExist(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
+ private static Either<Boolean, ResponseFormat> validateIsTOSCAMetadataExist(Map<String, byte[]> csar, String csarUUID,
+ ComponentsUtils componentsUtils) {
if (csar == null || csar.isEmpty()) {
log.debug("Error when fetching csar with ID {}", csarUUID);
BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID);
return Either.right(responseFormat);
}
-
Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN);
Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny();
- if(!keyOp.isPresent()){
-
+ if (!keyOp.isPresent()) {
log.debug("TOSCA-Metadata/TOSCA.meta file not found in csar, csar ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, CSAR_STRUCTURE_IS_INVALID, ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, CSAR_STRUCTURE_IS_INVALID,
+ ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID));
}
byte[] toscaMetaBytes = csar.get(keyOp.get());
-
if (toscaMetaBytes == null || toscaMetaBytes.length == 0) {
log.debug("TOSCA-Metadata/TOSCA.meta file not found in csar, csar ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, CSAR_STRUCTURE_IS_INVALID, ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, CSAR_STRUCTURE_IS_INVALID,
+ ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID));
}
-
return Either.left(Boolean.TRUE);
}
public static Either<String, ResponseFormat> getToscaYamlChecksum(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
-
Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlRes = getToscaYaml(csar, csarUUID, componentsUtils);
if (toscaYamlRes.isRight() || toscaYamlRes.left().value() == null || toscaYamlRes.left().value().getRight() == null) {
log.debug("Faild to create toscaYamlChecksum for csar, csar ID {}", csarUUID);
return Either.right(toscaYamlRes.right().value());
}
-
String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(toscaYamlRes.left().value().getRight().getBytes());
return Either.left(newCheckSum);
-
}
public static boolean isCsarPayloadName(String payloadName) {
return payloadName != null && payloadName.toLowerCase().endsWith(TOSCA_CSAR_EXTENSION);
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeBusinessLogic.java
index 5af7cf660b..401222861b 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeBusinessLogic.java
@@ -17,10 +17,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentParametersView;
import org.openecomp.sdc.be.model.DataTypeDefinition;
@@ -35,23 +37,15 @@ import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Optional;
-
@org.springframework.stereotype.Component("dataTypeBusinessLogic")
public class DataTypeBusinessLogic extends BaseBusinessLogic {
@Autowired
- public DataTypeBusinessLogic(IElementOperation elementDao,
- IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation,
- IGroupTypeOperation groupTypeOperation,
- InterfaceOperation interfaceOperation,
- InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
- ArtifactsOperations artifactToscaOperation) {
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
- interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+ public DataTypeBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+ IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
+ InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+ artifactToscaOperation);
}
/**
@@ -64,22 +58,19 @@ public class DataTypeBusinessLogic extends BaseBusinessLogic {
ComponentParametersView filter = new ComponentParametersView();
filter.disableAll();
filter.setIgnoreDataType(false);
-
// Get Component object
- Either<? extends Component, StorageOperationStatus> componentResult =
- toscaOperationFacade.getToscaElement(componentId, filter);
+ Either<? extends Component, StorageOperationStatus> componentResult = toscaOperationFacade.getToscaElement(componentId, filter);
if (componentResult.isRight()) {
return Either.right(componentResult.right().value());
}
Component component = componentResult.left().value();
-
List<DataTypeDefinition> dataTypesToReturn = component.getDataTypes();
if (dataTypesToReturn == null) {
// this means there is no DATA_TYPES graph vertex.
+
// in this case, returns empty list.
dataTypesToReturn = new ArrayList<>();
}
-
return Either.left(dataTypesToReturn);
}
@@ -114,23 +105,19 @@ public class DataTypeBusinessLogic extends BaseBusinessLogic {
ComponentParametersView filter = new ComponentParametersView();
filter.disableAll();
filter.setIgnoreDataType(false);
-
// Get Component object
- Either<? extends Component, StorageOperationStatus> componentResult =
- toscaOperationFacade.getToscaElement(componentId, filter);
+ Either<? extends Component, StorageOperationStatus> componentResult = toscaOperationFacade.getToscaElement(componentId, filter);
if (componentResult.isRight()) {
// not exists
return Either.right(componentResult.right().value());
}
-
return deletePrivateDataType(componentResult.left().value(), dataTypeName);
}
/**
* Delete a data type from the Component.
*
- * @param component Component object which has data types.
- * needs to be fetched with componentParametersView.setIgnoreDataType(false)
+ * @param component Component object which has data types. needs to be fetched with componentParametersView.setIgnoreDataType(false)
* @param dataTypeName Data type name to be deleted
* @return deleted data type
*/
@@ -140,18 +127,15 @@ public class DataTypeBusinessLogic extends BaseBusinessLogic {
if (CollectionUtils.isEmpty(dataTypes)) {
return Either.right(StorageOperationStatus.NOT_FOUND);
}
- Optional<DataTypeDefinition> dataTypeResult =
- dataTypes.stream().filter(e -> e.getName().equals(dataTypeName)).findFirst();
+ Optional<DataTypeDefinition> dataTypeResult = dataTypes.stream().filter(e -> e.getName().equals(dataTypeName)).findFirst();
if (!dataTypeResult.isPresent()) {
return Either.right(StorageOperationStatus.NOT_FOUND);
}
-
// delete it
StorageOperationStatus deleteResult = toscaOperationFacade.deleteDataTypeOfComponent(component, dataTypeName);
if (deleteResult != StorageOperationStatus.OK) {
return Either.right(deleteResult);
}
-
// return deleted data type if ok
return Either.left(dataTypeResult.get());
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java
index 2e8344fc0a..4c7f072f71 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,10 +17,16 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import javax.annotation.Resource;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -36,14 +42,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.stereotype.Component;
-import javax.annotation.Resource;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.stream.Collectors;
-
@Component("dataTypeImportManager")
public class DataTypeImportManager {
@@ -56,91 +54,90 @@ public class DataTypeImportManager {
private CommonImportManager commonImportManager;
public Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat> createDataTypes(String dataTypeYml) {
- return commonImportManager.createElementTypes(dataTypeYml, this::createDataTypesFromYml, this::createDataTypesByDao, ElementTypeEnum.DATA_TYPE);
+ return commonImportManager
+ .createElementTypes(dataTypeYml, this::createDataTypesFromYml, this::createDataTypesByDao, ElementTypeEnum.DATA_TYPE);
}
private Either<List<DataTypeDefinition>, ActionStatus> createDataTypesFromYml(String dataTypesYml) {
return commonImportManager.createElementTypesFromYml(dataTypesYml, this::createDataType);
}
- private Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat> createDataTypesByDao(List<DataTypeDefinition> dataTypesToCreate) {
-
- return commonImportManager.createElementTypesByDao(dataTypesToCreate, this::validateDataType, dataType -> new ImmutablePair<>(ElementTypeEnum.DATA_TYPE, dataType.getName()),
- dataTypeName -> propertyOperation.getDataTypeByNameWithoutDerived(dataTypeName), dataType -> propertyOperation.addDataType(dataType), (newDataType, oldDataType) -> propertyOperation.updateDataType(newDataType, oldDataType));
+ private Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat> createDataTypesByDao(
+ List<DataTypeDefinition> dataTypesToCreate) {
+ return commonImportManager.createElementTypesByDao(dataTypesToCreate, this::validateDataType,
+ dataType -> new ImmutablePair<>(ElementTypeEnum.DATA_TYPE, dataType.getName()),
+ dataTypeName -> propertyOperation.getDataTypeByNameWithoutDerived(dataTypeName), dataType -> propertyOperation.addDataType(dataType),
+ (newDataType, oldDataType) -> propertyOperation.updateDataType(newDataType, oldDataType));
}
private Either<ActionStatus, ResponseFormat> validateDataType(DataTypeDefinition dataType) {
-
String dataTypeName = dataType.getName();
List<PropertyDefinition> properties = dataType.getProperties();
if (properties == null) {
// At least one parameter should be defined either in the properties
+
// section or at one of the parents
String derivedDataType = dataType.getDerivedFromName();
// If there are no properties, then we can create a data type if it
+
// is an abstract one or it derives from non abstract data type
if (derivedDataType == null || derivedDataType.isEmpty()) {
if (!isAbstract(dataType.getName()) && !ToscaPropertyType.isScalarType(dataTypeName)) {
log.debug("Data type {} must have properties unless it derives from non abstract data type", dataType.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null);
return Either.right(responseFormat);
}
} else {
if (!ToscaPropertyType.isScalarType(dataTypeName) && isAbstract(derivedDataType)) {
log.warn("Creating data type {} which derived from abstract data type with no properties", dataType.getName());
}
- }
+ }
} else {
// properties tag cannot be empty
if (properties.isEmpty()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY, dataType, null);
-
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY, dataType, null);
return Either.right(responseFormat);
}
-
// check no duplicates
Set<String> collect = properties.stream().map(PropertyDataDefinition::getName).collect(Collectors.toSet());
if (collect != null && properties.size() != collect.size()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DUPLICATE_PROPERTY, dataType, null);
-
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByDataType(ActionStatus.DATA_TYPE_DUPLICATE_PROPERTY, dataType, null);
return Either.right(responseFormat);
}
-
- List<String> propertiesWithSameTypeAsDataType = properties.stream().filter(p -> p.getType().equals(dataType.getName())).map(PropertyDataDefinition::getName).collect(Collectors.toList());
+ List<String> propertiesWithSameTypeAsDataType = properties.stream().filter(p -> p.getType().equals(dataType.getName()))
+ .map(PropertyDataDefinition::getName).collect(Collectors.toList());
if (propertiesWithSameTypeAsDataType != null && !propertiesWithSameTypeAsDataType.isEmpty()) {
log.debug("The data type {} contains properties with the type {}", dataType.getName(), dataType.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE, dataType, propertiesWithSameTypeAsDataType);
-
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE, dataType,
+ propertiesWithSameTypeAsDataType);
return Either.right(responseFormat);
}
}
-
String derivedDataType = dataType.getDerivedFromName();
if (derivedDataType != null) {
Either<DataTypeDefinition, StorageOperationStatus> derivedDataTypeByName = propertyOperation.getDataTypeByName(derivedDataType, true);
if (derivedDataTypeByName.isRight()) {
StorageOperationStatus status = derivedDataTypeByName.right().value();
if (status == StorageOperationStatus.NOT_FOUND) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DERIVED_IS_MISSING, dataType, null);
-
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByDataType(ActionStatus.DATA_TYPE_DERIVED_IS_MISSING, dataType, null);
return Either.right(responseFormat);
} else {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.GENERAL_ERROR, dataType, null);
-
return Either.right(responseFormat);
-
}
} else {
-
DataTypeDefinition derivedDataTypeDef = derivedDataTypeByName.left().value();
- if (properties != null && !properties.isEmpty() && derivedDataTypeDef!=null) {
-
+ if (properties != null && !properties.isEmpty() && derivedDataTypeDef != null) {
if (isScalarType(derivedDataTypeDef)) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_CANNOT_HAVE_PROPERTIES, dataType, null);
-
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByDataType(ActionStatus.DATA_TYPE_CANNOT_HAVE_PROPERTIES, dataType, null);
return Either.right(responseFormat);
}
-
Set<String> allParentsProps = new HashSet<>();
do {
List<PropertyDefinition> currentParentsProps = derivedDataTypeDef.getProperties();
@@ -151,18 +148,18 @@ public class DataTypeImportManager {
}
derivedDataTypeDef = derivedDataTypeDef.getDerivedFrom();
} while (derivedDataTypeDef != null);
-
// Check that no property is already defined in one of the
+
// ancestors
- Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(PropertyDataDefinition::getName).collect(Collectors.toSet());
+ Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName()))
+ .map(PropertyDataDefinition::getName).collect(Collectors.toSet());
if (alreadyExistPropsCollection != null && !alreadyExistPropsCollection.isEmpty()) {
List<String> duplicateProps = new ArrayList<>();
duplicateProps.addAll(alreadyExistPropsCollection);
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR, dataType, duplicateProps);
-
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR, dataType, duplicateProps);
return Either.right(responseFormat);
}
-
}
}
}
@@ -170,37 +167,27 @@ public class DataTypeImportManager {
}
private boolean isAbstract(String dataTypeName) {
-
ToscaPropertyType isPrimitiveToscaType = ToscaPropertyType.isValidType(dataTypeName);
-
return isPrimitiveToscaType != null && isPrimitiveToscaType.isAbstract();
-
}
private boolean isScalarType(DataTypeDefinition dataTypeDef) {
-
boolean isScalar = false;
DataTypeDefinition dataType = dataTypeDef;
-
while (dataType != null) {
-
String name = dataType.getName();
if (ToscaPropertyType.isScalarType(name)) {
isScalar = true;
break;
}
-
dataType = dataType.getDerivedFrom();
}
-
return isScalar;
}
private DataTypeDefinition createDataType(String dataTypeName, Map<String, Object> toscaJson) {
DataTypeDefinition dataType = new DataTypeDefinition();
-
dataType.setName(dataTypeName);
-
if (toscaJson != null) {
// Description
commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName(), dataType::setDescription);
@@ -211,5 +198,4 @@ public class DataTypeImportManager {
}
return dataType;
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypesService.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypesService.java
index cc831d4255..be61e7b112 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypesService.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypesService.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,10 +17,10 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
+import java.util.Map;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
@@ -30,8 +30,6 @@ import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.stereotype.Component;
-import java.util.Map;
-
@Component
public class DataTypesService {
@@ -46,14 +44,15 @@ public class DataTypesService {
if (allDataTypes.isRight()) {
JanusGraphOperationStatus operationStatus = allDataTypes.right().value();
if (operationStatus == JanusGraphOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().logInternalDataError("FetchDataTypes", "Data types are not loaded", BeEcompErrorManager.ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError("FetchDataTypes", "Data types are not loaded", BeEcompErrorManager.ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY));
} else {
- BeEcompErrorManager.getInstance().logInternalFlowError("FetchDataTypes", "Failed to fetch data types", BeEcompErrorManager.ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalFlowError("FetchDataTypes", "Failed to fetch data types", BeEcompErrorManager.ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
}
return Either.left(allDataTypes.left().value());
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java
index 66cab35cd2..f3334e6177 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java
@@ -17,11 +17,15 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
import java.util.Optional;
+import java.util.Set;
import org.apache.http.HttpStatus;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
@@ -45,44 +49,28 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
@Component("distributionMonitoringBusinessLogic")
public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
- private static final String DEPLOYED = "Deployed";
+ private static final String DEPLOYED = "Deployed";
private static final String ERROR = "Error";
-
private static final String DISTRIBUTED = "Distributed";
-
private static final String IN_PROGRESS = "In Progress";
-
private static final Logger log = Logger.getLogger(ArtifactsBusinessLogic.class.getName());
-
private final AuditCassandraDao cassandraDao;
@Autowired
- public DistributionMonitoringBusinessLogic(IElementOperation elementDao,
- IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation,
- IGroupTypeOperation groupTypeOperation,
- InterfaceOperation interfaceOperation,
- InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
- AuditCassandraDao cassandraDao,
- ArtifactsOperations artifactToscaOperation) {
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
- interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+ public DistributionMonitoringBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
+ IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation,
+ InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+ AuditCassandraDao cassandraDao, ArtifactsOperations artifactToscaOperation) {
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+ artifactToscaOperation);
this.cassandraDao = cassandraDao;
}
public Either<DistributionStatusListResponse, ResponseFormat> getListOfDistributionStatus(String did, String userId) {
-
validateUserExists(userId);
-
log.trace("getListOfDistributionStatus for did {}", did);
Either<List<DistributionStatusEvent>, ActionStatus> distributionStatus = cassandraDao.getListOfDistributionStatuses(did);
if (distributionStatus.isRight()) {
@@ -96,7 +84,6 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
distribStatusInfoList.add(new DistributionStatusInfo(distributionStatusEvent));
}
}
-
DistributionStatusListResponse distributionStatusListResponse = new DistributionStatusListResponse();
distributionStatusListResponse.setDistributionStatusList(distribStatusInfoList);
log.trace("list statuses for did {} is {} ", did, distribStatusInfoList);
@@ -105,7 +92,6 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
public Either<DistributionStatusOfServiceListResponce, ResponseFormat> getListOfDistributionServiceStatus(String serviceUuid, String userId) {
validateUserExists(userId);
-
log.trace("getListOfDistributionServiceStatus for serviceUUID {}", serviceUuid);
Either<List<? extends AuditingGenericEvent>, ActionStatus> status = cassandraDao.getServiceDistributionStatusesList(serviceUuid);
if (status.isRight()) {
@@ -134,15 +120,12 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
AuditingGenericEvent resAuditingGenericEvent = null;
for (AuditingGenericEvent auditingGenericEvent : auditingGenericEventList) {
auditingGenericEvent.fillFields();
-
String action = (String) auditingGenericEvent.getFields().get(AuditingFieldsKey.AUDIT_ACTION.getDisplayName());
Object modifierUserId = auditingGenericEvent.getFields().get(AuditingFieldsKey.AUDIT_MODIFIER_UID.getDisplayName());
if (modifierUserId != null) {
distributionStatusOfServiceInfo.setUserId((String) modifierUserId);
}
-
if (action.equals(AuditingActionEnum.DISTRIBUTION_DEPLOY.getName())) {
-
isResult = true;
resAuditingGenericEvent = auditingGenericEvent;
break;
@@ -151,38 +134,34 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
} else if (action.equals(AuditingActionEnum.DISTRIBUTION_NOTIFY.getName())) {
dNotifyStatus = getStatusFromAuditEvent(auditingGenericEvent);
}
-
resAuditingGenericEvent = auditingGenericEvent;
}
-
if (resAuditingGenericEvent != null) {
Map<String, Object> fields = resAuditingGenericEvent.getFields();
-
if (fields != null) {
- Optional.ofNullable(
- fields.get(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName()))
+ Optional.ofNullable(fields.get(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName()))
.ifPresent(timestamp -> distributionStatusOfServiceInfo.setTimestamp((String) timestamp));
}
}
-
if (!isResult) {
if (dReguestStatus.equals(String.valueOf(HttpStatus.SC_OK))) {
if (dNotifyStatus.isEmpty()) {
distributionStatusOfServiceInfo.setDeployementStatus(IN_PROGRESS);
-
} else {
- if (dNotifyStatus.equals(String.valueOf(HttpStatus.SC_OK)))
+ if (dNotifyStatus.equals(String.valueOf(HttpStatus.SC_OK))) {
distributionStatusOfServiceInfo.setDeployementStatus(DISTRIBUTED);
- else
+ } else {
distributionStatusOfServiceInfo.setDeployementStatus(ERROR);
+ }
}
- } else
+ } else {
distributionStatusOfServiceInfo.setDeployementStatus(ERROR);
- } else
+ }
+ } else {
distributionStatusOfServiceInfo.setDeployementStatus(DEPLOYED);
+ }
reslist.add(distributionStatusOfServiceInfo);
}
-
return reslist;
}
@@ -196,25 +175,21 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
}
private Map<String, List<AuditingGenericEvent>> createServiceDidMap(List<? extends AuditingGenericEvent> distribStatusInfoList) {
-
Map<String, List<AuditingGenericEvent>> serviceDidMap = new HashMap<>();
for (AuditingGenericEvent auditingGenericEvent : distribStatusInfoList) {
List<AuditingGenericEvent> auditingGenericEventList = null;
String did = "";
auditingGenericEvent.fillFields();
-
Object didValue = auditingGenericEvent.getFields().get(AuditingFieldsKey.AUDIT_DISTRIBUTION_ID.getDisplayName());
if (didValue != null) {
did = (String) didValue;
}
-
if (!did.isEmpty()) {
if (serviceDidMap.containsKey(did)) {
auditingGenericEventList = serviceDidMap.get(did);
}
if (auditingGenericEventList == null) {
auditingGenericEventList = new ArrayList<>();
-
}
auditingGenericEventList.add(auditingGenericEvent);
serviceDidMap.put(did, auditingGenericEventList);
@@ -222,5 +197,4 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
}
return serviceDidMap;
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java
index 631daefff8..499a6127a1 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java
@@ -19,10 +19,26 @@
* Modifications copyright (c) 2019 Nokia
* ================================================================================
*/
-
package org.openecomp.sdc.be.components.impl;
+import static org.apache.commons.lang.BooleanUtils.isTrue;
+import static org.openecomp.sdc.be.components.impl.ImportUtils.Constants.DEFAULT_ICON;
+
import fj.data.Either;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
@@ -89,24 +105,6 @@ import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.Set;
-import java.util.function.Predicate;
-import java.util.stream.Collectors;
-
-import static org.apache.commons.lang.BooleanUtils.isTrue;
-import static org.openecomp.sdc.be.components.impl.ImportUtils.Constants.DEFAULT_ICON;
-
@org.springframework.stereotype.Component("elementsBusinessLogic")
public class ElementBusinessLogic extends BaseBusinessLogic {
@@ -116,27 +114,21 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
private static final String VALIDATION_OF_USER_FAILED_USER_ID = "Validation of user failed, userId {}";
private static final String COMPONENT_TYPE_IS_INVALID = "Component type {} is invalid";
private static final String VALIDATION_OF_USER_ROLE_FAILED_USER_ID = "Validation of user role failed, userId {}";
-
private final IElementOperation elementOperation;
private final UserBusinessLogic userAdminManager;
@Autowired
- public ElementBusinessLogic(IElementOperation elementDao,
- IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation,
- IGroupTypeOperation groupTypeOperation,
- GroupBusinessLogic groupBusinessLogic,
- InterfaceOperation interfaceOperation,
- InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
- ArtifactsOperations artifactToscaOperation, IElementOperation elementOperation,
- UserBusinessLogic userAdminManager) {
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
- interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+ public ElementBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+ IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic, InterfaceOperation interfaceOperation,
+ InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation,
+ IElementOperation elementOperation, UserBusinessLogic userAdminManager) {
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+ artifactToscaOperation);
this.elementOperation = elementOperation;
this.userAdminManager = userAdminManager;
}
+
/**
- *
* @param user
* @return
*/
@@ -147,35 +139,29 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
String role = user.getRole();
String userId = user.getUserId();
Role currentRole = Role.valueOf(role);
-
switch (currentRole) {
- case DESIGNER:
- response = handleDesigner(userId);
- break;
-
- case PRODUCT_STRATEGIST:
- response = handleProductStrategist();
- break;
-
- case PRODUCT_MANAGER:
- response = handleProductManager(userId);
- break;
-
- case ADMIN:
- response = handleAdmin();
- break;
-
- default:
- response = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- break;
+ case DESIGNER:
+ response = handleDesigner(userId);
+ break;
+ case PRODUCT_STRATEGIST:
+ response = handleProductStrategist();
+ break;
+ case PRODUCT_MANAGER:
+ response = handleProductManager(userId);
+ break;
+ case ADMIN:
+ response = handleAdmin();
+ break;
+ default:
+ response = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ break;
}
// converting the Set to List so the rest of the code will handle it normally (Was changed because the same element with the same uuid was returned twice)
return convertedToListResponse(response);
-
}
- private Either<Map<String, List<? extends Component>>, ResponseFormat> convertedToListResponse(Either<Map<String, Set<? extends Component>>, ResponseFormat> setResponse) {
-
+ private Either<Map<String, List<? extends Component>>, ResponseFormat> convertedToListResponse(
+ Either<Map<String, Set<? extends Component>>, ResponseFormat> setResponse) {
Map<String, List<? extends Component>> arrayResponse = new HashMap<>();
if (setResponse.isLeft()) {
for (Map.Entry<String, Set<? extends Component>> entry : setResponse.left().value().entrySet()) {
@@ -228,13 +214,15 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return response;
}
- private Either<Map<String, Set<? extends Component>>, ResponseFormat> getFollowedResourcesAndServices(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates) {
-
+ private Either<Map<String, Set<? extends Component>>, ResponseFormat> getFollowedResourcesAndServices(String userId,
+ Set<LifecycleStateEnum> lifecycleStates,
+ Set<LifecycleStateEnum> lastStateStates) {
try {
- Either<Set<Resource>, StorageOperationStatus> resources = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.RESOURCE);
-
+ Either<Set<Resource>, StorageOperationStatus> resources = toscaOperationFacade
+ .getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.RESOURCE);
if (resources.isLeft()) {
- Either<Set<Service>, StorageOperationStatus> services = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.SERVICE);
+ Either<Set<Service>, StorageOperationStatus> services = toscaOperationFacade
+ .getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.SERVICE);
if (services.isLeft()) {
Map<String, Set<? extends Component>> result = new HashMap<>();
result.put(SERVICES, services.left().value());
@@ -251,8 +239,10 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
}
- private Either<Map<String, Set<? extends Component>>, ResponseFormat> getFollowedProducts(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates) {
- Either<Set<Product>, StorageOperationStatus> products = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.PRODUCT);
+ private Either<Map<String, Set<? extends Component>>, ResponseFormat> getFollowedProducts(String userId, Set<LifecycleStateEnum> lifecycleStates,
+ Set<LifecycleStateEnum> lastStateStates) {
+ Either<Set<Product>, StorageOperationStatus> products = toscaOperationFacade
+ .getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.PRODUCT);
if (products.isLeft()) {
Map<String, Set<? extends Component>> result = new HashMap<>();
result.put("products", products.left().value());
@@ -274,12 +264,10 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
public Either<CategoryDefinition, ResponseFormat> createCategory(CategoryDefinition category, String componentTypeParamName, String userId) {
-
AuditingActionEnum auditingAction = AuditingActionEnum.ADD_CATEGORY;
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
String componentType = componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue();
CategoryTypeEnum categoryType = CategoryTypeEnum.CATEGORY;
-
User user = validateUserExists(userId);
if (category == null) {
log.debug("Category json is invalid");
@@ -287,7 +275,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
handleCategoryAuditing(responseFormat, user, null, auditingAction, componentType);
return Either.right(responseFormat);
}
-
String categoryName = category.getName();
// For auditing of failures we need the original non-normalized name
String origCategoryName = categoryName;
@@ -297,7 +284,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, componentTypeEnum);
if (validateUserRole.isRight()) {
log.debug(VALIDATION_OF_USER_ROLE_FAILED_USER_ID, userId);
@@ -305,35 +291,30 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
if (!ValidationUtils.validateCategoryDisplayNameFormat(categoryName)) {
log.debug("Category display name format is invalid, name {}, componentType {}", categoryName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue());
handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
categoryName = ValidationUtils.normalizeCategoryName4Display(categoryName);
-
if (!ValidationUtils.validateCategoryDisplayNameLength(categoryName)) {
- log.debug("Category display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", categoryName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue());
+ log.debug("Category display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", categoryName,
+ componentType);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue());
handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
category.setName(categoryName);
-
String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(categoryName);
category.setNormalizedName(normalizedName);
-
- if (ValidationUtils.validateCategoryIconNotEmpty(category.getIcons())){
+ if (ValidationUtils.validateCategoryIconNotEmpty(category.getIcons())) {
log.debug("createCategory: setting category icon to default icon since service category was created without an icon ");
category.setIcons(Arrays.asList(DEFAULT_ICON));
}
-
NodeTypeEnum nodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, categoryType);
-
Either<Boolean, ActionStatus> categoryUniqueEither = elementOperation.isCategoryUniqueForType(nodeType, normalizedName);
if (categoryUniqueEither.isRight()) {
log.debug("Failed to check category uniqueness, name {}, componentType {}", categoryName, componentType);
@@ -341,19 +322,19 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
Boolean isCategoryUnique = categoryUniqueEither.left().value();
if (!isCategoryUnique) {
log.debug("Category is not unique, name {}, componentType {}", categoryName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS, componentType, categoryName);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS, componentType, categoryName);
handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
Either<CategoryDefinition, ActionStatus> createCategoryByType = elementOperation.createCategory(category, nodeType);
if (createCategoryByType.isRight()) {
log.debug("Failed to create category, name {}, componentType {}", categoryName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS, componentType, categoryName);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS, componentType, categoryName);
handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
return Either.right(componentsUtils.getResponseFormat(createCategoryByType.right().value()));
}
@@ -364,37 +345,33 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return Either.left(category);
}
- public Either<SubCategoryDefinition, ResponseFormat> createSubCategory(SubCategoryDefinition subCategory, String componentTypeParamName, String parentCategoryId, String userId) {
-
+ public Either<SubCategoryDefinition, ResponseFormat> createSubCategory(SubCategoryDefinition subCategory, String componentTypeParamName,
+ String parentCategoryId, String userId) {
AuditingActionEnum auditingAction = AuditingActionEnum.ADD_SUB_CATEGORY;
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
String componentType = componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue();
CategoryTypeEnum categoryType = CategoryTypeEnum.SUBCATEGORY;
// For auditing
String parentCategoryName = parentCategoryId;
-
if (subCategory == null) {
log.debug("Sub-category json is invalid");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
handleCategoryAuditing(responseFormat, null, parentCategoryName, null, auditingAction, componentType);
return Either.right(responseFormat);
}
-
String subCategoryName = subCategory.getName();
// For auditing of failures we need the original non-normalized name
String origSubCategoryName = subCategoryName;
User user;
- try{
- user = validateUserExists(userId);
- } catch(ByActionStatusComponentException e){
+ try {
+ user = validateUserExists(userId);
+ } catch (ByActionStatusComponentException e) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
- handleComponentException(userId, auditingAction, componentType, parentCategoryName, origSubCategoryName,
- responseFormat);
+ handleComponentException(userId, auditingAction, componentType, parentCategoryName, origSubCategoryName, responseFormat);
throw e;
- } catch(ByResponseFormatComponentException e){
+ } catch (ByResponseFormatComponentException e) {
ResponseFormat responseFormat = e.getResponseFormat();
- handleComponentException(userId, auditingAction, componentType, parentCategoryName, origSubCategoryName,
- responseFormat);
+ handleComponentException(userId, auditingAction, componentType, parentCategoryName, origSubCategoryName, responseFormat);
throw e;
}
if (componentTypeEnum == null) {
@@ -403,7 +380,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
Either<Boolean, ResponseFormat> validateComponentType = validateComponentTypeForCategory(componentTypeEnum, categoryType);
if (validateComponentType.isRight()) {
log.debug("Validation of component type for sub-category failed");
@@ -411,7 +387,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, componentTypeEnum);
if (validateUserRole.isRight()) {
log.debug(VALIDATION_OF_USER_ROLE_FAILED_USER_ID, userId);
@@ -419,65 +394,69 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
NodeTypeEnum parentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY);
NodeTypeEnum childNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY);
-
CategoryDefinition categoryDefinition;
- Either<CategoryDefinition, ResponseFormat> validateCategoryExists = validateCategoryExists(parentNodeType, parentCategoryId, componentTypeEnum);
+ Either<CategoryDefinition, ResponseFormat> validateCategoryExists = validateCategoryExists(parentNodeType, parentCategoryId,
+ componentTypeEnum);
if (validateCategoryExists.isRight()) {
log.debug("Validation of parent category exists failed, parent categoryId {}", parentCategoryId);
ResponseFormat responseFormat = validateCategoryExists.right().value();
handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
categoryDefinition = validateCategoryExists.left().value();
parentCategoryName = categoryDefinition.getName();
-
if (!ValidationUtils.validateCategoryDisplayNameFormat(subCategoryName)) {
log.debug("Sub-category display name format is invalid, name {}, componentType {}", subCategoryName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue());
handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
subCategoryName = ValidationUtils.normalizeCategoryName4Display(subCategoryName);
-
if (!ValidationUtils.validateCategoryDisplayNameLength(subCategoryName)) {
- log.debug("Sub-category display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", subCategoryName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue());
+ log.debug("Sub-category display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", subCategoryName,
+ componentType);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue());
handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(subCategoryName);
subCategory.setNormalizedName(normalizedName);
-
// Uniqueness under this category
- Either<Boolean, ActionStatus> subCategoryUniqueForCategory = elementOperation.isSubCategoryUniqueForCategory(childNodeType, normalizedName, parentCategoryId);
+ Either<Boolean, ActionStatus> subCategoryUniqueForCategory = elementOperation
+ .isSubCategoryUniqueForCategory(childNodeType, normalizedName, parentCategoryId);
if (subCategoryUniqueForCategory.isRight()) {
- log.debug("Failed to check sub-category uniqueness, parent name {}, subcategory norm name {}, componentType {}", parentCategoryName, normalizedName, componentType);
+ log.debug("Failed to check sub-category uniqueness, parent name {}, subcategory norm name {}, componentType {}", parentCategoryName,
+ normalizedName, componentType);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForCategory.right().value());
handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
Boolean isSubUnique = subCategoryUniqueForCategory.left().value();
if (!isSubUnique) {
- log.debug("Sub-category is not unique for category, parent name {}, subcategory norm name {}, componentType {}", parentCategoryName, normalizedName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY, componentType, subCategoryName, parentCategoryName);
+ log.debug("Sub-category is not unique for category, parent name {}, subcategory norm name {}, componentType {}", parentCategoryName,
+ normalizedName, componentType);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY, componentType, subCategoryName, parentCategoryName);
handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
// Setting name of subcategory to fit the similar subcategory name
+
// ignoring cases.
+
// For example if Network-->kUKU exists for service category Network,
+
// and user is trying to create Router-->Kuku for service category
+
// Router,
+
// his subcategory name will be Router-->kUKU.
- Either<SubCategoryDefinition, ActionStatus> subCategoryUniqueForType = elementOperation.getSubCategoryUniqueForType(childNodeType, normalizedName);
+ Either<SubCategoryDefinition, ActionStatus> subCategoryUniqueForType = elementOperation
+ .getSubCategoryUniqueForType(childNodeType, normalizedName);
if (subCategoryUniqueForType.isRight()) {
log.debug("Failed validation of whether similar sub-category exists, normalizedName {} componentType {}", normalizedName, componentType);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForType.right().value());
@@ -488,18 +467,16 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
if (subCategoryDefinition != null) {
subCategoryName = subCategoryDefinition.getName();
}
-
subCategory.setName(subCategoryName);
///////////////////////////////////////////// Validations end
-
- Either<SubCategoryDefinition, ActionStatus> createSubCategory = elementOperation.createSubCategory(parentCategoryId, subCategory, childNodeType);
+ Either<SubCategoryDefinition, ActionStatus> createSubCategory = elementOperation
+ .createSubCategory(parentCategoryId, subCategory, childNodeType);
if (createSubCategory.isRight()) {
log.debug("Failed to create sub-category, name {}, componentType {}", subCategoryName, componentType);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForType.right().value());
handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
SubCategoryDefinition subCategoryCreated = createSubCategory.left().value();
log.debug("Created sub-category for component {}, name {}, uniqueId {}", componentType, subCategoryName, subCategoryCreated.getUniqueId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
@@ -507,25 +484,23 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return Either.left(subCategoryCreated);
}
- private void handleComponentException(String userId, AuditingActionEnum auditingAction, String componentType,
- String parentCategoryName, String origSubCategoryName, ResponseFormat responseFormat) {
+ private void handleComponentException(String userId, AuditingActionEnum auditingAction, String componentType, String parentCategoryName,
+ String origSubCategoryName, ResponseFormat responseFormat) {
User user;
log.debug(VALIDATION_OF_USER_FAILED_USER_ID, userId);
user = new User();
user.setUserId(userId);
- handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction,
- componentType);
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
}
- private void handleComponentException(GroupingDefinition grouping, String userId, AuditingActionEnum auditingAction,
- String componentType, String parentCategoryName, String parentSubCategoryName, ResponseFormat responseFormat) {
+ private void handleComponentException(GroupingDefinition grouping, String userId, AuditingActionEnum auditingAction, String componentType,
+ String parentCategoryName, String parentSubCategoryName, ResponseFormat responseFormat) {
User user;
log.debug(VALIDATION_OF_USER_FAILED_USER_ID, userId);
user = new User();
user.setUserId(userId);
String groupingNameForAudit = grouping == null ? null : grouping.getName();
- handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingNameForAudit,
- auditingAction, componentType);
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingNameForAudit, auditingAction, componentType);
}
private void handleComponentException(String componentType, String userId, ResponseFormat responseFormat) {
@@ -536,8 +511,8 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
componentsUtils.auditGetCategoryHierarchy(user, componentType, responseFormat);
}
- public Either<GroupingDefinition, ResponseFormat> createGrouping(GroupingDefinition grouping, String componentTypeParamName, String grandParentCategoryId, String parentSubCategoryId, String userId) {
-
+ public Either<GroupingDefinition, ResponseFormat> createGrouping(GroupingDefinition grouping, String componentTypeParamName,
+ String grandParentCategoryId, String parentSubCategoryId, String userId) {
AuditingActionEnum auditingAction = AuditingActionEnum.ADD_GROUPING;
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
String componentType = componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue();
@@ -545,41 +520,33 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
// For auditing
String parentCategoryName = grandParentCategoryId;
String parentSubCategoryName = parentSubCategoryId;
-
User user;
- try{
+ try {
user = validateUserExists(userId);
- } catch(ByResponseFormatComponentException e){
+ } catch (ByResponseFormatComponentException e) {
ResponseFormat responseFormat = e.getResponseFormat();
- handleComponentException(grouping, userId, auditingAction, componentType, parentCategoryName,
- parentSubCategoryName,
- responseFormat);
+ handleComponentException(grouping, userId, auditingAction, componentType, parentCategoryName, parentSubCategoryName, responseFormat);
throw e;
- } catch(ByActionStatusComponentException e){
+ } catch (ByActionStatusComponentException e) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
- handleComponentException(grouping, userId, auditingAction, componentType, parentCategoryName,
- parentSubCategoryName, responseFormat);
+ handleComponentException(grouping, userId, auditingAction, componentType, parentCategoryName, parentSubCategoryName, responseFormat);
throw e;
}
-
if (grouping == null) {
log.debug("Grouping json is invalid");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, null, auditingAction, componentType);
return Either.right(responseFormat);
}
-
String groupingName = grouping.getName();
// For auditing of failures we need the original non-normalized name
String origGroupingName = groupingName;
-
if (componentTypeEnum == null) {
log.debug(COMPONENT_TYPE_IS_INVALID, componentTypeParamName);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
Either<Boolean, ResponseFormat> validateComponentType = validateComponentTypeForCategory(componentTypeEnum, categoryType);
if (validateComponentType.isRight()) {
log.debug("Validation of component type for grouping failed");
@@ -587,7 +554,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, componentTypeEnum);
if (validateUserRole.isRight()) {
log.debug(VALIDATION_OF_USER_ROLE_FAILED_USER_ID, userId);
@@ -595,78 +561,80 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
NodeTypeEnum grandParentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY);
NodeTypeEnum parentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY);
NodeTypeEnum childNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.GROUPING);
-
// Validate category
CategoryDefinition categoryDefinition;
- Either<CategoryDefinition, ResponseFormat> validateCategoryExists = validateCategoryExists(grandParentNodeType, grandParentCategoryId, componentTypeEnum);
+ Either<CategoryDefinition, ResponseFormat> validateCategoryExists = validateCategoryExists(grandParentNodeType, grandParentCategoryId,
+ componentTypeEnum);
if (validateCategoryExists.isRight()) {
log.debug("Validation of parent category exists failed, parent categoryId {}", grandParentCategoryId);
ResponseFormat responseFormat = validateCategoryExists.right().value();
handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
categoryDefinition = validateCategoryExists.left().value();
parentCategoryName = categoryDefinition.getName();
-
// Validate subcategory
SubCategoryDefinition subCategoryDefinition;
- Either<SubCategoryDefinition, ResponseFormat> validateSubCategoryExists = validateSubCategoryExists(parentNodeType, parentSubCategoryId, componentTypeEnum);
+ Either<SubCategoryDefinition, ResponseFormat> validateSubCategoryExists = validateSubCategoryExists(parentNodeType, parentSubCategoryId,
+ componentTypeEnum);
if (validateSubCategoryExists.isRight()) {
log.debug("Validation of parent sub-category exists failed, parent sub-category id {}", parentSubCategoryId);
ResponseFormat responseFormat = validateSubCategoryExists.right().value();
handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
subCategoryDefinition = validateSubCategoryExists.left().value();
parentSubCategoryName = subCategoryDefinition.getName();
-
if (!ValidationUtils.validateCategoryDisplayNameFormat(groupingName)) {
log.debug("Sub-category display name format is invalid, name {}, componentType {}", groupingName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue());
handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
groupingName = ValidationUtils.normalizeCategoryName4Display(groupingName);
-
if (!ValidationUtils.validateCategoryDisplayNameLength(groupingName)) {
- log.debug("Grouping display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", groupingName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue());
+ log.debug("Grouping display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", groupingName,
+ componentType);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue());
handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(groupingName);
grouping.setNormalizedName(normalizedName);
-
// Uniqueness under this category
- Either<Boolean, ActionStatus> groupingUniqueForSubCategory = elementOperation.isGroupingUniqueForSubCategory(childNodeType, normalizedName, parentSubCategoryId);
+ Either<Boolean, ActionStatus> groupingUniqueForSubCategory = elementOperation
+ .isGroupingUniqueForSubCategory(childNodeType, normalizedName, parentSubCategoryId);
if (groupingUniqueForSubCategory.isRight()) {
- log.debug("Failed to check grouping uniqueness, parent name {}, grouping norm name {}, componentType {}", parentSubCategoryName, normalizedName, componentType);
+ log.debug("Failed to check grouping uniqueness, parent name {}, grouping norm name {}, componentType {}", parentSubCategoryName,
+ normalizedName, componentType);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(groupingUniqueForSubCategory.right().value());
handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
Boolean isGroupingUnique = groupingUniqueForSubCategory.left().value();
if (!isGroupingUnique) {
- log.debug("Grouping is not unique for sub-category, parent name {}, grouping norm name {}, componentType {}", parentSubCategoryName, normalizedName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY, componentType, groupingName, parentSubCategoryName);
+ log.debug("Grouping is not unique for sub-category, parent name {}, grouping norm name {}, componentType {}", parentSubCategoryName,
+ normalizedName, componentType);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY, componentType, groupingName, parentSubCategoryName);
handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
// Setting name of grouping to fit the similar grouping name ignoring
+
// cases.
+
// For example if Network-->kUKU exists for service sub-category
+
// Network, and user is trying to create grouping Router-->Kuku for
+
// service sub-category Router,
+
// his grouping name will be Router-->kUKU.
Either<GroupingDefinition, ActionStatus> groupingUniqueForType = elementOperation.getGroupingUniqueForType(childNodeType, normalizedName);
if (groupingUniqueForType.isRight()) {
@@ -679,10 +647,8 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
if (groupingDefinition != null) {
groupingName = groupingDefinition.getName();
}
-
grouping.setName(groupingName);
///////////////////////////////////////////// Validations end
-
Either<GroupingDefinition, ActionStatus> createGrouping = elementOperation.createGrouping(parentSubCategoryId, grouping, childNodeType);
if (createGrouping.isRight()) {
log.debug("Failed to create grouping, name {}, componentType {}", groupingName, componentType);
@@ -690,16 +656,14 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
return Either.right(responseFormat);
}
-
GroupingDefinition groupingCreated = createGrouping.left().value();
log.debug("Created grouping for component {}, name {}, uniqueId {}", componentType, groupingName, groupingCreated.getUniqueId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
- handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingCreated.getName(), auditingAction, componentType);
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingCreated.getName(), auditingAction,
+ componentType);
return Either.left(groupingCreated);
}
-
-
public Either<List<CategoryDefinition>, ResponseFormat> getAllCategories(String componentType, String userId) {
ResponseFormat responseFormat;
User user = new User();
@@ -711,11 +675,11 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
try {
user = validateUserExists(userId);
- } catch (ByActionStatusComponentException e){
+ } catch (ByActionStatusComponentException e) {
responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
handleComponentException(componentType, userId, responseFormat);
throw e;
- } catch (ByResponseFormatComponentException e){
+ } catch (ByResponseFormatComponentException e) {
responseFormat = e.getResponseFormat();
handleComponentException(componentType, userId, responseFormat);
throw e;
@@ -727,7 +691,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
componentsUtils.auditGetCategoryHierarchy(user, componentType, responseFormat);
return Either.right(responseFormat);
}
-
NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY);
Either<List<CategoryDefinition>, ActionStatus> getAllCategoriesByType = elementOperation.getAllCategories(nodeTypeEnum, false);
if (getAllCategoriesByType.isRight()) {
@@ -741,25 +704,22 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return Either.left(categories);
}
-
-
public Either<UiCategories, ResponseFormat> getAllCategories(String userId) {
ResponseFormat responseFormat;
UiCategories categories = new UiCategories();
-
User user = validateUserExists(userId);
-
// GET resource categories
- Either<List<CategoryDefinition>, ActionStatus> getResourceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ResourceNewCategory, false);
+ Either<List<CategoryDefinition>, ActionStatus> getResourceCategoriesByType = elementOperation
+ .getAllCategories(NodeTypeEnum.ResourceNewCategory, false);
if (getResourceCategoriesByType.isRight()) {
responseFormat = componentsUtils.getResponseFormat(getResourceCategoriesByType.right().value());
componentsUtils.auditGetCategoryHierarchy(user, ComponentTypeEnum.RESOURCE.getValue(), responseFormat);
return Either.right(responseFormat);
}
categories.setResourceCategories(getResourceCategoriesByType.left().value());
-
// GET service categories
- Either<List<CategoryDefinition>, ActionStatus> getServiceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ServiceNewCategory, false);
+ Either<List<CategoryDefinition>, ActionStatus> getServiceCategoriesByType = elementOperation
+ .getAllCategories(NodeTypeEnum.ServiceNewCategory, false);
if (getServiceCategoriesByType.isRight()) {
responseFormat = componentsUtils.getResponseFormat(getServiceCategoriesByType.right().value());
componentsUtils.auditGetCategoryHierarchy(user, ComponentTypeEnum.SERVICE.getValue(), responseFormat);
@@ -771,17 +731,13 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
public Either<CategoryDefinition, ResponseFormat> deleteCategory(String categoryId, String componentTypeParamName, String userId) {
-
validateUserExists(userId);
-
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
if (componentTypeEnum == null) {
log.debug("Cannot create category for component type {}", componentTypeParamName);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
-
NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY);
-
Either<CategoryDefinition, ActionStatus> deleteCategoryByType = elementOperation.deleteCategory(nodeTypeEnum, categoryId);
if (deleteCategoryByType.isRight()) {
// auditing, logging here...
@@ -793,17 +749,13 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
public Either<SubCategoryDefinition, ResponseFormat> deleteSubCategory(String parentSubCategoryId, String componentTypeParamName, String userId) {
-
validateUserExists(userId);
-
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
if (componentTypeEnum == null) {
log.debug("Cannot delete sub-category for component type {}", componentTypeParamName);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
-
NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY);
-
Either<SubCategoryDefinition, ActionStatus> deleteSubCategoryByType = elementOperation.deleteSubCategory(nodeTypeEnum, parentSubCategoryId);
if (deleteSubCategoryByType.isRight()) {
// auditing, logging here...
@@ -815,17 +767,13 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
public Either<GroupingDefinition, ResponseFormat> deleteGrouping(String groupingId, String componentTypeParamName, String userId) {
-
validateUserExists(userId);
-
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
if (componentTypeEnum == null) {
log.debug("Cannot delete grouping for component type {}", componentTypeParamName);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
-
NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.GROUPING);
-
Either<GroupingDefinition, ActionStatus> deleteGroupingByType = elementOperation.deleteGrouping(nodeTypeEnum, groupingId);
if (deleteGroupingByType.isRight()) {
// auditing, logging here...
@@ -838,26 +786,31 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
private Either<Boolean, ResponseFormat> validateUserRole(User user, ComponentTypeEnum componentTypeEnum) {
String role = user.getRole();
- boolean validAdminAction = role.equals(Role.ADMIN.name()) && (componentTypeEnum == ComponentTypeEnum.SERVICE || componentTypeEnum == ComponentTypeEnum.RESOURCE);
+ boolean validAdminAction =
+ role.equals(Role.ADMIN.name()) && (componentTypeEnum == ComponentTypeEnum.SERVICE || componentTypeEnum == ComponentTypeEnum.RESOURCE);
boolean validProductAction = role.equals(Role.PRODUCT_STRATEGIST.name()) && (componentTypeEnum == ComponentTypeEnum.PRODUCT);
-
if (!(validAdminAction || validProductAction)) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- log.debug("User not permitted to perform operation on category, userId = {}, role = {}, componentType = {}", user.getUserId(), role, componentTypeEnum);
+ log.debug("User not permitted to perform operation on category, userId = {}, role = {}, componentType = {}", user.getUserId(), role,
+ componentTypeEnum);
return Either.right(responseFormat);
}
return Either.left(true);
}
private Either<Boolean, ResponseFormat> validateComponentTypeForCategory(ComponentTypeEnum componentType, CategoryTypeEnum categoryType) {
- boolean validResourceAction = componentType == ComponentTypeEnum.RESOURCE && (categoryType == CategoryTypeEnum.CATEGORY || categoryType == CategoryTypeEnum.SUBCATEGORY);
+ boolean validResourceAction = componentType == ComponentTypeEnum.RESOURCE && (categoryType == CategoryTypeEnum.CATEGORY
+ || categoryType == CategoryTypeEnum.SUBCATEGORY);
boolean validServiceAction = componentType == ComponentTypeEnum.SERVICE && categoryType == CategoryTypeEnum.CATEGORY;
boolean validProductAction = componentType == ComponentTypeEnum.PRODUCT; // can
- // be
- // any
- // category
- // type
+ // be
+
+ // any
+
+ // category
+
+ // type
if (!(validResourceAction || validServiceAction || validProductAction)) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
log.debug("It's not allowed to create category type {} for component type {}", categoryType, componentType);
@@ -866,14 +819,16 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return Either.left(true);
}
- private Either<CategoryDefinition, ResponseFormat> validateCategoryExists(NodeTypeEnum nodeType, String categoryId, ComponentTypeEnum componentType) {
+ private Either<CategoryDefinition, ResponseFormat> validateCategoryExists(NodeTypeEnum nodeType, String categoryId,
+ ComponentTypeEnum componentType) {
Either<CategoryDefinition, ActionStatus> categoryByTypeAndId = elementOperation.getCategory(nodeType, categoryId);
if (categoryByTypeAndId.isRight()) {
log.debug("Failed to fetch parent category, parent categoryId {}", categoryId);
ActionStatus actionStatus = categoryByTypeAndId.right().value();
ResponseFormat responseFormat;
if (actionStatus == ActionStatus.COMPONENT_CATEGORY_NOT_FOUND) {
- responseFormat = componentsUtils.getResponseFormat(actionStatus, componentType.getValue().toLowerCase(), CategoryTypeEnum.CATEGORY.getValue(), "");
+ responseFormat = componentsUtils
+ .getResponseFormat(actionStatus, componentType.getValue().toLowerCase(), CategoryTypeEnum.CATEGORY.getValue(), "");
} else {
responseFormat = componentsUtils.getResponseFormat(actionStatus);
}
@@ -882,14 +837,16 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return Either.left(categoryByTypeAndId.left().value());
}
- private Either<SubCategoryDefinition, ResponseFormat> validateSubCategoryExists(NodeTypeEnum nodeType, String subCategoryId, ComponentTypeEnum componentType) {
+ private Either<SubCategoryDefinition, ResponseFormat> validateSubCategoryExists(NodeTypeEnum nodeType, String subCategoryId,
+ ComponentTypeEnum componentType) {
Either<SubCategoryDefinition, ActionStatus> subCategoryByTypeAndId = elementOperation.getSubCategory(nodeType, subCategoryId);
if (subCategoryByTypeAndId.isRight()) {
log.debug("Failed to fetch parent category, parent categoryId {}", subCategoryId);
ActionStatus actionStatus = subCategoryByTypeAndId.right().value();
ResponseFormat responseFormat;
if (actionStatus == ActionStatus.COMPONENT_CATEGORY_NOT_FOUND) {
- responseFormat = componentsUtils.getResponseFormat(actionStatus, componentType.getValue().toLowerCase(), CategoryTypeEnum.SUBCATEGORY.getValue(), "");
+ responseFormat = componentsUtils
+ .getResponseFormat(actionStatus, componentType.getValue().toLowerCase(), CategoryTypeEnum.SUBCATEGORY.getValue(), "");
} else {
responseFormat = componentsUtils.getResponseFormat(actionStatus);
}
@@ -898,22 +855,24 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return Either.left(subCategoryByTypeAndId.left().value());
}
- private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, AuditingActionEnum auditingAction, String componentType) {
+ private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, AuditingActionEnum auditingAction,
+ String componentType) {
componentsUtils.auditCategory(responseFormat, user, category, null, null, auditingAction, componentType);
}
- private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, String subCategory, AuditingActionEnum auditingAction, String componentType) {
+ private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, String subCategory,
+ AuditingActionEnum auditingAction, String componentType) {
componentsUtils.auditCategory(responseFormat, user, category, subCategory, null, auditingAction, componentType);
}
- private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, String subCategory, String grouping, AuditingActionEnum auditingAction, String componentType) {
+ private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, String subCategory, String grouping,
+ AuditingActionEnum auditingAction, String componentType) {
componentsUtils.auditCategory(responseFormat, user, category, subCategory, grouping, auditingAction, componentType);
}
/*
* New categories flow - end
*/
-
public Either<List<Tag>, ActionStatus> getAllTags(String userId) {
ActionStatus status = validateUserExistsActionStatus(userId);
if (ActionStatus.OK != status) {
@@ -942,19 +901,18 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return elementOperation.getDefaultHeatTimeout();
}
- public Either<Map<String, List<CatalogComponent>>, ResponseFormat> getCatalogComponents(String userId, List<OriginTypeEnum> excludeTypes) {
+ public Either<Map<String, List<CatalogComponent>>, ResponseFormat> getCatalogComponents(String userId, List<OriginTypeEnum> excludeTypes) {
try {
return toscaOperationFacade.getCatalogOrArchiveComponents(true, excludeTypes)
- .bimap(this::groupByComponentType,
- err -> componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(err)));
+ .bimap(this::groupByComponentType, err -> componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(err)));
} finally {
janusGraphDao.commit();
}
}
private Map<String, List<CatalogComponent>> groupByComponentType(List<CatalogComponent> components) {
- Map<String, List<CatalogComponent>> map = components.stream().collect(Collectors.groupingBy(cmpt -> cmptTypeToString(cmpt.getComponentType())));
-
+ Map<String, List<CatalogComponent>> map = components.stream()
+ .collect(Collectors.groupingBy(cmpt -> cmptTypeToString(cmpt.getComponentType())));
// fixed response for UI!!! UI need to receive always map!
if (map == null) {
map = new HashMap<>();
@@ -966,26 +924,26 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
private String cmptTypeToString(ComponentTypeEnum componentTypeEnum) {
switch (componentTypeEnum) {
- case RESOURCE:
- return RESOURCES;
- case SERVICE:
- return SERVICES;
- default:
- throw new IllegalStateException("resources or services only");
+ case RESOURCE:
+ return RESOURCES;
+ case SERVICE:
+ return SERVICES;
+ default:
+ throw new IllegalStateException("resources or services only");
}
}
- public Either<List<? extends Component>, ResponseFormat> getFilteredCatalogComponents(String assetType, Map<FilterKeyEnum, String> filters, String query) {
+ public Either<List<? extends Component>, ResponseFormat> getFilteredCatalogComponents(String assetType, Map<FilterKeyEnum, String> filters,
+ String query) {
ComponentTypeEnum assetTypeEnum = AssetTypeEnum.convertToComponentTypeEnum(assetType);
-
if (query != null) {
Optional<NameValuePair> invalidFilter = findInvalidFilter(query, assetTypeEnum);
if (invalidFilter.isPresent()) {
log.debug("getFilteredAssetList: invalid filter key");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_FILTER_KEY, invalidFilter.get().getName(), FilterKeyEnum.getValidFiltersByAssetType(assetTypeEnum).toString()));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_FILTER_KEY, invalidFilter.get().getName(),
+ FilterKeyEnum.getValidFiltersByAssetType(assetTypeEnum).toString()));
}
}
-
if (filters == null || filters.isEmpty()) {
Either<List<Component>, StorageOperationStatus> componentsList = toscaOperationFacade.getCatalogComponents(assetTypeEnum, null, false);
if (componentsList.isRight()) {
@@ -993,38 +951,35 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
return Either.left(componentsList.left().value());
}
-
Either<List<Component>, StorageOperationStatus> result = getFilteredComponents(filters, assetTypeEnum, false);
-
// category hierarchy mismatch or category/subCategory/distributionStatus not found
if (result.isRight()) {
List<String> params = getErrorResponseParams(filters, assetTypeEnum);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value()), params.get(0), params.get(1), params.get(2)));
+ return Either.right(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value()), params.get(0), params.get(1), params.get(2)));
}
if (result.left().value().isEmpty()) {// no assets found for requested
- // criteria
+
+ // criteria
return Either.right(componentsUtils.getResponseFormat(ActionStatus.NO_ASSETS_FOUND, assetType, query));
}
return Either.left(result.left().value());
}
- private Either<List<Component>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, ComponentTypeEnum assetType, boolean inTransaction) {
+ private Either<List<Component>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, ComponentTypeEnum assetType,
+ boolean inTransaction) {
Either<List<Component>, StorageOperationStatus> assetResult = Either.left(new LinkedList<>());
if (assetType == ComponentTypeEnum.RESOURCE) {
-
assetResult = getFilteredResources(filters, inTransaction);
-
} else if (assetType == ComponentTypeEnum.SERVICE) {
-
assetResult = getFilteredServices(filters, inTransaction);
}
return assetResult;
}
- private <T extends Component> Either<List<T>, StorageOperationStatus> getFilteredServices(Map<FilterKeyEnum, String> filters, boolean inTransaction) {
-
+ private <T extends Component> Either<List<T>, StorageOperationStatus> getFilteredServices(Map<FilterKeyEnum, String> filters,
+ boolean inTransaction) {
Either<List<T>, StorageOperationStatus> components = null;
-
String categoryName = filters.get(FilterKeyEnum.CATEGORY);
String distributionStatus = filters.get(FilterKeyEnum.DISTRIBUTION_STATUS);
DistributionStatusEnum distEnum = DistributionStatusEnum.findState(distributionStatus);
@@ -1032,7 +987,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
filters.remove(FilterKeyEnum.CATEGORY);
return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND);
}
-
if (categoryName != null) { // primary filter
components = fetchByCategoryOrSubCategoryName(categoryName, NodeTypeEnum.ServiceNewCategory, NodeTypeEnum.Service, inTransaction, null);
if (components.isLeft() && distEnum != null) {// secondary filter
@@ -1042,52 +996,44 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
filters.remove(FilterKeyEnum.DISTRIBUTION_STATUS);
return components;
}
-
Set<DistributionStatusEnum> distStatusSet = new HashSet<>();
distStatusSet.add(distEnum);
Either<List<Service>, StorageOperationStatus> servicesWithDistStatus = toscaOperationFacade.getServicesWithDistStatus(distStatusSet, null);
if (servicesWithDistStatus.isRight()) { // not found == empty list
return Either.left(new ArrayList<>());
}
-
return Either.left((List<T>) servicesWithDistStatus.left().value());
}
public Either<List<? extends Component>, ResponseFormat> getCatalogComponentsByUuidAndAssetType(String assetType, String uuid) {
-
if (assetType == null || uuid == null) {
log.debug("getCatalogComponentsByUuidAndAssetType: One of the function parameteres is null");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
-
ComponentTypeEnum assetTypeEnum = AssetTypeEnum.convertToComponentTypeEnum(assetType);
-
if (assetTypeEnum == null) {
log.debug("getCatalogComponentsByUuidAndAssetType: Corresponding ComponentTypeEnum not found");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
-
Map<GraphPropertyEnum, Object> additionalPropertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
-
switch (assetTypeEnum) {
- case RESOURCE:
- additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
- break;
- case SERVICE:
- additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
- break;
- default:
- log.debug("getCatalogComponentsByUuidAndAssetType: Corresponding ComponentTypeEnum not allowed for this API");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
-
- Either<List<Component>, StorageOperationStatus> componentsListByUuid = toscaOperationFacade.getComponentListByUuid(uuid, additionalPropertiesToMatch);
+ case RESOURCE:
+ additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ break;
+ case SERVICE:
+ additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ break;
+ default:
+ log.debug("getCatalogComponentsByUuidAndAssetType: Corresponding ComponentTypeEnum not allowed for this API");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ Either<List<Component>, StorageOperationStatus> componentsListByUuid = toscaOperationFacade
+ .getComponentListByUuid(uuid, additionalPropertiesToMatch);
if (componentsListByUuid.isRight()) {
log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue() + " fetching failed");
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(componentsListByUuid.right().value(), assetTypeEnum);
return Either.right(componentsUtils.getResponseFormat(actionStatus, uuid));
}
-
log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue() + assetTypeEnum.getValue() + "fetching successful");
return Either.left(componentsListByUuid.left().value());
}
@@ -1135,13 +1081,11 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
public Either<List<Component>, StorageOperationStatus> getFilteredResources(Map<FilterKeyEnum, String> filters, boolean inTransaction) {
-
String subCategoryName = filters.get(FilterKeyEnum.SUB_CATEGORY);
String categoryName = filters.get(FilterKeyEnum.CATEGORY);
ResourceTypeEnum resourceType = ResourceTypeEnum.getType(filters.get(FilterKeyEnum.RESOURCE_TYPE));
Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, StorageOperationStatus> subcategories = null;
Optional<ImmutablePair<SubCategoryData, GraphEdge>> subCategoryData;
-
if (categoryName != null) {
subcategories = getAllSubCategories(categoryName);
if (subcategories.isRight()) {
@@ -1155,10 +1099,11 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
if (!subCategoryData.isPresent()) {
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
- return fetchByCategoryOrSubCategoryUid(subCategoryData.get().getLeft().getUniqueId(), NodeTypeEnum.Resource, inTransaction, resourceType);
+ return fetchByCategoryOrSubCategoryUid(subCategoryData.get().getLeft().getUniqueId(), NodeTypeEnum.Resource, inTransaction,
+ resourceType);
}
-
- return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, NodeTypeEnum.Resource, inTransaction, resourceType);
+ return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, NodeTypeEnum.Resource, inTransaction,
+ resourceType);
}
if (subcategories != null) {
return fetchByMainCategory(subcategories.left().value(), inTransaction, resourceType);
@@ -1167,12 +1112,12 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
private Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, StorageOperationStatus> getAllSubCategories(String categoryName) {
- Either<CategoryData, StorageOperationStatus> categoryResult = elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class);
+ Either<CategoryData, StorageOperationStatus> categoryResult = elementOperation
+ .getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class);
if (categoryResult.isRight()) {
return Either.right(categoryResult.right().value());
}
CategoryData categoryData = categoryResult.left().value();
-
Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao
.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), (String) categoryData.getUniqueId(),
GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class);
@@ -1182,12 +1127,17 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return Either.left(childrenNodes.left().value());
}
- private Optional<ImmutablePair<SubCategoryData, GraphEdge>> validateCategoryHierarcy(List<ImmutablePair<SubCategoryData, GraphEdge>> childNodes, String subCategoryName) {
- Predicate<ImmutablePair<SubCategoryData, GraphEdge>> matchName = p -> p.getLeft().getSubCategoryDataDefinition().getName().equals(subCategoryName);
+ private Optional<ImmutablePair<SubCategoryData, GraphEdge>> validateCategoryHierarcy(List<ImmutablePair<SubCategoryData, GraphEdge>> childNodes,
+ String subCategoryName) {
+ Predicate<ImmutablePair<SubCategoryData, GraphEdge>> matchName = p -> p.getLeft().getSubCategoryDataDefinition().getName()
+ .equals(subCategoryName);
return childNodes.stream().filter(matchName).findAny();
}
- protected <T extends Component> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryUid(String categoryUid, NodeTypeEnum categoryType, boolean inTransaction, ResourceTypeEnum resourceType) {
+ protected <T extends Component> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryUid(String categoryUid,
+ NodeTypeEnum categoryType,
+ boolean inTransaction,
+ ResourceTypeEnum resourceType) {
try {
return collectComponents(categoryType, categoryUid, resourceType);
} finally {
@@ -1197,7 +1147,11 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
}
- protected <T extends Component> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName, NodeTypeEnum categoryType, NodeTypeEnum neededType, boolean inTransaction, ResourceTypeEnum resourceType) {
+ protected <T extends Component> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName,
+ NodeTypeEnum categoryType,
+ NodeTypeEnum neededType,
+ boolean inTransaction,
+ ResourceTypeEnum resourceType) {
List<T> components = new ArrayList<>();
try {
Class categoryClazz = categoryType == NodeTypeEnum.ServiceNewCategory ? CategoryData.class : SubCategoryData.class;
@@ -1211,11 +1165,11 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
Either<List<T>, StorageOperationStatus> result = collectComponents(neededType, category.getUniqueId(), resourceType);
if (result.isRight() && result.right().value() != StorageOperationStatus.NOT_FOUND) {
return result;
- } else if (result.isLeft()){
+ } else if (result.isLeft()) {
components.addAll(result.left().value());
}
}
- if (components.isEmpty()){
+ if (components.isEmpty()) {
return Either.right(StorageOperationStatus.NOT_FOUND);
}
return Either.left(components);
@@ -1226,36 +1180,35 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
}
-
- private <T extends Component> Either<List<T>, StorageOperationStatus> collectComponents(NodeTypeEnum neededType, String categoryUid, ResourceTypeEnum resourceType) {
+ private <T extends Component> Either<List<T>, StorageOperationStatus> collectComponents(NodeTypeEnum neededType, String categoryUid,
+ ResourceTypeEnum resourceType) {
List<T> components = new ArrayList<>();
Either<GraphVertex, JanusGraphOperationStatus> categoryVertexById = janusGraphDao.getVertexById(categoryUid, JsonParseFlagEnum.NoParse);
- if (categoryVertexById.isRight()){
+ if (categoryVertexById.isRight()) {
JanusGraphOperationStatus status = categoryVertexById.right().value();
log.debug("#collectComponents Failed to get category vertex with uid {}, status is {}.", categoryUid, status);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
GraphVertex categoryVertex = categoryVertexById.left().value();
- Either<List<GraphVertex>, JanusGraphOperationStatus> componentsVertices = janusGraphDao.getParentVertices(categoryVertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.ParseMetadata);
- if (componentsVertices.isRight()){
+ Either<List<GraphVertex>, JanusGraphOperationStatus> componentsVertices = janusGraphDao
+ .getParentVertices(categoryVertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.ParseMetadata);
+ if (componentsVertices.isRight()) {
JanusGraphOperationStatus status = componentsVertices.right().value();
log.debug("#collectComponents Failed to get components vertices of category {}, status is {}.", categoryVertex, status);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
- List<ComponentMetadataDataDefinition> componentsMetadataDataDefinition = componentsVertices.left().value()
- .stream()
- .filter(Objects::nonNull)
- .filter(componentsVertex -> Objects.nonNull(componentsVertex.getType()))
- .map(ModelConverter::convertToComponentMetadataDataDefinition)
- .collect(Collectors.toList());
+ List<ComponentMetadataDataDefinition> componentsMetadataDataDefinition = componentsVertices.left().value().stream().filter(Objects::nonNull)
+ .filter(componentsVertex -> Objects.nonNull(componentsVertex.getType())).map(ModelConverter::convertToComponentMetadataDataDefinition)
+ .collect(Collectors.toList());
for (ComponentMetadataDataDefinition component : componentsMetadataDataDefinition) {
boolean isHighest = isTrue(component.isHighestVersion());
boolean isMatchingResourceType = isMatchingByResourceType(neededType, resourceType, component);
boolean isDeleted = isTrue(component.isDeleted());
boolean isArchived = isTrue(component.isArchived());
if (isHighest && isMatchingResourceType && !isDeleted && !isArchived) {
- Either<T, StorageOperationStatus> result = toscaOperationFacade.getToscaElement(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
- if (result.isRight()) {
+ Either<T, StorageOperationStatus> result = toscaOperationFacade
+ .getToscaElement(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
+ if (result.isRight()) {
return Either.right(result.right().value());
}
components.add(result.left().value());
@@ -1264,8 +1217,8 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return Either.left(components);
}
- private boolean isMatchingByResourceType(NodeTypeEnum componentType, ResourceTypeEnum resourceType, ComponentMetadataDataDefinition componentData) {
-
+ private boolean isMatchingByResourceType(NodeTypeEnum componentType, ResourceTypeEnum resourceType,
+ ComponentMetadataDataDefinition componentData) {
boolean isMatching;
if (componentType == NodeTypeEnum.Resource) {
if (resourceType == null) {
@@ -1279,12 +1232,12 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return isMatching;
}
- private <T extends Component> Either<List<T>, StorageOperationStatus> fetchByMainCategory(List<ImmutablePair<SubCategoryData, GraphEdge>> subcategories, boolean inTransaction, ResourceTypeEnum resourceType) {
+ private <T extends Component> Either<List<T>, StorageOperationStatus> fetchByMainCategory(
+ List<ImmutablePair<SubCategoryData, GraphEdge>> subcategories, boolean inTransaction, ResourceTypeEnum resourceType) {
List<T> components = new ArrayList<>();
-
for (ImmutablePair<SubCategoryData, GraphEdge> subCategory : subcategories) {
- Either<List<T>, StorageOperationStatus> fetched = fetchByCategoryOrSubCategoryUid(subCategory.getLeft().getUniqueId(), NodeTypeEnum.Resource,
- inTransaction, resourceType);
+ Either<List<T>, StorageOperationStatus> fetched = fetchByCategoryOrSubCategoryUid(subCategory.getLeft().getUniqueId(),
+ NodeTypeEnum.Resource, inTransaction, resourceType);
if (fetched.isRight()) {
continue;
}
@@ -1299,8 +1252,10 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
Wrapper<StorageOperationStatus> statusWrapper = new Wrapper<>();
Either<List<Component>, StorageOperationStatus> result;
try {
- ComponentParametersView fetchUsersAndCategoriesFilter = new ComponentParametersView(Arrays.asList(ComponentFieldsEnum.USERS.getValue(), ComponentFieldsEnum.CATEGORIES.getValue()));
- Either<List<Component>, StorageOperationStatus> getResources = toscaOperationFacade.fetchMetaDataByResourceType(resourceType, fetchUsersAndCategoriesFilter);
+ ComponentParametersView fetchUsersAndCategoriesFilter = new ComponentParametersView(
+ Arrays.asList(ComponentFieldsEnum.USERS.getValue(), ComponentFieldsEnum.CATEGORIES.getValue()));
+ Either<List<Component>, StorageOperationStatus> getResources = toscaOperationFacade
+ .fetchMetaDataByResourceType(resourceType, fetchUsersAndCategoriesFilter);
if (getResources.isRight()) {
status = getResources.right().value();
if (status != StorageOperationStatus.NOT_FOUND) {
@@ -1324,15 +1279,11 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
}
-
public CatalogUpdateTimestamp getCatalogUpdateTime(String userId) {
-
- try{
+ try {
return toscaOperationFacade.getCatalogTimes();
-
} finally {
janusGraphDao.commit();
}
-
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java
index 2c824c8e23..acd19e4bee 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,10 +17,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
import org.openecomp.sdc.be.components.impl.lock.LockingTransactional;
import org.openecomp.sdc.be.components.validation.AccessValidations;
@@ -34,10 +36,6 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.common.log.wrappers.Logger;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
/**
* Created by yavivi on 04/02/2018.
*/
@@ -45,20 +43,21 @@ import java.util.Map;
public class ExternalRefsBusinessLogic {
private static final Logger log = Logger.getLogger(ExternalRefsBusinessLogic.class);
-
private final ExternalReferencesOperation externalReferencesOperation;
private final ToscaOperationFacade toscaOperationFacade;
private final AccessValidations accessValidations;
private final ComponentLocker componentLocker;
- public ExternalRefsBusinessLogic(ExternalReferencesOperation externalReferencesOperation, ToscaOperationFacade toscaOperationFacade, AccessValidations accessValidations, ComponentLocker componentLocker) {
+ public ExternalRefsBusinessLogic(ExternalReferencesOperation externalReferencesOperation, ToscaOperationFacade toscaOperationFacade,
+ AccessValidations accessValidations, ComponentLocker componentLocker) {
this.externalReferencesOperation = externalReferencesOperation;
this.toscaOperationFacade = toscaOperationFacade;
this.accessValidations = accessValidations;
this.componentLocker = componentLocker;
}
- public Either<List<String>, ActionStatus> getExternalReferences(String assetUuid, String version, String componentInstanceName, String objectType){
+ public Either<List<String>, ActionStatus> getExternalReferences(String assetUuid, String version, String componentInstanceName,
+ String objectType) {
Either<Component, StorageOperationStatus> componentsResult = toscaOperationFacade.getComponentByUuidAndVersion(assetUuid, version);
if (componentsResult == null || componentsResult.isRight()) {
return Either.right(ActionStatus.RESOURCE_NOT_FOUND);
@@ -67,16 +66,15 @@ public class ExternalRefsBusinessLogic {
return this.externalReferencesOperation.getExternalReferences(component.getUniqueId(), componentInstanceName, objectType);
}
- public Either<Map<String, List<String>>, ActionStatus> getExternalReferences(String assetUuid, String version, String objectType){
+ public Either<Map<String, List<String>>, ActionStatus> getExternalReferences(String assetUuid, String version, String objectType) {
Either<Component, StorageOperationStatus> componentsResult = toscaOperationFacade.getComponentByUuidAndVersion(assetUuid, version);
if (componentsResult == null || componentsResult.isRight()) {
return Either.right(ActionStatus.RESOURCE_NOT_FOUND);
}
-
Component component = componentsResult.left().value();
-
- Either<Map<String, List<String>>, ActionStatus> externalReferencesResult = this.externalReferencesOperation.getExternalReferences(component.getUniqueId(), objectType);
- if (externalReferencesResult.isRight()){
+ Either<Map<String, List<String>>, ActionStatus> externalReferencesResult = this.externalReferencesOperation
+ .getExternalReferences(component.getUniqueId(), objectType);
+ if (externalReferencesResult.isRight()) {
return Either.right(externalReferencesResult.right().value());
} else {
return Either.left(externalReferencesResult.left().value());
@@ -84,36 +82,38 @@ public class ExternalRefsBusinessLogic {
}
@LockingTransactional
- public Either<String, ActionStatus> addExternalReference(String componentId, ComponentTypeEnum componentType, String userId, String componentInstanceName, String objectType, ExternalRefDTO ref) {
+ public Either<String, ActionStatus> addExternalReference(String componentId, ComponentTypeEnum componentType, String userId,
+ String componentInstanceName, String objectType, ExternalRefDTO ref) {
return this.doAction(componentId, componentType, userId, "POST", componentId, componentInstanceName, objectType, ref.getReferenceUUID(), "");
}
@LockingTransactional
- public Either<String, ActionStatus> deleteExternalReference(String componentId, ComponentTypeEnum componentType, String userId, String componentInstanceName, String objectType, String reference) {
+ public Either<String, ActionStatus> deleteExternalReference(String componentId, ComponentTypeEnum componentType, String userId,
+ String componentInstanceName, String objectType, String reference) {
return this.doAction(componentId, componentType, userId, "DELETE", componentId, componentInstanceName, objectType, reference, "");
}
@LockingTransactional
- public Either<String, ActionStatus> updateExternalReference(String componentId, ComponentTypeEnum componentType, String userId, String componentInstanceName, String objectType, String oldRefValue, String newRefValue) {
+ public Either<String, ActionStatus> updateExternalReference(String componentId, ComponentTypeEnum componentType, String userId,
+ String componentInstanceName, String objectType, String oldRefValue,
+ String newRefValue) {
return this.doAction(componentId, componentType, userId, "PUT", componentId, componentInstanceName, objectType, oldRefValue, newRefValue);
}
- public String fetchComponentUniqueIdByUuid(String uuid, ComponentTypeEnum componentType){
- Either<Component, StorageOperationStatus> latestServiceByUuid = toscaOperationFacade.getLatestComponentByUuid(uuid, createPropsToMatch(componentType));
- if (latestServiceByUuid == null || latestServiceByUuid.isRight()){
+ public String fetchComponentUniqueIdByUuid(String uuid, ComponentTypeEnum componentType) {
+ Either<Component, StorageOperationStatus> latestServiceByUuid = toscaOperationFacade
+ .getLatestComponentByUuid(uuid, createPropsToMatch(componentType));
+ if (latestServiceByUuid == null || latestServiceByUuid.isRight()) {
throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, uuid);
}
-
//Get Component Unique ID
Component component = latestServiceByUuid.left().value();
return component.getUniqueId();
}
-
- public Either<String, ActionStatus> doAction(String componentId, ComponentTypeEnum componentType, String userId, String action, String uuid, String componentInstanceName, String objectType, String ref1, String ref2){
-
+ public Either<String, ActionStatus> doAction(String componentId, ComponentTypeEnum componentType, String userId, String action, String uuid,
+ String componentInstanceName, String objectType, String ref1, String ref2) {
accessValidations.validateUserCanWorkOnComponent(componentId, componentType, userId, action + " EXTERNAL REF");
-
switch (action) {
case "POST":
return this.externalReferencesOperation.addExternalReferenceWithCommit(componentId, componentInstanceName, objectType, ref1);
@@ -124,7 +124,6 @@ public class ExternalRefsBusinessLogic {
default:
return Either.right(ActionStatus.GENERAL_ERROR);
}
-
}
private Map<GraphPropertyEnum, Object> createPropsToMatch(ComponentTypeEnum componentType) {
@@ -132,5 +131,4 @@ public class ExternalRefsBusinessLogic {
propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
return propertiesToMatch;
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GenericArtifactBrowserBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GenericArtifactBrowserBusinessLogic.java
index 4f092c6bd9..1f9aad5c25 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GenericArtifactBrowserBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GenericArtifactBrowserBusinessLogic.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import com.google.gson.Gson;
@@ -27,6 +26,8 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
+import java.io.IOException;
+import java.lang.reflect.Type;
import org.onap.sdc.gab.GABService;
import org.onap.sdc.gab.GABServiceImpl;
import org.onap.sdc.gab.model.GABQuery;
@@ -41,24 +42,18 @@ import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
import org.springframework.beans.factory.annotation.Autowired;
-import java.io.IOException;
-import java.lang.reflect.Type;
-
@org.springframework.stereotype.Component
public class GenericArtifactBrowserBusinessLogic extends BaseBusinessLogic {
private GABService gabService;
@Autowired
- public GenericArtifactBrowserBusinessLogic(IElementOperation elementDao,
- IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation,
- IGroupTypeOperation groupTypeOperation,
- InterfaceOperation interfaceOperation,
- InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
- ArtifactsOperations artifactToscaOperation) {
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
- interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+ public GenericArtifactBrowserBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
+ IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation,
+ InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+ ArtifactsOperations artifactToscaOperation) {
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+ artifactToscaOperation);
gabService = new GABServiceImpl();
}
@@ -67,17 +62,15 @@ public class GenericArtifactBrowserBusinessLogic extends BaseBusinessLogic {
return createGsonForGABResult().toJson(gabResults);
}
- private Gson createGsonForGABResult(){
- return new GsonBuilder().setPrettyPrinting()
- .registerTypeAdapter(GABResult.class, new GABResultSerializer())
- .registerTypeAdapter(GABResults.class, new GABResultsSerializer())
- .create();
+ private Gson createGsonForGABResult() {
+ return new GsonBuilder().setPrettyPrinting().registerTypeAdapter(GABResult.class, new GABResultSerializer())
+ .registerTypeAdapter(GABResults.class, new GABResultsSerializer()).create();
}
private class GABResultsSerializer implements JsonSerializer<GABResults> {
+
@Override
- public JsonElement serialize(GABResults gabResults, Type type,
- JsonSerializationContext jsonSerializationContext) {
+ public JsonElement serialize(GABResults gabResults, Type type, JsonSerializationContext jsonSerializationContext) {
JsonObject result = new JsonObject();
JsonArray jsonArray = new JsonArray();
gabResults.getRows().stream().map(jsonSerializationContext::serialize).forEach(jsonArray::add);
@@ -87,6 +80,7 @@ public class GenericArtifactBrowserBusinessLogic extends BaseBusinessLogic {
}
private class GABResultSerializer implements JsonSerializer<GABResult> {
+
@Override
public JsonElement serialize(GABResult gabResult, Type type, JsonSerializationContext jsonSerializationContext) {
JsonObject result = new JsonObject();
@@ -94,5 +88,4 @@ public class GenericArtifactBrowserBusinessLogic extends BaseBusinessLogic {
return result;
}
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java
index fe9d44837b..fee80c65c1 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java
@@ -19,10 +19,26 @@
* Modifications copyright (c) 2019 Nokia
* ================================================================================
*/
-
package org.openecomp.sdc.be.components.impl;
+import static java.util.stream.Collectors.toList;
+import static org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter.extractCapabilitiesFromGroups;
+import static org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter.extractCapabilityPropertiesFromGroups;
+
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.Set;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FilenameUtils;
@@ -89,68 +105,47 @@ import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.Set;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
-import static java.util.stream.Collectors.toList;
-import static org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter.extractCapabilitiesFromGroups;
-import static org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter.extractCapabilityPropertiesFromGroups;
-
@org.springframework.stereotype.Component("groupBusinessLogic")
public class GroupBusinessLogic extends BaseBusinessLogic {
public static final String GROUP_DELIMITER_REGEX = "\\.\\.";
-
public static final String INITIAL_VERSION = "0.0";
-
private static final String ADDING_GROUP = "AddingGroup";
-
private static final String CREATE_GROUP = "CreateGroup";
-
private static final String UPDATE_GROUP = "UpdateGroup";
-
private static final String GET_GROUP = "GetGroup";
-
private static final String DELETE_GROUP = "DeleteGroup";
-
private static final Logger log = Logger.getLogger(GroupBusinessLogic.class);
-
private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(GroupBusinessLogic.class.getName());
-
private final AccessValidations accessValidations;
private final PolicyTargetsUpdateHandler policyTargetsUpdateHandler;
-
@javax.annotation.Resource
private final GroupsOperation groupsOperation;
-
@Autowired
- public GroupBusinessLogic(IElementOperation elementDao,
- IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation,
- IGroupTypeOperation groupTypeOperation,
- InterfaceOperation interfaceOperation,
- InterfaceLifecycleOperation interfaceLifecycleTypeOperation, AccessValidations accessValidations,
- GroupsOperation groupsOperation, PolicyTargetsUpdateHandler policyTargetsUpdateHandler,
- ArtifactsOperations artifactToscaOperation) {
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
- interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+ public GroupBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+ IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
+ InterfaceLifecycleOperation interfaceLifecycleTypeOperation, AccessValidations accessValidations,
+ GroupsOperation groupsOperation, PolicyTargetsUpdateHandler policyTargetsUpdateHandler,
+ ArtifactsOperations artifactToscaOperation) {
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+ artifactToscaOperation);
this.accessValidations = accessValidations;
this.groupsOperation = groupsOperation;
this.policyTargetsUpdateHandler = policyTargetsUpdateHandler;
}
+ private static boolean groupExistsInComponent(String groupDefinitionName, Component component) {
+ boolean found = false;
+ List<GroupDefinition> groups = component.getGroups();
+ if (CollectionUtils.isNotEmpty(groups)) {
+ found = groups.stream()
+ .filter(p -> (p.getName().equalsIgnoreCase(groupDefinitionName)) || p.getInvariantName().equalsIgnoreCase(groupDefinitionName))
+ .findFirst().orElse(null) != null;
+ }
+ return found;
+ }
+
private String getComponentTypeForResponse(org.openecomp.sdc.be.model.Component component) {
String componentTypeForResponse = "SERVICE";
if (component instanceof Resource) {
@@ -167,26 +162,23 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
* @return
*/
private Either<Boolean, ResponseFormat> verifyArtifactsBelongsToComponent(Component component, List<String> artifacts, String context) {
-
if (CollectionUtils.isEmpty(artifacts)) {
return Either.left(true);
}
-
Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
if (MapUtils.isEmpty(deploymentArtifacts)) {
- BeEcompErrorManager.getInstance().logInvalidInputError(context, "No deployment artifact found under component " + component.getNormalizedName(), ErrorSeverity.INFO);
+ BeEcompErrorManager.getInstance()
+ .logInvalidInputError(context, "No deployment artifact found under component " + component.getNormalizedName(), ErrorSeverity.INFO);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
-
List<String> currentArtifacts = deploymentArtifacts.values().stream().map(ArtifactDefinition::getUniqueId).collect(toList());
log.debug("The deployment artifacts of component {} are {}", component.getNormalizedName(), deploymentArtifacts);
if (!currentArtifacts.containsAll(artifacts)) {
- BeEcompErrorManager.getInstance().logInvalidInputError(context, "Not all artifacts belongs to component " + component.getNormalizedName(), ErrorSeverity.INFO);
+ BeEcompErrorManager.getInstance()
+ .logInvalidInputError(context, "Not all artifacts belongs to component " + component.getNormalizedName(), ErrorSeverity.INFO);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
-
return Either.left(true);
-
}
/**
@@ -197,43 +189,38 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
* @param memberToscaTypes
* @return
*/
- private Either<Boolean, ResponseFormat> verifyComponentInstancesAreValidMembers(Component component, String groupName, Map<String, String> groupMembers, List<String> memberToscaTypes) {
-
+ private Either<Boolean, ResponseFormat> verifyComponentInstancesAreValidMembers(Component component, String groupName,
+ Map<String, String> groupMembers, List<String> memberToscaTypes) {
if (MapUtils.isEmpty(groupMembers)) {
return Either.left(true);
}
-
if (CollectionUtils.isEmpty(memberToscaTypes)) {
return Either.left(true);
}
-
List<ComponentInstance> componentInstances = component.getComponentInstances();
if (CollectionUtils.isNotEmpty(componentInstances)) {
- Map<String, ComponentInstance> compInstUidToCompInstMap = componentInstances.stream().collect(Collectors.toMap(ComponentInstance::getUniqueId, p -> p));
-
+ Map<String, ComponentInstance> compInstUidToCompInstMap = componentInstances.stream()
+ .collect(Collectors.toMap(ComponentInstance::getUniqueId, p -> p));
Set<String> allCompInstances = compInstUidToCompInstMap.keySet();
-
for (Entry<String, String> groupMember : groupMembers.entrySet()) {
String compName = groupMember.getKey();
String compUid = groupMember.getValue();
-
if (!allCompInstances.contains(compUid)) {
/*
* %1 - member name %2 - group name %3 - VF name %4 - component type [VF ]
*/
String componentTypeForResponse = getComponentTypeForResponse(component);
-
- BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "Not all group members exists under the component", ErrorSeverity.INFO);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, compName, groupName, component.getNormalizedName(), componentTypeForResponse));
+ BeEcompErrorManager.getInstance()
+ .logInvalidInputError(CREATE_GROUP, "Not all group members exists under the component", ErrorSeverity.INFO);
+ return Either.right(componentsUtils
+ .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, compName, groupName, component.getNormalizedName(),
+ componentTypeForResponse));
}
}
}
-
return Either.left(true);
}
-
-
/**
* Update GroupDefinition metadata
*
@@ -244,8 +231,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
* @param inTransaction
* @return
*/
- public Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType, GroupDefinition updatedGroup, boolean inTransaction , boolean shouldLock) {
-
+ public Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType,
+ GroupDefinition updatedGroup, boolean inTransaction,
+ boolean shouldLock) {
Either<GroupDefinition, ResponseFormat> result = null;
boolean failed = false;
try {
@@ -257,35 +245,40 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
validateCanWorkOnComponent(component, user.getUserId());
List<GroupDefinition> currentGroups = component.getGroups();
if (CollectionUtils.isEmpty(currentGroups)) {
- log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue()));
+ log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(),
+ component.getName(), ActionStatus.GROUP_IS_MISSING);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(),
+ component.getComponentType().getValue()));
return result;
}
// Validate groups exists in the component
- Optional<GroupDefinition> currentGroupOpt = currentGroups.stream().filter(g -> g.getUniqueId().equals(updatedGroup.getUniqueId())).findAny();
+ Optional<GroupDefinition> currentGroupOpt = currentGroups.stream().filter(g -> g.getUniqueId().equals(updatedGroup.getUniqueId()))
+ .findAny();
if (!currentGroupOpt.isPresent()) {
- log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue()));
+ log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(),
+ component.getName(), ActionStatus.GROUP_IS_MISSING);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(),
+ component.getComponentType().getValue()));
return result;
}
GroupDefinition currentGroup = currentGroupOpt.get();
- if ( shouldLock ){
+ if (shouldLock) {
lockComponent(componentId, component, "Update GroupDefinition Metadata");
}
// Validate group type is vfModule
if (currentGroup.getType().equals(Constants.GROUP_TOSCA_HEAT)) {
- log.error("Failed to update the metadata of group {}. Group type is {} and cannot be updated", currentGroup.getName(), currentGroup.getType());
+ log.error("Failed to update the metadata of group {}. Group type is {} and cannot be updated", currentGroup.getName(),
+ currentGroup.getType());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, updatedGroup.getType());
result = Either.right(responseFormat);
return result;
}
result = updateGroupMetadata(component, currentGroup, updatedGroup);
return result;
-
- }catch (ComponentException e){
+ } catch (ComponentException e) {
failed = true;
throw e;
- }finally {
+ } finally {
if (!failed) {
janusGraphDao.commit();
} else {
@@ -297,10 +290,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
}
- private Either<GroupDefinition, ResponseFormat> updateGroupMetadata(Component component, GroupDefinition currentGroup, GroupDefinition updatedGroup) {
+ private Either<GroupDefinition, ResponseFormat> updateGroupMetadata(Component component, GroupDefinition currentGroup,
+ GroupDefinition updatedGroup) {
String currentGroupName = currentGroup.getName();
Either<GroupDefinition, ResponseFormat> result = validateAndUpdateGroupMetadata(currentGroup, updatedGroup);
-
if (result.isRight()) {
log.debug("Failed to validate a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName());
}
@@ -338,14 +331,12 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
ResponseFormat errorResponse = response.right().value();
return Either.right(errorResponse);
}
-
// Do not allow to update GroupDefinition version directly.
String versionUpdated = groupUpdate.getVersion();
String versionCurrent = currentGroup.getVersion();
if (versionUpdated != null && !versionCurrent.equals(versionUpdated)) {
log.info("update Group: recived request to update version to {} the field is not updatable ignoring.", versionUpdated);
}
-
return Either.left(currentGroup);
}
@@ -360,7 +351,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
String nameUpdated = groupUpdate.getName();
String nameCurrent = currentGroup.getName();
if (!nameCurrent.equals(nameUpdated)) {
- Either<Boolean, ResponseFormat> validatNameResponse = validateGroupName(currentGroup.getName(), groupUpdate.getName() ,true);
+ Either<Boolean, ResponseFormat> validatNameResponse = validateGroupName(currentGroup.getName(), groupUpdate.getName(), true);
if (validatNameResponse.isRight()) {
ResponseFormat errorRespons = validatNameResponse.right().value();
return Either.right(errorRespons);
@@ -371,44 +362,41 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
/**
- * Validate that group name to update is valid (same as current group name except for middle part). For example: Current group name: MyResource..MyDesc..Module-1 Group to update: MyResource..MyDesc2..Module-1 Verify that only the second part
- * MyDesc was changed.
+ * Validate that group name to update is valid (same as current group name except for middle part). For example: Current group name:
+ * MyResource..MyDesc..Module-1 Group to update: MyResource..MyDesc2..Module-1 Verify that only the second part MyDesc was changed.
*
* @param currentGroupName
* @param groupUpdateName
* @return
*/
- private Either<Boolean, ResponseFormat> validateGroupName(String currentGroupName, String groupUpdateName , boolean isforceNameModification) {
+ private Either<Boolean, ResponseFormat> validateGroupName(String currentGroupName, String groupUpdateName, boolean isforceNameModification) {
try {
// Check if the group name is in old format.
if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupUpdateName).matches()) {
log.error("Group name {} is in old format", groupUpdateName);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME, groupUpdateName));
}
-
// Check that name pats 1 and 3 did not changed (only the second
+
// part can be changed)
+
// But verify before that the current group format is the new one
if (!Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(currentGroupName).matches()) {
String[] split1 = currentGroupName.split(GROUP_DELIMITER_REGEX);
String currentResourceName = split1[0];
String currentCounter = split1[2];
-
String[] split2 = groupUpdateName.split(GROUP_DELIMITER_REGEX);
String groupUpdateResourceName = split2[0];
String groupUpdateCounter = split2[2];
- if (!isforceNameModification){ //if not forced ,allow name prefix&suffix validation [no changes]
+ if (!isforceNameModification) { //if not forced ,allow name prefix&suffix validation [no changes]
if (!currentResourceName.equals(groupUpdateResourceName)) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentResourceName));
}
-
if (!currentCounter.equals(groupUpdateCounter)) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentCounter));
}
}
-
}
-
return Either.left(true);
} catch (Exception e) {
log.error("Error valiadting group name", e);
@@ -416,7 +404,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
}
-
/**
* associate artifacts to a given group
*
@@ -426,59 +413,54 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
* @param inTransaction
* @return
*/
- public Either<GroupDefinitionInfo, ResponseFormat> getGroupWithArtifactsById(ComponentTypeEnum componentType, String componentId, String groupId, String userId, boolean inTransaction) {
-
+ public Either<GroupDefinitionInfo, ResponseFormat> getGroupWithArtifactsById(ComponentTypeEnum componentType, String componentId, String groupId,
+ String userId, boolean inTransaction) {
Either<GroupDefinitionInfo, ResponseFormat> result = null;
-
// Validate user exist
validateUserExists(userId);
// Validate component exist
org.openecomp.sdc.be.model.Component component = null;
-
try {
ComponentParametersView componentParametersView = new ComponentParametersView();
componentParametersView.disableAll();
componentParametersView.setIgnoreGroups(false);
componentParametersView.setIgnoreArtifacts(false);
componentParametersView.setIgnoreUsers(false);
-
component = validateComponentExists(componentId, componentType, componentParametersView);
-
Either<GroupDefinition, StorageOperationStatus> groupEither = findGroupOnComponent(component, groupId);
-
if (groupEither.isRight()) {
log.debug("Failed to find group {} under component {}", groupId, component.getUniqueId());
- BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "group " + groupId + " not found under component " + component.getUniqueId(), ErrorSeverity.INFO);
+ BeEcompErrorManager.getInstance()
+ .logInvalidInputError(GET_GROUP, "group " + groupId + " not found under component " + component.getUniqueId(),
+ ErrorSeverity.INFO);
String componentTypeForResponse = getComponentTypeForResponse(component);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupId, component.getSystemName(), componentTypeForResponse));
+ result = Either.right(
+ componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupId, component.getSystemName(), componentTypeForResponse));
return result;
}
GroupDefinition group = groupEither.left().value();
-
List<GroupProperty> props = group.convertToGroupProperties();
Boolean isBase = isBaseProp(component, props);
-
List<ArtifactDefinitionInfo> artifacts = new ArrayList<>();
List<ArtifactDefinition> artifactsFromComponent = new ArrayList<>();
List<String> artifactsIds = group.getArtifacts();
-
Map<String, ArtifactDefinition> deploymentArtifacts = null;
if (MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
- deploymentArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, a -> a));
+ deploymentArtifacts = component.getDeploymentArtifacts().values().stream()
+ .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, a -> a));
}
-
if (artifactsIds != null && !artifactsIds.isEmpty()) {
for (String id : artifactsIds) {
if (deploymentArtifacts == null || !deploymentArtifacts.containsKey(id)) {
log.debug("Failed to get artifact {} . Status is {} ", id, StorageOperationStatus.NOT_FOUND);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND));
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND));
result = Either.right(responseFormat);
return result;
}
artifactsFromComponent.add(deploymentArtifacts.get(id));
}
addArtifactsToList(artifacts, artifactsFromComponent);
-
}
GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group);
resultInfo.setIsBase(isBase);
@@ -486,17 +468,14 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
resultInfo.setArtifacts(artifacts);
}
result = Either.left(resultInfo);
-
return result;
-
} finally {
closeTransaction(inTransaction, result);
}
-
}
private void addArtifactsToList(List<ArtifactDefinitionInfo> artifacts, List<ArtifactDefinition> artifactsFromComponent) {
- artifactsFromComponent.forEach(a-> artifacts.add(new ArtifactDefinitionInfo(a)));
+ artifactsFromComponent.forEach(a -> artifacts.add(new ArtifactDefinitionInfo(a)));
}
private Boolean isBaseProp(Component component, List<GroupProperty> props) {
@@ -506,16 +485,15 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (isBasePropOp.isPresent()) {
GroupProperty propIsBase = isBasePropOp.get();
isBase = Boolean.parseBoolean(propIsBase.getValue());
-
} else {
- BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
+ BeEcompErrorManager.getInstance()
+ .logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
}
}
return isBase;
}
private Either<GroupDefinition, StorageOperationStatus> findGroupOnComponent(Component component, String groupId) {
-
Either<GroupDefinition, StorageOperationStatus> result = null;
if (CollectionUtils.isNotEmpty(component.getGroups())) {
Optional<GroupDefinition> foundGroup = component.getGroups().stream().filter(g -> g.getUniqueId().equals(groupId)).findFirst();
@@ -529,11 +507,13 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
return result;
}
- public Either<Boolean, ResponseFormat> validateGenerateVfModuleGroupNames(List<ArtifactTemplateInfo> allGroups, String resourceSystemName, int startGroupCounter) {
+ public Either<Boolean, ResponseFormat> validateGenerateVfModuleGroupNames(List<ArtifactTemplateInfo> allGroups, String resourceSystemName,
+ int startGroupCounter) {
Either<Boolean, ResponseFormat> validateGenerateGroupNamesRes = Either.left(true);
Collections.sort(allGroups, ArtifactTemplateInfo::compareByGroupName);
for (ArtifactTemplateInfo group : allGroups) {
- Either<String, ResponseFormat> validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, group.getDescription(), startGroupCounter++);
+ Either<String, ResponseFormat> validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName,
+ group.getDescription(), startGroupCounter++);
if (validateGenerateGroupNameRes.isRight()) {
validateGenerateGroupNamesRes = Either.right(validateGenerateGroupNameRes.right().value());
break;
@@ -555,7 +535,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
Either<String, ResponseFormat> validateGenerateGroupNameRes;
if (resourceSystemName != null && description != null && Pattern.compile(Constants.MODULE_DESC_PATTERN).matcher(description).matches()) {
final String fileName = description.replaceAll(GROUP_DELIMITER_REGEX, "\\.");
- validateGenerateGroupNameRes = Either.left(String.format(Constants.MODULE_NAME_FORMAT, resourceSystemName, FilenameUtils.removeExtension(fileName), groupCounter));
+ validateGenerateGroupNameRes = Either
+ .left(String.format(Constants.MODULE_NAME_FORMAT, resourceSystemName, FilenameUtils.removeExtension(fileName), groupCounter));
} else {
validateGenerateGroupNameRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME));
}
@@ -563,7 +544,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNames(Map<String, GroupDefinition> groups, String resourceSystemName) {
-
Map<String, GroupDefinition> updatedNamesGroups = new HashMap<>();
Either<Map<String, GroupDefinition>, ResponseFormat> result = Either.left(updatedNamesGroups);
for (Entry<String, GroupDefinition> groupEntry : groups.entrySet()) {
@@ -573,8 +553,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
int counter;
String description;
Either<String, ResponseFormat> newGroupNameRes;
- if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && !Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(groupName).matches()) {
-
+ if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && !Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(groupName)
+ .matches()) {
if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupEntry.getKey()).matches()) {
counter = Integer.parseInt(groupEntry.getKey().split(Constants.MODULE_NAME_DELIMITER)[1]);
description = curGroup.getDescription();
@@ -585,7 +565,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
newGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, description, counter);
if (newGroupNameRes.isRight()) {
log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value());
- loggerSupportability.log(LogLevel.INFO,LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML.getName(),StatusCode.ERROR.name(),"Failed to generate new vf module group name. Status is: "+newGroupNameRes.right().value());
+ loggerSupportability.log(LogLevel.INFO, LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML.getName(), StatusCode.ERROR.name(),
+ "Failed to generate new vf module group name. Status is: " + newGroupNameRes.right().value());
result = Either.right(newGroupNameRes.right().value());
break;
}
@@ -608,8 +589,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
public int getNextVfModuleNameCounter(Collection<GroupDefinition> groups) {
int counter = 0;
if (groups != null && !groups.isEmpty()) {
- List<Integer> counters = groups.stream().filter(group -> Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(group.getName()).matches() || Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(group.getName()).matches())
- .map(group -> Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1])).collect(toList());
+ List<Integer> counters = groups.stream().filter(
+ group -> Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(group.getName()).matches() || Pattern
+ .compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(group.getName()).matches())
+ .map(group -> Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1])).collect(toList());
counter = (counters == null || counters.isEmpty()) ? 0 : counters.stream().max(Integer::compare).get() + 1;
}
return counter;
@@ -617,14 +600,14 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
public Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesOnGraph(List<GroupDefinition> groups, Component component) {
List<GroupDefinition> updatedGroups = new ArrayList<>();
-
for (GroupDefinition group : groups) {
String groupType = group.getType();
String oldGroupName = group.getName();
String newGroupName;
Either<String, ResponseFormat> newGroupNameRes;
int counter;
- if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(oldGroupName).matches()) {
+ if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(oldGroupName)
+ .matches()) {
counter = Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1]);
newGroupNameRes = validateGenerateVfModuleGroupName(component.getSystemName(), group.getDescription(), counter);
if (newGroupNameRes.isRight()) {
@@ -633,54 +616,45 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
newGroupName = newGroupNameRes.left().value();
group.setName(newGroupName);
-
}
updatedGroups.add(group);
-
}
-
return Either.left(updatedGroups);
}
-
- public Either<GroupDefinitionInfo, ResponseFormat> getGroupInstWithArtifactsById(ComponentTypeEnum componentType, String componentId, String componentInstanceId, String groupInstId, String userId, boolean inTransaction) {
+ public Either<GroupDefinitionInfo, ResponseFormat> getGroupInstWithArtifactsById(ComponentTypeEnum componentType, String componentId,
+ String componentInstanceId, String groupInstId, String userId,
+ boolean inTransaction) {
Either<GroupDefinitionInfo, ResponseFormat> result = null;
-
// Validate user exist
validateUserExists(userId);
// Validate component exist
org.openecomp.sdc.be.model.Component component;
-
try {
ComponentParametersView componentParametersView = new ComponentParametersView();
componentParametersView.disableAll();
componentParametersView.setIgnoreUsers(false);
componentParametersView.setIgnoreComponentInstances(false);
componentParametersView.setIgnoreArtifacts(false);
-
component = validateComponentExists(componentId, componentType, componentParametersView);
- Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceRes = findComponentInstanceAndGroupInstanceOnComponent(component, componentInstanceId, groupInstId);
-
+ Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceRes = findComponentInstanceAndGroupInstanceOnComponent(
+ component, componentInstanceId, groupInstId);
if (findComponentInstanceAndGroupInstanceRes.isRight()) {
log.debug("Failed to get group {} . Status is {} ", groupInstId, findComponentInstanceAndGroupInstanceRes.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findComponentInstanceAndGroupInstanceRes.right().value()));
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(findComponentInstanceAndGroupInstanceRes.right().value()));
result = Either.right(responseFormat);
return result;
}
-
GroupInstance group = findComponentInstanceAndGroupInstanceRes.left().value().getRight();
-
Boolean isBase = isBaseProperty(component, group);
-
List<ArtifactDefinitionInfo> artifacts = new ArrayList<>();
List<String> artifactsIds = group.getArtifacts();
if (artifactsIds != null && !artifactsIds.isEmpty()) {
-
List<ComponentInstance> instances = component.getComponentInstances();
if (instances != null) {
- instances.stream().filter(i -> i.getUniqueId().equals(componentInstanceId))
- .findFirst()
- .ifPresent(f->getFirstComponentInstance(group, artifacts, artifactsIds, f));
+ instances.stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst()
+ .ifPresent(f -> getFirstComponentInstance(group, artifacts, artifactsIds, f));
}
}
GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group);
@@ -689,31 +663,23 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
resultInfo.setArtifacts(artifacts);
}
result = Either.left(resultInfo);
-
return result;
-
} finally {
closeTransaction(inTransaction, result);
}
}
- private void getFirstComponentInstance(GroupInstance group, List<ArtifactDefinitionInfo> artifacts, List<String> artifactsIds, ComponentInstance ci) {
+ private void getFirstComponentInstance(GroupInstance group, List<ArtifactDefinitionInfo> artifacts, List<String> artifactsIds,
+ ComponentInstance ci) {
Map<String, ArtifactDefinition> deploymentArtifacts = ci.getDeploymentArtifacts();
- artifactsIds.forEach(id -> deploymentArtifacts.values().stream()
- .filter(a -> a.getUniqueId().equals(id))
- .findFirst()
- .ifPresent(g -> artifacts.add(new ArtifactDefinitionInfo(g))));
-
+ artifactsIds.forEach(id -> deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst()
+ .ifPresent(g -> artifacts.add(new ArtifactDefinitionInfo(g))));
List<String> instArtifactsIds = group.getGroupInstanceArtifacts();
- instArtifactsIds.forEach(id -> deploymentArtifacts.values()
- .stream()
- .filter(a -> a.getUniqueId().equals(id))
- .findFirst()
- .ifPresent(g -> artifacts.add(new ArtifactDefinitionInfo(g))));
- }
+ instArtifactsIds.forEach(id -> deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst()
+ .ifPresent(g -> artifacts.add(new ArtifactDefinitionInfo(g))));
+ }
private Boolean isBaseProperty(Component component, GroupInstance group) {
-
Boolean isBase = null;
List<? extends GroupProperty> props = group.convertToGroupInstancesProperties();
if (props != null && !props.isEmpty()) {
@@ -721,9 +687,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (isBasePropOp.isPresent()) {
GroupProperty propIsBase = isBasePropOp.get();
isBase = Boolean.parseBoolean(propIsBase.getValue());
-
} else {
- BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
+ BeEcompErrorManager.getInstance()
+ .logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
}
}
return isBase;
@@ -733,20 +699,21 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (!inTransaction) {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- janusGraphDao.rollback();
+ janusGraphDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- janusGraphDao.commit();
+ janusGraphDao.commit();
}
}
}
- private Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceOnComponent(Component component, String componentInstanceId, String groupInstId) {
-
+ private Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceOnComponent(
+ Component component, String componentInstanceId, String groupInstId) {
Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> result = null;
if (CollectionUtils.isNotEmpty(component.getComponentInstances())) {
Optional<GroupInstance> foundGroup;
- Optional<ComponentInstance> foundComponent = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst();
+ Optional<ComponentInstance> foundComponent = component.getComponentInstances().stream()
+ .filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst();
if (foundComponent.isPresent() && CollectionUtils.isNotEmpty(foundComponent.get().getGroupInstances())) {
foundGroup = foundComponent.get().getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstId)).findFirst();
if (foundGroup.isPresent()) {
@@ -760,39 +727,44 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
return result;
}
- private Boolean validateMinMaxAndInitialCountPropertyLogic(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues, Map<PropertyNames, String> parentValues) {
-
+ private Boolean validateMinMaxAndInitialCountPropertyLogic(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues,
+ Map<PropertyNames, String> parentValues) {
for (Entry<PropertyNames, String> entry : newValues.entrySet()) {
PropertyNames currPropertyName = entry.getKey();
if (currPropertyName == PropertyNames.MIN_INSTANCES) {
String minValue = parentValues.get(PropertyNames.MIN_INSTANCES);
String maxValue = getMaxValue(newValues, currValues);
- validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue),
- new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue));
+ validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()),
+ new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue), new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue));
} else if (currPropertyName == PropertyNames.INITIAL_COUNT) {
- String minValue = newValues.containsKey(PropertyNames.MIN_INSTANCES) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.MIN_INSTANCES);
- String maxValue = newValues.containsKey(PropertyNames.MAX_INSTANCES) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.MAX_INSTANCES);
- validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue),
- new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue));
+ String minValue = newValues.containsKey(PropertyNames.MIN_INSTANCES) ? newValues.get(PropertyNames.MIN_INSTANCES)
+ : currValues.get(PropertyNames.MIN_INSTANCES);
+ String maxValue = newValues.containsKey(PropertyNames.MAX_INSTANCES) ? newValues.get(PropertyNames.MAX_INSTANCES)
+ : currValues.get(PropertyNames.MAX_INSTANCES);
+ validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()),
+ new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue), new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue));
} else if (currPropertyName == PropertyNames.MAX_INSTANCES) {
String minValue = getMinValue(newValues, currValues);
String maxValue = parentValues.get(PropertyNames.MAX_INSTANCES);
- validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue),
- new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue));
+ validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()),
+ new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue), new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue));
}
}
return true;
}
private String getMaxValue(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues) {
- return newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT);
+ return newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MAX_INSTANCES)
+ : currValues.get(PropertyNames.INITIAL_COUNT);
}
private String getMinValue(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues) {
- return newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT);
+ return newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MIN_INSTANCES)
+ : currValues.get(PropertyNames.INITIAL_COUNT);
}
- private Boolean validateValueInRange(ImmutablePair<PropertyNames, String> newValue, ImmutablePair<PropertyNames, String> min, ImmutablePair<PropertyNames, String> max) {
+ private Boolean validateValueInRange(ImmutablePair<PropertyNames, String> newValue, ImmutablePair<PropertyNames, String> min,
+ ImmutablePair<PropertyNames, String> max) {
final String warnMessage = "Failed to validate {} as property value of {}. It must be not higher than {}, and not lower than {}.";
int newValueInt = parseIntValue(newValue.getValue(), newValue.getKey());
int minInt = parseIntValue(min.getValue(), min.getKey());
@@ -801,8 +773,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY);
} else if (newValueInt < minInt || newValueInt > maxInt) {
log.debug(warnMessage, newValue.getValue(), newValue.getKey().getPropertyName(), min.getValue(), max.getValue());
- throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE, newValue.getKey().getPropertyName(),
- maxInt == Integer.MAX_VALUE ? Constants.UNBOUNDED : max.getValue(), min.getValue());
+ throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE,
+ newValue.getKey().getPropertyName(), maxInt == Integer.MAX_VALUE ? Constants.UNBOUNDED : max.getValue(), min.getValue());
}
return true;
}
@@ -826,17 +798,20 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
* @param newProperties
* @return
*/
- public Either<GroupInstance, ResponseFormat> validateAndUpdateGroupInstancePropertyValues(String componentId, String instanceId, GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties) {
-
+ public Either<GroupInstance, ResponseFormat> validateAndUpdateGroupInstancePropertyValues(String componentId, String instanceId,
+ GroupInstance oldGroupInstance,
+ List<GroupInstanceProperty> newProperties) {
Either<GroupInstance, ResponseFormat> actionResult = null;
Either<GroupInstance, StorageOperationStatus> updateGroupInstanceResult = null;
List<GroupInstanceProperty> validateRes = validateReduceGroupInstancePropertiesBeforeUpdate(oldGroupInstance, newProperties);
if (actionResult == null) {
List<GroupInstanceProperty> validatedReducedNewProperties = validateRes;
- updateGroupInstanceResult = groupsOperation.updateGroupInstancePropertyValuesOnGraph(componentId, instanceId, oldGroupInstance, validatedReducedNewProperties);
+ updateGroupInstanceResult = groupsOperation
+ .updateGroupInstancePropertyValuesOnGraph(componentId, instanceId, oldGroupInstance, validatedReducedNewProperties);
if (updateGroupInstanceResult.isRight()) {
log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName());
- actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupInstanceResult.right().value())));
+ actionResult = Either
+ .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupInstanceResult.right().value())));
}
}
if (actionResult == null) {
@@ -845,11 +820,12 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
return actionResult;
}
- private List<GroupInstanceProperty> validateReduceGroupInstancePropertiesBeforeUpdate(GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties) {
-
+ private List<GroupInstanceProperty> validateReduceGroupInstancePropertiesBeforeUpdate(GroupInstance oldGroupInstance,
+ List<GroupInstanceProperty> newProperties) {
Boolean validationRes = null;
List<GroupInstanceProperty> actionResult = null;
- Map<String, GroupInstanceProperty> existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream().collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
+ Map<String, GroupInstanceProperty> existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream()
+ .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
Map<PropertyNames, String> newPropertyValues = new EnumMap<>(PropertyNames.class);
List<GroupInstanceProperty> reducedProperties = new ArrayList<>();
String currPropertyName;
@@ -874,7 +850,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
return actionResult;
}
- private void fillValuesAndParentValuesFromExistingProperties(Map<String, GroupInstanceProperty> existingProperties, Map<PropertyNames, String> propertyValues, Map<PropertyNames, String> parentPropertyValues) {
+ private void fillValuesAndParentValuesFromExistingProperties(Map<String, GroupInstanceProperty> existingProperties,
+ Map<PropertyNames, String> propertyValues,
+ Map<PropertyNames, String> parentPropertyValues) {
PropertyNames[] allPropertyNames = PropertyNames.values();
for (PropertyNames name : allPropertyNames) {
if (isUpdatable(name)) {
@@ -884,8 +862,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
}
- private Boolean handleAndAddProperty(List<GroupInstanceProperty> reducedProperties, Map<PropertyNames, String> newPropertyValues, GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) {
-
+ private Boolean handleAndAddProperty(List<GroupInstanceProperty> reducedProperties, Map<PropertyNames, String> newPropertyValues,
+ GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) {
Boolean validationRes = null;
String currPropertyName = currNewProperty.getName();
PropertyNames propertyName = PropertyNames.findName(currPropertyName);
@@ -908,11 +886,14 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
private boolean isUpdatable(PropertyNames updatablePropertyName) {
- return updatablePropertyName != null && updatablePropertyName.getUpdateBehavior().getLevelNumber() >= GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL.getLevelNumber();
+ return updatablePropertyName != null
+ && updatablePropertyName.getUpdateBehavior().getLevelNumber() >= GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL
+ .getLevelNumber();
}
- private void addPropertyUpdatedValues(List<GroupInstanceProperty> reducedProperties, PropertyNames propertyName, Map<PropertyNames, String> newPropertyValues, GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) {
-
+ private void addPropertyUpdatedValues(List<GroupInstanceProperty> reducedProperties, PropertyNames propertyName,
+ Map<PropertyNames, String> newPropertyValues, GroupInstanceProperty newProperty,
+ GroupInstanceProperty existingProperty) {
String newValue = newProperty.getValue();
if (!newValue.equals(String.valueOf(existingProperty.getValue()))) {
newProperty.setValueUniqueUid(existingProperty.getValueUniqueUid());
@@ -932,7 +913,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
private int convertIfUnboundMax(String value) {
-
int result;
if (!NumberUtils.isNumber(value)) {
result = Integer.MAX_VALUE;
@@ -943,9 +923,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
private Boolean validateAndUpdatePropertyValue(GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) {
-
String parentValue = existingProperty.getParentValue();
-
newProperty.setParentValue(parentValue);
if (StringUtils.isEmpty(newProperty.getValue())) {
newProperty.setValue(parentValue);
@@ -955,34 +933,30 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
StorageOperationStatus status = groupOperation.validateAndUpdatePropertyValue(newProperty);
if (status != StorageOperationStatus.OK) {
- log.debug("Failed to validate property value {} of property with name {}. Status is {}. ", newProperty.getValue(), newProperty.getName(), status);
+ log.debug("Failed to validate property value {} of property with name {}. Status is {}. ", newProperty.getValue(), newProperty.getName(),
+ status);
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status));
}
return true;
}
private void validateImmutableProperty(GroupProperty oldProperty, GroupProperty newProperty) {
- if (oldProperty.getValue() == null && newProperty.getValue() != null || oldProperty.getValue() != null && !oldProperty.getValue().equals(newProperty.getValue())) {
- log.warn("The value of property with the name {} cannot be updated on service level. Going to ignore new property value {}. ", oldProperty.getName(), newProperty.getValue());
+ if (oldProperty.getValue() == null && newProperty.getValue() != null || oldProperty.getValue() != null && !oldProperty.getValue()
+ .equals(newProperty.getValue())) {
+ log.warn("The value of property with the name {} cannot be updated on service level. Going to ignore new property value {}. ",
+ oldProperty.getName(), newProperty.getValue());
}
}
@LockingTransactional
- public GroupDefinition createGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupType,
- String userId) {
-
+ public GroupDefinition createGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupType, String userId) {
Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentTypeEnum, userId, CREATE_GROUP);
-
validateGroupTypePerComponent(groupType, component);
-
- GroupTypeDefinition groupTypeDefinition = groupTypeOperation.getLatestGroupTypeByType(groupType, false)
- .left()
- .on(se -> onGroupTypeNotFound(component));
-
+ GroupTypeDefinition groupTypeDefinition = groupTypeOperation.getLatestGroupTypeByType(groupType, false).left()
+ .on(se -> onGroupTypeNotFound(component));
boolean hasExistingGroups = CollectionUtils.isNotEmpty(component.getGroups());
GroupDefinition groupDefinition = new GroupDefinition();
groupDefinition.setType(groupType);
-
//find next valid counter
int nextCounter = 0;
if (hasExistingGroups) {
@@ -993,26 +967,17 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
groupDefinition.setDescription(groupTypeDefinition.getDescription());
groupDefinition.setInvariantName(name);
groupDefinition.setCreatedFrom(CreatedFrom.UI);
-
//Add default type properties
List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties();
- List<GroupProperty> properties = groupTypeProperties.stream()
- .map(GroupProperty::new)
- .collect(toList());
+ List<GroupProperty> properties = groupTypeProperties.stream().map(GroupProperty::new).collect(toList());
groupDefinition.convertFromGroupProperties(properties);
-
groupDefinition.convertCapabilityDefinitions(groupTypeDefinition.getCapabilities());
-
List<GroupDefinition> gdList;
if (toscaOperationFacade.canAddGroups(componentId)) {
- gdList = addGroups(component, Arrays.asList(groupDefinition), false)
- .left()
- .on(this::onFailedGroupDBOperation);
+ gdList = addGroups(component, Arrays.asList(groupDefinition), false).left().on(this::onFailedGroupDBOperation);
} else {
//createGroups also creates an edge and vertex to store group data
- gdList = createGroups(component, Arrays.asList(groupDefinition), false)
- .left()
- .on(this::onFailedGroupDBOperation);
+ gdList = createGroups(component, Arrays.asList(groupDefinition), false).left().on(this::onFailedGroupDBOperation);
}
return gdList.get(0);
}
@@ -1020,51 +985,35 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
private void validateGroupTypePerComponent(String groupType, Component component) {
String specificType = component.getComponentMetadataDefinition().getMetadataDataDefinition().getActualComponentType();
if (!component.isTopologyTemplate()) {
- throw new ByActionStatusComponentException(ActionStatus.GROUP_TYPE_ILLEGAL_PER_COMPONENT, groupType,
- specificType);
+ throw new ByActionStatusComponentException(ActionStatus.GROUP_TYPE_ILLEGAL_PER_COMPONENT, groupType, specificType);
}
Map<String, Set<String>> excludedGroupTypesMap = ConfigurationManager.getConfigurationManager().getConfiguration()
- .getExcludedGroupTypesMapping();
-
+ .getExcludedGroupTypesMapping();
if (MapUtils.isNotEmpty(excludedGroupTypesMap) && StringUtils.isNotEmpty(specificType)) {
Set<String> excludedGroupTypesPerComponent = excludedGroupTypesMap.get(specificType);
- if (excludedGroupTypesPerComponent!=null && excludedGroupTypesPerComponent.contains(groupType)) {
+ if (excludedGroupTypesPerComponent != null && excludedGroupTypesPerComponent.contains(groupType)) {
throw new ByActionStatusComponentException(ActionStatus.GROUP_TYPE_ILLEGAL_PER_COMPONENT, groupType, specificType);
}
}
}
private int getNewGroupCounter(Component component) {
- List<String> existingNames = component.getGroups()
- .stream()
- .map(GroupDataDefinition::getInvariantName)
- .collect(toList());
- List<String> existingIds = component.getGroups()
- .stream()
- .map(GroupDataDefinition::getUniqueId)
- .collect(toList());
+ List<String> existingNames = component.getGroups().stream().map(GroupDataDefinition::getInvariantName).collect(toList());
+ List<String> existingIds = component.getGroups().stream().map(GroupDataDefinition::getUniqueId).collect(toList());
existingIds.addAll(existingNames);
-
return Utils.getNextCounter(existingIds);
}
@LockingTransactional
- public GroupDefinition updateGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupId,
- String userId, GroupDefinition updatedGroup) {
+ public GroupDefinition updateGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupId, String userId,
+ GroupDefinition updatedGroup) {
Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentTypeEnum, userId, UPDATE_GROUP);
-
- GroupDefinition existingGroup = findGroupOnComponent(component, groupId)
- .left()
- .on(se -> onGroupNotFoundInComponentError(component, groupId));
-
+ GroupDefinition existingGroup = findGroupOnComponent(component, groupId).left().on(se -> onGroupNotFoundInComponentError(component, groupId));
String existingGroupName = existingGroup.getName();
String updatedGroupName = updatedGroup.getName();
assertNewNameIsValidAndUnique(existingGroupName, updatedGroupName, component);
existingGroup.setName(updatedGroupName);
-
- return updateGroup(component, existingGroup, existingGroupName)
- .left()
- .on(this::onFailedUpdateGroupDBOperation);
+ return updateGroup(component, existingGroup, existingGroupName).left().on(this::onFailedUpdateGroupDBOperation);
}
private void assertNewNameIsValidAndUnique(String currentGroupName, String updatedGroupName, Component component) {
@@ -1080,18 +1029,11 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
@LockingTransactional
- public GroupDefinition deleteGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupId,
- String userId) {
+ public GroupDefinition deleteGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupId, String userId) {
Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentTypeEnum, userId, DELETE_GROUP);
-
- GroupDefinition groupDefinition = findGroupOnComponent(component, groupId)
- .left()
- .on(se -> onGroupNotFoundInComponentError(component, groupId));
-
- List<GroupDefinition> gdList = deleteGroups(component, java.util.Arrays.asList(groupDefinition))
- .left()
- .on(this::onFailedGroupDBOperation);
-
+ GroupDefinition groupDefinition = findGroupOnComponent(component, groupId).left()
+ .on(se -> onGroupNotFoundInComponentError(component, groupId));
+ List<GroupDefinition> gdList = deleteGroups(component, java.util.Arrays.asList(groupDefinition)).left().on(this::onFailedGroupDBOperation);
updatePolicyTargetReferencingDeletedGroup(groupId, component);
return gdList.get(0);
}
@@ -1107,17 +1049,18 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
private GroupDefinition onGroupNotFoundInComponentError(Component component, String groupId) {
- throw new ByActionStatusComponentException(ActionStatus.GROUP_IS_MISSING, groupId,
- component.getSystemName(), getComponentTypeForResponse(component));
+ throw new ByActionStatusComponentException(ActionStatus.GROUP_IS_MISSING, groupId, component.getSystemName(),
+ getComponentTypeForResponse(component));
}
private GroupTypeDefinition onGroupTypeNotFound(Component component) {
throw new ByActionStatusComponentException(ActionStatus.GROUP_TYPE_IS_INVALID, component.getSystemName(),
- component.getComponentType().toString());
+ component.getComponentType().toString());
}
private void updatePolicyTargetReferencingDeletedGroup(String groupId, Component component) {
- log.debug("#updatePolicyTargetReferencingDeletedGroup - removing all component {} policy targets referencing group {}", component.getUniqueId(), groupId);
+ log.debug("#updatePolicyTargetReferencingDeletedGroup - removing all component {} policy targets referencing group {}",
+ component.getUniqueId(), groupId);
ActionStatus actionStatus = policyTargetsUpdateHandler.removePoliciesTargets(component, groupId, PolicyTargetType.GROUPS);
if (ActionStatus.OK != actionStatus) {
janusGraphDao.rollback();
@@ -1125,20 +1068,19 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
}
-
- public Either<List<GroupDefinition>, ResponseFormat> createGroups(Component component, final List<GroupDefinition> groupDefinitions, boolean fromCsar) {
-
+ public Either<List<GroupDefinition>, ResponseFormat> createGroups(Component component, final List<GroupDefinition> groupDefinitions,
+ boolean fromCsar) {
Map<String, GroupDataDefinition> groups = new HashMap<>();
Either<List<GroupDefinition>, ResponseFormat> result = null;
Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
if (allDataTypes.isRight()) {
JanusGraphOperationStatus status = allDataTypes.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
-
+ BeEcompErrorManager.getInstance()
+ .logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR);
+ return Either.right(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
}
-
// handle groups and convert to tosca data
if (groupDefinitions != null && !groupDefinitions.isEmpty()) {
for (GroupDefinition groupDefinition : groupDefinitions) {
@@ -1149,13 +1091,13 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
GroupDefinition handledGroup = handleGroupRes.left().value();
groups.put(handledGroup.getInvariantName(), new GroupDataDefinition(handledGroup));
-
}
}
if (result == null) {
createGroupsResult = groupsOperation.createGroups(component, groups);
if (createGroupsResult.isRight()) {
- result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
+ result = Either
+ .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
}
}
if (result == null) {
@@ -1168,26 +1110,27 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
return result;
}
- private void updateCalculatedCapabilitiesWithPropertiesOnComponent(Component component, final List<GroupDefinition> groupDefinitions, boolean fromCsar) {
+ private void updateCalculatedCapabilitiesWithPropertiesOnComponent(Component component, final List<GroupDefinition> groupDefinitions,
+ boolean fromCsar) {
groupDefinitions.forEach(GroupDefinition::updateEmptyCapabilitiesOwnerFields);
- StorageOperationStatus status = groupsOperation.updateCalculatedCapabilitiesWithProperties(component.getUniqueId(),
- extractCapabilitiesFromGroups(groupDefinitions), extractCapabilityPropertiesFromGroups(groupDefinitions, fromCsar));
- if(status != StorageOperationStatus.OK){
- log.error("#updateCalculatedCapabilitiesWithPropertiesOnComponent - failed to update the groups' calculated capabilities with the properties on the component {}. ", component.getUniqueId());
+ StorageOperationStatus status = groupsOperation
+ .updateCalculatedCapabilitiesWithProperties(component.getUniqueId(), extractCapabilitiesFromGroups(groupDefinitions),
+ extractCapabilityPropertiesFromGroups(groupDefinitions, fromCsar));
+ if (status != StorageOperationStatus.OK) {
+ log.error(
+ "#updateCalculatedCapabilitiesWithPropertiesOnComponent - failed to update the groups' calculated capabilities with the properties on the component {}. ",
+ component.getUniqueId());
rollbackWithException(componentsUtils.convertFromStorageResponse(status));
}
}
- private void addCalculatedCapabilitiesWithPropertiesToComponent(Component component,
- final List<GroupDefinition> groupDefinitions, boolean fromCsar) {
- final List<GroupDefinition> nonNullGroupDefinitions =
- (groupDefinitions == null) ? Collections.emptyList() : groupDefinitions;
-
+ private void addCalculatedCapabilitiesWithPropertiesToComponent(Component component, final List<GroupDefinition> groupDefinitions,
+ boolean fromCsar) {
+ final List<GroupDefinition> nonNullGroupDefinitions = (groupDefinitions == null) ? Collections.emptyList() : groupDefinitions;
nonNullGroupDefinitions.forEach(GroupDefinition::updateEmptyCapabilitiesOwnerFields);
- StorageOperationStatus status = groupsOperation.addCalculatedCapabilitiesWithProperties(
- component.getUniqueId(),
- extractCapabilitiesFromGroups(nonNullGroupDefinitions),
- extractCapabilityPropertiesFromGroups(nonNullGroupDefinitions, fromCsar));
+ StorageOperationStatus status = groupsOperation
+ .addCalculatedCapabilitiesWithProperties(component.getUniqueId(), extractCapabilitiesFromGroups(nonNullGroupDefinitions),
+ extractCapabilityPropertiesFromGroups(nonNullGroupDefinitions, fromCsar));
if (status != StorageOperationStatus.OK) {
log.error(
"#addCalculatedCapabilitiesWithPropertiesToComponent - failed to add the groups' calculated capabilities with the properties to the component {}. ",
@@ -1198,26 +1141,27 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
private void deleteCalculatedCapabilitiesWithPropertiesFromComponent(Component component, final List<GroupDefinition> groupDefinitions) {
StorageOperationStatus status = groupsOperation.deleteCalculatedCapabilitiesWithProperties(component.getUniqueId(), groupDefinitions);
- if(status != StorageOperationStatus.OK){
- log.error("#deleteCalculatedCapabilitiesWithPropertiesFromComponent - failed to remove the groups' calculated capabilities with the properties from the component {}. ", component.getUniqueId());
+ if (status != StorageOperationStatus.OK) {
+ log.error(
+ "#deleteCalculatedCapabilitiesWithPropertiesFromComponent - failed to remove the groups' calculated capabilities with the properties from the component {}. ",
+ component.getUniqueId());
rollbackWithException(componentsUtils.convertFromStorageResponse(status));
}
}
- public Either<List<GroupDefinition>, ResponseFormat> addGroups(Component component, final List<GroupDefinition> groupDefinitions, boolean fromCsar) {
-
+ public Either<List<GroupDefinition>, ResponseFormat> addGroups(Component component, final List<GroupDefinition> groupDefinitions,
+ boolean fromCsar) {
Either<List<GroupDefinition>, ResponseFormat> result = null;
Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
List<GroupDataDefinition> groups = new ArrayList<>();
-
Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
if (allDataTypes.isRight()) {
JanusGraphOperationStatus status = allDataTypes.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
-
+ BeEcompErrorManager.getInstance()
+ .logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR);
+ return Either.right(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
}
-
// handle groups and convert to tosca data
if (groupDefinitions != null && !groupDefinitions.isEmpty()) {
for (GroupDefinition groupDefinition : groupDefinitions) {
@@ -1233,7 +1177,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (result == null) {
createGroupsResult = groupsOperation.addGroups(component, groups);
if (createGroupsResult.isRight()) {
- result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
+ result = Either
+ .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
}
component.addGroups(createGroupsResult.left().value());
}
@@ -1247,16 +1192,14 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
public Either<List<GroupDefinition>, ResponseFormat> deleteGroups(Component component, List<GroupDefinition> groupDefinitions) {
-
Either<List<GroupDefinition>, StorageOperationStatus> deleteGroupsResult;
-
deleteGroupsResult = groupsOperation.deleteGroups(component, groupDefinitions.stream().map(GroupDataDefinition::new).collect(toList()));
if (deleteGroupsResult.isRight()) {
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteGroupsResult.right().value())));
} else {
deleteCalculatedCapabilitiesWithPropertiesFromComponent(component, groupDefinitions);
}
- if (component.getGroups()!=null) {
+ if (component.getGroups() != null) {
component.getGroups().removeAll(deleteGroupsResult.left().value());
}
return Either.left(deleteGroupsResult.left().value());
@@ -1264,15 +1207,14 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
/**
* Update specific group version
- * @param fromCsar TODO
*
+ * @param fromCsar TODO
*/
public Either<List<GroupDefinition>, ResponseFormat> updateGroups(Component component, List<GroupDefinition> groupDefinitions, boolean fromCsar) {
-
Either<List<GroupDefinition>, ResponseFormat> result = null;
Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult;
-
- createGroupsResult = groupsOperation.updateGroups(component, groupDefinitions.stream().map(GroupDataDefinition::new).collect(toList()), PromoteVersionEnum.MINOR);
+ createGroupsResult = groupsOperation
+ .updateGroups(component, groupDefinitions.stream().map(GroupDataDefinition::new).collect(toList()), PromoteVersionEnum.MINOR);
if (createGroupsResult.isRight()) {
result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
}
@@ -1285,15 +1227,17 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
return result;
}
- private Either<GroupDefinition, ResponseFormat> handleGroup(Component component, GroupDefinition groupDefinition, Map<String, DataTypeDefinition> allDAtaTypes) {
-
+ private Either<GroupDefinition, ResponseFormat> handleGroup(Component component, GroupDefinition groupDefinition,
+ Map<String, DataTypeDefinition> allDAtaTypes) {
log.trace("Going to create group {}", groupDefinition);
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(),StatusCode.STARTED,"Start to create group: {}",groupDefinition.getName()+ " for component " + component.getName());
+ loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY, component.getComponentMetadataForSupportLog(), StatusCode.STARTED,
+ "Start to create group: {}", groupDefinition.getName() + " for component " + component.getName());
// 3. verify group not already exist
String groupDefinitionName = groupDefinition.getName();
if (groupExistsInComponent(groupDefinitionName, component)) {
String componentTypeForResponse = getComponentTypeForResponse(component);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinitionName, component.getNormalizedName(), componentTypeForResponse));
+ return Either.right(componentsUtils
+ .getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinitionName, component.getNormalizedName(), componentTypeForResponse));
}
// 4. verify type of group exist
String groupType = groupDefinition.getType();
@@ -1304,56 +1248,60 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (getGroupType.isRight()) {
StorageOperationStatus status = getGroupType.right().value();
if (status == StorageOperationStatus.NOT_FOUND) {
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(), StatusCode.ERROR,"group {} cannot be found",groupDefinition.getName());
- BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "group type " + groupType + " cannot be found", ErrorSeverity.INFO);
+ loggerSupportability
+ .log(LoggerSupportabilityActions.CREATE_GROUP_POLICY, component.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "group {} cannot be found", groupDefinition.getName());
+ BeEcompErrorManager.getInstance()
+ .logInvalidInputError(CREATE_GROUP, "group type " + groupType + " cannot be found", ErrorSeverity.INFO);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType));
} else {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
}
// 6. verify the component instances type are allowed according to
+
// the member types in the group type
GroupTypeDefinition groupTypeDefinition = getGroupType.left().value();
-
- Either<Boolean, ResponseFormat> areValidMembers = verifyComponentInstancesAreValidMembers(component, groupDefinitionName, groupDefinition.getMembers(), groupTypeDefinition.getMembers());
-
+ Either<Boolean, ResponseFormat> areValidMembers = verifyComponentInstancesAreValidMembers(component, groupDefinitionName,
+ groupDefinition.getMembers(), groupTypeDefinition.getMembers());
if (areValidMembers.isRight()) {
ResponseFormat responseFormat = areValidMembers.right().value();
return Either.right(responseFormat);
}
// 7. verify the artifacts belongs to the component
- Either<Boolean, ResponseFormat> areValidArtifacts = verifyArtifactsBelongsToComponent(component, groupDefinition.getArtifacts(), CREATE_GROUP);
+ Either<Boolean, ResponseFormat> areValidArtifacts = verifyArtifactsBelongsToComponent(component, groupDefinition.getArtifacts(),
+ CREATE_GROUP);
if (areValidArtifacts.isRight()) {
ResponseFormat responseFormat = areValidArtifacts.right().value();
return Either.right(responseFormat);
}
List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties();
-
List<GroupProperty> properties = groupDefinition.convertToGroupProperties();
List<GroupProperty> updatedGroupTypeProperties = new ArrayList<>();
if (CollectionUtils.isNotEmpty(properties)) {
if (CollectionUtils.isEmpty(groupTypeProperties)) {
BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "group type does not have properties", ErrorSeverity.INFO);
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(), StatusCode.ERROR,"group {} does not have properties ",groupDefinition.getName());
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.MATCH_NOT_FOUND))));
+ loggerSupportability
+ .log(LoggerSupportabilityActions.CREATE_GROUP_POLICY, component.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "group {} does not have properties ", groupDefinition.getName());
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
+ DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.MATCH_NOT_FOUND))));
}
-
- Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(PropertyDefinition::getName, p -> p));
-
+ Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream()
+ .collect(Collectors.toMap(PropertyDefinition::getName, p -> p));
Either<GroupProperty, JanusGraphOperationStatus> addPropertyResult;
int i = 1;
for (GroupProperty prop : properties) {
addPropertyResult = handleProperty(prop, groupTypePropertiesMap.get(prop.getName()), i, allDAtaTypes, groupType);
if (addPropertyResult.isRight()) {
BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "failed to validate property", ErrorSeverity.INFO);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(addPropertyResult.right().value()))));
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils
+ .convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(addPropertyResult.right().value()))));
}
updatedGroupTypeProperties.add(addPropertyResult.left().value());
-
i++;
}
}
-
if (groupDefinition.getUniqueId() == null) {
String uid = UniqueIdBuilder.buildGroupingUid(component.getUniqueId(), groupDefinitionName);
groupDefinition.setUniqueId(uid);
@@ -1363,42 +1311,27 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
groupDefinition.setGroupUUID(UniqueIdBuilder.generateUUID());
groupDefinition.setVersion(INITIAL_VERSION);
groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId());
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,"group {} has been created ",groupDefinition.getName());
+ loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY, component.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
+ "group {} has been created ", groupDefinition.getName());
return Either.left(groupDefinition);
}
- private static boolean groupExistsInComponent(String groupDefinitionName, Component component) {
- boolean found = false;
- List<GroupDefinition> groups = component.getGroups();
- if (CollectionUtils.isNotEmpty(groups)) {
- found = groups.stream().filter(p -> (p.getName().equalsIgnoreCase(groupDefinitionName))
- || p.getInvariantName().equalsIgnoreCase(groupDefinitionName))
- .findFirst().orElse(null) != null;
- }
- return found;
- }
-
- private Either<GroupProperty, JanusGraphOperationStatus> handleProperty(GroupProperty groupProperty, PropertyDefinition prop, Integer index, Map<String, DataTypeDefinition> allDataTypes, String groupType) {
-
+ private Either<GroupProperty, JanusGraphOperationStatus> handleProperty(GroupProperty groupProperty, PropertyDefinition prop, Integer index,
+ Map<String, DataTypeDefinition> allDataTypes, String groupType) {
if (prop == null) {
return Either.right(JanusGraphOperationStatus.ILLEGAL_ARGUMENT);
}
-
String propertyType = prop.getType();
String value = groupProperty.getValue();
-
Either<String, JanusGraphOperationStatus> checkInnerType = propertyOperation.checkInnerType(prop);
if (checkInnerType.isRight()) {
JanusGraphOperationStatus status = checkInnerType.right().value();
return Either.right(status);
}
-
String innerType = checkInnerType.left().value();
-
log.debug("Before validateAndUpdatePropertyValue");
Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes);
log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid);
-
String newValue = value;
if (isValid.isRight()) {
Boolean res = isValid.right().value();
@@ -1411,10 +1344,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
newValue = object.toString();
}
}
-
- String uniqueId = shouldReconstructUniqueId(groupType) ? UniqueIdBuilder.buildGroupPropertyValueUid(prop.getUniqueId(), index)
- : prop.getUniqueId();
-
+ String uniqueId =
+ shouldReconstructUniqueId(groupType) ? UniqueIdBuilder.buildGroupPropertyValueUid(prop.getUniqueId(), index) : prop.getUniqueId();
groupProperty.setUniqueId(uniqueId);
groupProperty.setValue(newValue);
groupProperty.setType(prop.getType());
@@ -1423,16 +1354,13 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
groupProperty.setSchema(prop.getSchema());
groupProperty.setPassword(prop.isPassword());
groupProperty.setParentUniqueId(prop.getUniqueId());
-
log.debug("Before adding property value to graph {}", groupProperty);
-
return Either.left(groupProperty);
}
-
// For old groups we want to leave indexing of property
+
// For new groups we just need the types
private boolean shouldReconstructUniqueId(String groupType) {
return Constants.GROUP_TOSCA_HEAT.equals(groupType) || Constants.DEFAULT_GROUP_VF_MODULE.equals(groupType);
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicNew.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicNew.java
index eb576a46f6..46b6f79133 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicNew.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicNew.java
@@ -21,6 +21,14 @@
*/
package org.openecomp.sdc.be.components.impl;
+import static org.openecomp.sdc.be.components.impl.BaseBusinessLogic.enumHasValueFilter;
+
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
@@ -46,15 +54,6 @@ import org.openecomp.sdc.be.model.operations.impl.GroupOperation;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.springframework.transaction.annotation.Transactional;
-import java.util.ArrayList;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-import static org.openecomp.sdc.be.components.impl.BaseBusinessLogic.enumHasValueFilter;
-
@org.springframework.stereotype.Component
public class GroupBusinessLogicNew {
@@ -63,7 +62,8 @@ public class GroupBusinessLogicNew {
private final GroupsOperation groupsOperation;
private final GroupOperation groupOperation;
- public GroupBusinessLogicNew(AccessValidations accessValidations, ComponentValidations componentValidations, GroupsOperation groupsOperation, GroupOperation groupOperation) {
+ public GroupBusinessLogicNew(AccessValidations accessValidations, ComponentValidations componentValidations, GroupsOperation groupsOperation,
+ GroupOperation groupOperation) {
this.accessValidations = accessValidations;
this.componentValidations = componentValidations;
this.groupsOperation = groupsOperation;
@@ -71,7 +71,8 @@ public class GroupBusinessLogicNew {
}
@LockingTransactional
- public List<String> updateMembers(String componentId, ComponentTypeEnum componentType, String userId, String groupUniqueId, List<String> members) {
+ public List<String> updateMembers(String componentId, ComponentTypeEnum componentType, String userId, String groupUniqueId,
+ List<String> members) {
Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentType, userId, "UPDATE GROUP MEMBERS");
GroupDefinition groupDefinition = getGroup(component, groupUniqueId);
groupDefinition.setMembers(buildMembersMap(component, members));
@@ -80,13 +81,13 @@ public class GroupBusinessLogicNew {
}
@LockingTransactional
- public List<GroupProperty> updateProperties(String componentId, ComponentTypeEnum componentType, String userId, String groupUniqueId, List<GroupProperty> newProperties) {
+ public List<GroupProperty> updateProperties(String componentId, ComponentTypeEnum componentType, String userId, String groupUniqueId,
+ List<GroupProperty> newProperties) {
Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentType, userId, "UPDATE GROUP PROPERTIES");
GroupDefinition currentGroup = getGroup(component, groupUniqueId);
validateUpdatedPropertiesAndSetEmptyValues(currentGroup, newProperties);
- return groupsOperation.updateGroupPropertiesOnComponent(componentId, currentGroup, newProperties, PromoteVersionEnum.MINOR)
- .left()
- .on(this::onUpdatePropertyError);
+ return groupsOperation.updateGroupPropertiesOnComponent(componentId, currentGroup, newProperties, PromoteVersionEnum.MINOR).left()
+ .on(this::onUpdatePropertyError);
}
@Transactional
@@ -110,31 +111,26 @@ public class GroupBusinessLogicNew {
}
private ComponentInstance getComponentInstance(Component component, String memberUniqueId) {
- return componentValidations.getComponentInstance(component, memberUniqueId)
- .orElseThrow(() -> new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
- memberUniqueId, "",
- component.getActualComponentType(), component.getSystemName()));
+ return componentValidations.getComponentInstance(component, memberUniqueId).orElseThrow(
+ () -> new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, memberUniqueId, "",
+ component.getActualComponentType(), component.getSystemName()));
}
private GroupDefinition getGroup(Component component, String groupUniqueId) {
- return component.getGroupById(groupUniqueId)
- .orElseThrow(() -> new ByActionStatusComponentException(ActionStatus.GROUP_IS_MISSING,
- component.getSystemName(), component.getActualComponentType()));
+ return component.getGroupById(groupUniqueId).orElseThrow(
+ () -> new ByActionStatusComponentException(ActionStatus.GROUP_IS_MISSING, component.getSystemName(), component.getActualComponentType()));
}
private void validateUpdatedPropertiesAndSetEmptyValues(GroupDefinition originalGroup, List<GroupProperty> groupPropertiesToUpdate) {
-
if (CollectionUtils.isEmpty(groupPropertiesToUpdate)) {
throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, StringUtils.EMPTY);
}
if (CollectionUtils.isEmpty(originalGroup.getProperties())) {
- throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, groupPropertiesToUpdate.get(NumberUtils.INTEGER_ZERO).getName());
+ throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND,
+ groupPropertiesToUpdate.get(NumberUtils.INTEGER_ZERO).getName());
}
- Map<String, GroupProperty> originalProperties = originalGroup.convertToGroupProperties()
- .stream()
- .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
-
-
+ Map<String, GroupProperty> originalProperties = originalGroup.convertToGroupProperties().stream()
+ .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
for (GroupProperty gp : groupPropertiesToUpdate) {
String updatedPropertyName = gp.getName();
if (!originalProperties.containsKey(updatedPropertyName)) {
@@ -151,12 +147,10 @@ public class GroupBusinessLogicNew {
throw new StorageException(sos, updatedPropertyName);
}
}
-
validatePropertyBusinessLogic(groupPropertiesToUpdate, originalGroup);
}
private void validatePropertyBusinessLogic(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) {
-
Map<PropertyDefinition.PropertyNames, String> enumValueMap = new EnumMap<>(PropertyDefinition.PropertyNames.class);
for (GroupProperty gp : groupPropertiesToUpdate) {
// Filter out non special properties which does not have Enum
@@ -168,20 +162,19 @@ public class GroupBusinessLogicNew {
if (MapUtils.isEmpty(enumValueMap)) {
return;
}
-
validateVFInstancesLogic(enumValueMap, prepareMapWithOriginalProperties(originalGroup));
-
- if (enumValueMap.containsKey(PropertyDefinition.PropertyNames.VF_MODULE_DESCRIPTION) || enumValueMap.containsKey(PropertyDefinition.PropertyNames.VF_MODULE_LABEL)) {
- groupPropertiesToUpdate.stream()
- .filter(e -> enumHasValueFilter(e.getName(), PropertyDefinition.PropertyNames::findName, PropertyDefinition.PropertyNames.VF_MODULE_DESCRIPTION, PropertyDefinition.PropertyNames.VF_MODULE_LABEL))
- .forEach(this::validateFreeText);
+ if (enumValueMap.containsKey(PropertyDefinition.PropertyNames.VF_MODULE_DESCRIPTION) || enumValueMap
+ .containsKey(PropertyDefinition.PropertyNames.VF_MODULE_LABEL)) {
+ groupPropertiesToUpdate.stream().filter(e -> enumHasValueFilter(e.getName(), PropertyDefinition.PropertyNames::findName,
+ PropertyDefinition.PropertyNames.VF_MODULE_DESCRIPTION, PropertyDefinition.PropertyNames.VF_MODULE_LABEL))
+ .forEach(this::validateFreeText);
}
}
private Map<PropertyDefinition.PropertyNames, String> prepareMapWithOriginalProperties(GroupDefinition originalGroup) {
Map<PropertyDefinition.PropertyNames, String> oldValueMap = new EnumMap<>(PropertyDefinition.PropertyNames.class);
- PropertyDefinition.PropertyNames[] propertiesToCheck = new PropertyDefinition.PropertyNames[] { PropertyDefinition.PropertyNames.INITIAL_COUNT, PropertyDefinition.PropertyNames.MAX_INSTANCES, PropertyDefinition.PropertyNames.MIN_INSTANCES };
-
+ PropertyDefinition.PropertyNames[] propertiesToCheck = new PropertyDefinition.PropertyNames[]{PropertyDefinition.PropertyNames.INITIAL_COUNT,
+ PropertyDefinition.PropertyNames.MAX_INSTANCES, PropertyDefinition.PropertyNames.MIN_INSTANCES};
for (GroupProperty gp : originalGroup.convertToGroupProperties()) {
if (enumHasValueFilter(gp.getName(), PropertyDefinition.PropertyNames::findName, propertiesToCheck)) {
oldValueMap.put(PropertyDefinition.PropertyNames.findName(gp.getName()), gp.getValue());
@@ -193,35 +186,39 @@ public class GroupBusinessLogicNew {
return oldValueMap;
}
- private void validateVFInstancesLogic(Map<PropertyDefinition.PropertyNames, String> newValues, Map<PropertyDefinition.PropertyNames, String> parentValues) {
- if (!newValues.containsKey(PropertyDefinition.PropertyNames.INITIAL_COUNT)
- && !newValues.containsKey(PropertyDefinition.PropertyNames.MAX_INSTANCES)
- && !newValues.containsKey(PropertyDefinition.PropertyNames.MIN_INSTANCES)) {
+ private void validateVFInstancesLogic(Map<PropertyDefinition.PropertyNames, String> newValues,
+ Map<PropertyDefinition.PropertyNames, String> parentValues) {
+ if (!newValues.containsKey(PropertyDefinition.PropertyNames.INITIAL_COUNT) && !newValues
+ .containsKey(PropertyDefinition.PropertyNames.MAX_INSTANCES) && !newValues.containsKey(PropertyDefinition.PropertyNames.MIN_INSTANCES)) {
return;
}
int latestMaxInstances = getLatestIntProperty(newValues, parentValues, PropertyDefinition.PropertyNames.MAX_INSTANCES);
int latestInitialCount = getLatestIntProperty(newValues, parentValues, PropertyDefinition.PropertyNames.INITIAL_COUNT);
int latestMinInstances = getLatestIntProperty(newValues, parentValues, PropertyDefinition.PropertyNames.MIN_INSTANCES);
-
- if (isPropertyChanged(newValues, parentValues, PropertyDefinition.PropertyNames.INITIAL_COUNT)
- && (latestInitialCount > latestMaxInstances || latestInitialCount < latestMinInstances)) {
- throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE, PropertyDefinition.PropertyNames.INITIAL_COUNT.getPropertyName(), String.valueOf(latestMinInstances), String.valueOf(latestMaxInstances));
+ if (isPropertyChanged(newValues, parentValues, PropertyDefinition.PropertyNames.INITIAL_COUNT) && (latestInitialCount > latestMaxInstances
+ || latestInitialCount < latestMinInstances)) {
+ throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE,
+ PropertyDefinition.PropertyNames.INITIAL_COUNT.getPropertyName(), String.valueOf(latestMinInstances),
+ String.valueOf(latestMaxInstances));
}
- if (isPropertyChanged(newValues, parentValues, PropertyDefinition.PropertyNames.MAX_INSTANCES) &&
- latestMaxInstances < latestInitialCount) {
- throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyDefinition.PropertyNames.MAX_INSTANCES.getPropertyName(), "higher", String.valueOf(latestInitialCount));
+ if (isPropertyChanged(newValues, parentValues, PropertyDefinition.PropertyNames.MAX_INSTANCES) && latestMaxInstances < latestInitialCount) {
+ throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER,
+ PropertyDefinition.PropertyNames.MAX_INSTANCES.getPropertyName(), "higher", String.valueOf(latestInitialCount));
}
- if (isPropertyChanged(newValues, parentValues, PropertyDefinition.PropertyNames.MIN_INSTANCES) &&
- latestMinInstances > latestInitialCount) {
- throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyDefinition.PropertyNames.MIN_INSTANCES.getPropertyName(), "lower", String.valueOf(latestInitialCount));
+ if (isPropertyChanged(newValues, parentValues, PropertyDefinition.PropertyNames.MIN_INSTANCES) && latestMinInstances > latestInitialCount) {
+ throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER,
+ PropertyDefinition.PropertyNames.MIN_INSTANCES.getPropertyName(), "lower", String.valueOf(latestInitialCount));
}
}
- private boolean isPropertyChanged(Map<PropertyDefinition.PropertyNames, String> newValues, Map<PropertyDefinition.PropertyNames, String> parentValues, final PropertyDefinition.PropertyNames minInstances) {
+ private boolean isPropertyChanged(Map<PropertyDefinition.PropertyNames, String> newValues,
+ Map<PropertyDefinition.PropertyNames, String> parentValues,
+ final PropertyDefinition.PropertyNames minInstances) {
return newValues.containsKey(minInstances) && !newValues.get(minInstances).equals(parentValues.get(minInstances));
}
- private int getLatestIntProperty(Map<PropertyDefinition.PropertyNames, String> newValues, Map<PropertyDefinition.PropertyNames, String> parentValues, PropertyDefinition.PropertyNames propertyKey) {
+ private int getLatestIntProperty(Map<PropertyDefinition.PropertyNames, String> newValues,
+ Map<PropertyDefinition.PropertyNames, String> parentValues, PropertyDefinition.PropertyNames propertyKey) {
String value;
if (newValues.containsKey(propertyKey)) {
value = newValues.get(propertyKey);
@@ -240,22 +237,19 @@ public class GroupBusinessLogicNew {
groupProperty2Duplicate.setValue(null);
groupProperty2Duplicate.setSchema(null);
groupProperty2Duplicate.setParentUniqueId(null);
- return StringUtils.equals(groupProperty1Duplicate.getValueUniqueUid(), groupProperty2Duplicate.getValueUniqueUid())
- && groupProperty1Duplicate.equals(groupProperty2Duplicate);
+ return StringUtils.equals(groupProperty1Duplicate.getValueUniqueUid(), groupProperty2Duplicate.getValueUniqueUid()) && groupProperty1Duplicate
+ .equals(groupProperty2Duplicate);
}
private void validateFreeText(GroupProperty groupPropertyToUpdate) {
final String groupTypeValue = groupPropertyToUpdate.getValue();
if (!org.apache.commons.lang3.StringUtils.isEmpty(groupTypeValue)) {
if (!ValidationUtils.validateDescriptionLength(groupTypeValue)) {
- throw new ByActionStatusComponentException(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
- NodeTypeEnum.Property.getName(),
- String.valueOf(ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH));
+ throw new ByActionStatusComponentException(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, NodeTypeEnum.Property.getName(),
+ String.valueOf(ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH));
} else if (!ValidationUtils.validateIsEnglish(groupTypeValue)) {
- throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_DESCRIPTION,
- NodeTypeEnum.Property.getName());
+ throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_DESCRIPTION, NodeTypeEnum.Property.getName());
}
}
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java
index ee53c35884..4a67b09634 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java
@@ -21,6 +21,11 @@
*/
package org.openecomp.sdc.be.components.impl;
+import static java.util.Collections.emptySet;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
import org.openecomp.sdc.be.components.validation.UserValidations;
@@ -33,12 +38,6 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation;
import org.springframework.stereotype.Component;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import static java.util.Collections.emptySet;
-
@Component("groupTypeBusinessLogic")
public class GroupTypeBusinessLogic {
@@ -47,14 +46,14 @@ public class GroupTypeBusinessLogic {
private final UserValidations userValidations;
private final ComponentsUtils componentsUtils;
- public GroupTypeBusinessLogic(GroupTypeOperation groupTypeOperation, JanusGraphDao janusGraphDao, UserValidations userValidations, ComponentsUtils componentsUtils) {
+ public GroupTypeBusinessLogic(GroupTypeOperation groupTypeOperation, JanusGraphDao janusGraphDao, UserValidations userValidations,
+ ComponentsUtils componentsUtils) {
this.groupTypeOperation = groupTypeOperation;
this.janusGraphDao = janusGraphDao;
this.userValidations = userValidations;
this.componentsUtils = componentsUtils;
}
-
public List<GroupTypeDefinition> getAllGroupTypes(String userId, String internalComponentType) {
try {
userValidations.validateUserExists(userId);
@@ -66,16 +65,15 @@ public class GroupTypeBusinessLogic {
}
public GroupTypeDefinition getLatestGroupTypeByType(String groupTypeName) {
- return groupTypeOperation.getLatestGroupTypeByType(groupTypeName, true)
- .left()
- .on(e -> failOnGetGroupType(e, groupTypeName));
+ return groupTypeOperation.getLatestGroupTypeByType(groupTypeName, true).left().on(e -> failOnGetGroupType(e, groupTypeName));
}
public Set<String> getExcludedGroupTypes(String internalComponentType) {
if (StringUtils.isEmpty(internalComponentType)) {
return emptySet();
}
- Map<String, Set<String>> excludedGroupTypesMapping = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedGroupTypesMapping();
+ Map<String, Set<String>> excludedGroupTypesMapping = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getExcludedGroupTypesMapping();
Set<String> excludedTypes = excludedGroupTypesMapping.get(internalComponentType);
return excludedTypes == null ? emptySet() : excludedTypes;
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java
index 24cbb3e3a4..d3640a71a7 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,10 +17,13 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum;
import org.openecomp.sdc.be.components.impl.model.ToscaTypeImportData;
@@ -41,11 +44,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.stereotype.Component;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
@Component("groupTypeImportManager")
public class GroupTypeImportManager {
@@ -55,7 +53,8 @@ public class GroupTypeImportManager {
private final ToscaOperationFacade toscaOperationFacade;
private final CommonImportManager commonImportManager;
- public GroupTypeImportManager(GroupTypeOperation groupTypeOperation, ComponentsUtils componentsUtils, ToscaOperationFacade toscaOperationFacade, CommonImportManager commonImportManager) {
+ public GroupTypeImportManager(GroupTypeOperation groupTypeOperation, ComponentsUtils componentsUtils, ToscaOperationFacade toscaOperationFacade,
+ CommonImportManager commonImportManager) {
this.groupTypeOperation = groupTypeOperation;
this.componentsUtils = componentsUtils;
this.toscaOperationFacade = toscaOperationFacade;
@@ -70,22 +69,23 @@ public class GroupTypeImportManager {
return commonImportManager.createElementTypesFromYml(groupTypesYml, this::createGroupType);
}
- private Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat> upsertGroupTypesByDao(List<GroupTypeDefinition> groupTypesToCreate) {
- return commonImportManager.createElementTypesByDao(groupTypesToCreate, this::validateGroupType, groupType -> new ImmutablePair<>(ElementTypeEnum.GROUP_TYPE, groupType.getType()),
- groupTypeOperation::getLatestGroupTypeByType, groupTypeOperation::addGroupType, this::updateGroupType);
+ private Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat> upsertGroupTypesByDao(
+ List<GroupTypeDefinition> groupTypesToCreate) {
+ return commonImportManager.createElementTypesByDao(groupTypesToCreate, this::validateGroupType,
+ groupType -> new ImmutablePair<>(ElementTypeEnum.GROUP_TYPE, groupType.getType()), groupTypeOperation::getLatestGroupTypeByType,
+ groupTypeOperation::addGroupType, this::updateGroupType);
}
private Either<GroupTypeDefinition, StorageOperationStatus> updateGroupType(GroupTypeDefinition newGroupType, GroupTypeDefinition oldGroupType) {
Either<GroupTypeDefinition, StorageOperationStatus> validationRes = groupTypeOperation.validateUpdateProperties(newGroupType);
if (validationRes.isRight()) {
- log.error("#updateGroupType - One or all properties of group type {} not valid. status is {}", newGroupType, validationRes.right().value());
+ log.error("#updateGroupType - One or all properties of group type {} not valid. status is {}", newGroupType,
+ validationRes.right().value());
return validationRes;
}
-
if (TypeCompareUtils.isGroupTypesEquals(newGroupType, oldGroupType)) {
return TypeCompareUtils.typeAlreadyExists();
}
-
return groupTypeOperation.updateGroupType(newGroupType, oldGroupType);
}
@@ -98,7 +98,8 @@ public class GroupTypeImportManager {
} else {
for (String member : groupType.getMembers()) {
// Verify that such Resource exist
- Either<org.openecomp.sdc.be.model.Resource, StorageOperationStatus> eitherMemberExist = toscaOperationFacade.getLatestByToscaResourceName(member);
+ Either<org.openecomp.sdc.be.model.Resource, StorageOperationStatus> eitherMemberExist = toscaOperationFacade
+ .getLatestByToscaResourceName(member);
if (eitherMemberExist.isRight()) {
StorageOperationStatus operationStatus = eitherMemberExist.right().value();
log.debug("Error when fetching parent resource {}, error: {}", member, operationStatus);
@@ -108,16 +109,13 @@ public class GroupTypeImportManager {
break;
}
}
-
}
}
return result;
}
private GroupTypeDefinition createGroupType(String groupTypeName, Map<String, Object> toscaJson) {
-
GroupTypeDefinition groupType = new GroupTypeDefinition();
-
if (toscaJson != null) {
// Description
commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName(), groupType::setDescription);
@@ -132,11 +130,8 @@ public class GroupTypeImportManager {
groupType.setCapabilities(capabilities);
// Members
commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.MEMBERS.getElementName(), groupType::setMembers);
-
groupType.setType(groupTypeName);
-
groupType.setHighestVersion(true);
-
groupType.setVersion(TypeUtils.getFirstCertifiedVersionVersion());
}
return groupType;
@@ -148,41 +143,24 @@ public class GroupTypeImportManager {
*/
private Map<String, CapabilityDefinition> createCapabilities(Map<String, Object> toscaJson) {
CapabilityTypeToscaJsonHolder capabilityTypeToscaJsonHolder = new CapabilityTypeToscaJsonHolder();
- commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.CAPABILITIES.getElementName(), capabilityTypeToscaJsonHolder::setCapabilityTypeToscaJson);
+ commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.CAPABILITIES.getElementName(),
+ capabilityTypeToscaJsonHolder::setCapabilityTypeToscaJson);
Map<String, CapabilityDefinition> capabilities;
if (capabilityTypeToscaJsonHolder.isEmpty()) {
capabilities = Collections.emptyMap();
- }
- else {
- capabilities = commonImportManager.createElementTypesMapFromToscaJsonMap(this::createCapability, capabilityTypeToscaJsonHolder.getCapabilityTypeToscaJson());
+ } else {
+ capabilities = commonImportManager
+ .createElementTypesMapFromToscaJsonMap(this::createCapability, capabilityTypeToscaJsonHolder.getCapabilityTypeToscaJson());
}
return capabilities;
}
-
- private class CapabilityTypeToscaJsonHolder {
- private Map<String, Object> capabilityTypeToscaJson;
-
- public Map<String, Object> getCapabilityTypeToscaJson() {
- return capabilityTypeToscaJson;
- }
-
- public boolean isEmpty() {
- return capabilityTypeToscaJson == null;
- }
- public void setCapabilityTypeToscaJson(Map<String, Object> capabilityTypeToscaJson) {
- this.capabilityTypeToscaJson = capabilityTypeToscaJson;
- }
- }
-
private CapabilityDefinition createCapability(String capabilityName, Map<String, Object> toscaJson) {
CapabilityDefinition capability = new CapabilityDefinition();
-
capability.setName(capabilityName);
commonImportManager.setField(toscaJson, ToscaTagNamesEnum.TYPE.getElementName(), capability::setType);
// Properties
CommonImportManager.setProperties(toscaJson, pl -> capability.setProperties(map(pl)));
-
return capability;
}
@@ -191,9 +169,23 @@ public class GroupTypeImportManager {
* @return
*/
private List<ComponentInstanceProperty> map(List<PropertyDefinition> pl) {
- return pl.stream()
- .map(ComponentInstanceProperty::new)
- .collect(Collectors.toList());
+ return pl.stream().map(ComponentInstanceProperty::new).collect(Collectors.toList());
}
+ private class CapabilityTypeToscaJsonHolder {
+
+ private Map<String, Object> capabilityTypeToscaJson;
+
+ public Map<String, Object> getCapabilityTypeToscaJson() {
+ return capabilityTypeToscaJson;
+ }
+
+ public void setCapabilityTypeToscaJson(Map<String, Object> capabilityTypeToscaJson) {
+ this.capabilityTypeToscaJson = capabilityTypeToscaJson;
+ }
+
+ public boolean isEmpty() {
+ return capabilityTypeToscaJson == null;
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckInformer.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckInformer.java
index ddf462639b..ccc7feb4da 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckInformer.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckInformer.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import org.openecomp.sdc.common.api.HealthCheckInfo;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java
index 57e6eb54a7..ea41995683 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,11 +17,11 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
public interface IDeploymentArtifactTypeConfigGetter {
+
ArtifactTypeConfig getDeploymentArtifactConfig();
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java
index ed26eade32..f53726743c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import static org.apache.commons.collections.CollectionUtils.isEmpty;
@@ -86,10 +85,8 @@ public final class ImportUtils {
private static final CustomResolver customResolver = new CustomResolver();
private static final Yaml strictYamlLoader = new YamlLoader().getStrictYamlLoader();
-
- private static ComponentsUtils componentsUtils;
-
private static final Logger log = Logger.getLogger(ImportUtils.class);
+ private static ComponentsUtils componentsUtils;
private ImportUtils() {
}
@@ -99,21 +96,6 @@ public final class ImportUtils {
componentsUtils = componentsUtils;
}
- private static class CustomResolver extends Resolver {
-
- @Override
- protected void addImplicitResolvers() {
- // avoid implicit resolvers for strings that can be interpreted as boolean values
- addImplicitResolver(Tag.STR, EMPTY, "");
- addImplicitResolver(Tag.STR, NULL, null);
- addImplicitResolver(Tag.NULL, NULL, "~nN\0");
- addImplicitResolver(Tag.NULL, EMPTY, null);
- addImplicitResolver(Tag.INT, INT, "-+0123456789");
- addImplicitResolver(Tag.FLOAT, FLOAT, "-+0123456789.");
- addImplicitResolver(Tag.YAML, YAML, "!&*");
- }
- }
-
private static void buildMap(Map<String, Object> output, Map<String, Object> map) {
for (Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
@@ -142,56 +124,17 @@ public final class ImportUtils {
return result;
}
- private static class YamlLoader extends YamlProcessor {
-
- public Yaml getStrictYamlLoader() {
- return createYaml();
- }
- }
-
@SuppressWarnings("unchecked")
- public static Either<List<HeatParameterDefinition>, ResultStatusEnum> getHeatParamsWithoutImplicitTypes(
- String heatDecodedPayload, String artifactType) {
- Map<String, Object> heatData = (Map<String, Object>) new Yaml(new Constructor(), new Representer(),
- new DumperOptions(), customResolver).load(heatDecodedPayload);
+ public static Either<List<HeatParameterDefinition>, ResultStatusEnum> getHeatParamsWithoutImplicitTypes(String heatDecodedPayload,
+ String artifactType) {
+ Map<String, Object> heatData = (Map<String, Object>) new Yaml(new Constructor(), new Representer(), new DumperOptions(), customResolver)
+ .load(heatDecodedPayload);
return getHeatParameters(heatData, artifactType);
}
- public static class Constants {
-
- public static final String FIRST_NON_CERTIFIED_VERSION = "0.1";
- public static final String VENDOR_NAME = "ONAP (Tosca)";
- public static final String VENDOR_RELEASE = "1.0.0.wd03";
- public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE = LifecycleStateEnum.CERTIFIED;
- public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT;
- public static final boolean NORMATIVE_TYPE_HIGHEST_VERSION = true;
- public static final String ABSTRACT_CATEGORY_NAME = "Generic";
- public static final String ABSTRACT_SUBCATEGORY = "Abstract";
- public static final String DEFAULT_ICON = "defaulticon";
- public static final String INNER_VFC_DESCRIPTION = "Not reusable inner VFC";
- public static final String USER_DEFINED_RESOURCE_NAMESPACE_PREFIX = "org.openecomp.resource.";
- public static final String UI_JSON_PAYLOAD_NAME = "payloadName";
- public static final String CVFC_DESCRIPTION = "Complex node type that is used as nested type in VF";
- public static final String ESCAPED_DOUBLE_QUOTE = "\"";
- public static final String QUOTE = "'";
- public static final String VF_DESCRIPTION = "Nested VF in service";
-
- private Constants() {
- }
- }
-
- public enum ResultStatusEnum {
- ELEMENT_NOT_FOUND, GENERAL_ERROR, OK, INVALID_PROPERTY_DEFAULT_VALUE, INVALID_PROPERTY_TYPE,
- INVALID_PROPERTY_VALUE, MISSING_ENTRY_SCHEMA_TYPE, INVALID_PROPERTY_NAME, INVALID_ATTRIBUTE_NAME
- }
-
- public enum ToscaElementTypeEnum {
- BOOLEAN, STRING, MAP, LIST, ALL
- }
-
@SuppressWarnings("unchecked")
- private static void handleElementNameNotFound(String elementName, Object elementValue,
- ToscaElementTypeEnum elementType, List<Object> returnedList) {
+ private static void handleElementNameNotFound(String elementName, Object elementValue, ToscaElementTypeEnum elementType,
+ List<Object> returnedList) {
if (elementValue instanceof Map) {
findToscaElements((Map<String, Object>) elementValue, elementName, elementType, returnedList);
} else if (elementValue instanceof List) {
@@ -200,9 +143,8 @@ public final class ImportUtils {
}
@SuppressWarnings("unchecked")
- private static void addFoundElementAccordingToItsType(String elementName, ToscaElementTypeEnum elementType,
- List<Object> returnedList, Object elementValue) {
-
+ private static void addFoundElementAccordingToItsType(String elementName, ToscaElementTypeEnum elementType, List<Object> returnedList,
+ Object elementValue) {
if (elementValue instanceof Boolean) {
if (elementType == ToscaElementTypeEnum.BOOLEAN || elementType == ToscaElementTypeEnum.ALL) {
returnedList.add(elementValue);
@@ -216,13 +158,11 @@ public final class ImportUtils {
returnedList.add(elementValue);
}
findToscaElements((Map<String, Object>) elementValue, elementName, elementType, returnedList);
-
} else if (elementValue instanceof List) {
if (elementType == ToscaElementTypeEnum.LIST || elementType == ToscaElementTypeEnum.ALL) {
returnedList.add(elementValue);
}
findAllToscaElementsInList((List<Object>) elementValue, elementName, elementType, returnedList);
-
}
// For Integer, Double etc...
else if (elementType == ToscaElementTypeEnum.ALL && elementValue != null) {
@@ -230,13 +170,12 @@ public final class ImportUtils {
}
}
- private static void findAllToscaElementsInList(List<Object> list, String elementName,
- ToscaElementTypeEnum elementType, List<Object> returnedList) {
+ private static void findAllToscaElementsInList(List<Object> list, String elementName, ToscaElementTypeEnum elementType,
+ List<Object> returnedList) {
list.forEach(elementValue -> handleElementNameNotFound(elementName, elementValue, elementType, returnedList));
}
- public static Either<Object, ResultStatusEnum> findToscaElement(Map<String, Object> toscaJson,
- TypeUtils.ToscaTagNamesEnum elementName,
+ public static Either<Object, ResultStatusEnum> findToscaElement(Map<String, Object> toscaJson, TypeUtils.ToscaTagNamesEnum elementName,
ToscaElementTypeEnum elementType) {
List<Object> foundElements = new ArrayList<>();
findToscaElements(toscaJson, elementName.getElementName(), elementType, foundElements);
@@ -247,22 +186,19 @@ public final class ImportUtils {
}
/**
- * Recursively searches for all tosca elements with key equals to elementName and value equals to elementType. <br>
- * Returns Either element with:<br> List with all value if values found<br> Or ELEMENT_NOT_FOUND ActionStatus
+ * Recursively searches for all tosca elements with key equals to elementName and value equals to elementType. <br> Returns Either element
+ * with:<br> List with all value if values found<br> Or ELEMENT_NOT_FOUND ActionStatus
*
* @param toscaJson
* @return
*/
- public static Either<List<Object>, ResultStatusEnum> findToscaElements(Map<String, Object> toscaJson,
- String elementName,
- ToscaElementTypeEnum elementType,
- List<Object> returnedList) {
+ public static Either<List<Object>, ResultStatusEnum> findToscaElements(Map<String, Object> toscaJson, String elementName,
+ ToscaElementTypeEnum elementType, List<Object> returnedList) {
Either<List<Object>, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
String skipKey = null;
if (toscaJson.containsKey(elementName)) {
skipKey = handleFoundElement(toscaJson, elementName, elementType, returnedList);
}
-
Iterator<Entry<String, Object>> keyValItr = toscaJson.entrySet().iterator();
while (keyValItr.hasNext()) {
Entry<String, Object> keyValEntry = keyValItr.next();
@@ -270,53 +206,45 @@ public final class ImportUtils {
handleElementNameNotFound(elementName, keyValEntry.getValue(), elementType, returnedList);
}
}
-
if (!isEmpty(returnedList)) {
returnedElement = Either.left(returnedList);
}
-
return returnedElement;
}
- private static String handleFoundElement(Map<String, Object> toscaJson, String elementName,
- ToscaElementTypeEnum elementType, List<Object> returnedList) {
+ private static String handleFoundElement(Map<String, Object> toscaJson, String elementName, ToscaElementTypeEnum elementType,
+ List<Object> returnedList) {
Object elementValue = toscaJson.get(elementName);
addFoundElementAccordingToItsType(elementName, elementType, returnedList, elementValue);
return elementName;
-
}
@SuppressWarnings("unchecked")
public static <T> Either<List<T>, ResultStatusEnum> findFirstToscaListElement(Map<String, Object> toscaJson,
TypeUtils.ToscaTagNamesEnum toscaTagName) {
Either<List<T>, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
- Either<Object, ResultStatusEnum> findFirstToscaElement = findToscaElement(toscaJson, toscaTagName,
- ToscaElementTypeEnum.LIST);
+ Either<Object, ResultStatusEnum> findFirstToscaElement = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.LIST);
if (findFirstToscaElement.isLeft()) {
returnedElement = Either.left((List<T>) findFirstToscaElement.left().value());
}
return returnedElement;
-
}
@SuppressWarnings("unchecked")
public static <T> Either<Map<String, T>, ResultStatusEnum> findFirstToscaMapElement(Map<String, Object> toscaJson,
TypeUtils.ToscaTagNamesEnum toscaTagName) {
Either<Map<String, T>, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
- Either<Object, ResultStatusEnum> findFirstToscaElement = findToscaElement(toscaJson, toscaTagName,
- ToscaElementTypeEnum.MAP);
+ Either<Object, ResultStatusEnum> findFirstToscaElement = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.MAP);
if (findFirstToscaElement.isLeft()) {
returnedElement = Either.left((Map<String, T>) findFirstToscaElement.left().value());
}
return returnedElement;
-
}
public static Either<String, ResultStatusEnum> findFirstToscaStringElement(Map<String, Object> toscaJson,
TypeUtils.ToscaTagNamesEnum toscaTagName) {
Either<String, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
- Either<Object, ResultStatusEnum> findFirstToscaElements = findToscaElement(toscaJson, toscaTagName,
- ToscaElementTypeEnum.STRING);
+ Either<Object, ResultStatusEnum> findFirstToscaElements = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.STRING);
if (findFirstToscaElements.isLeft()) {
returnedElement = Either.left((String) findFirstToscaElements.left().value());
}
@@ -324,8 +252,7 @@ public final class ImportUtils {
}
/**
- * searches for first Tosca in Json map (toscaJson) boolean element by name (toscaTagName) returns found element or
- * ELEMENT_NOT_FOUND status
+ * searches for first Tosca in Json map (toscaJson) boolean element by name (toscaTagName) returns found element or ELEMENT_NOT_FOUND status
*
* @param toscaJson
* @param toscaTagName
@@ -334,8 +261,7 @@ public final class ImportUtils {
public static Either<String, ResultStatusEnum> findFirstToscaBooleanElement(Map<String, Object> toscaJson,
TypeUtils.ToscaTagNamesEnum toscaTagName) {
Either<String, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
- Either<Object, ResultStatusEnum> findFirstToscaElements = findToscaElement(toscaJson, toscaTagName,
- ToscaElementTypeEnum.BOOLEAN);
+ Either<Object, ResultStatusEnum> findFirstToscaElements = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.BOOLEAN);
if (findFirstToscaElements.isLeft()) {
returnedElement = Either.left(String.valueOf(findFirstToscaElements.left().value()));
}
@@ -349,8 +275,7 @@ public final class ImportUtils {
}
}
- private static List<PropertyConstraint> getPropertyConstraints(final Map<String, Object> propertyValue,
- final String propertyType) {
+ private static List<PropertyConstraint> getPropertyConstraints(final Map<String, Object> propertyValue, final String propertyType) {
final List<Object> propertyFieldConstraints = findCurrentLevelConstraintsElement(propertyValue);
if (CollectionUtils.isEmpty(propertyFieldConstraints)) {
return Collections.emptyList();
@@ -358,12 +283,9 @@ public final class ImportUtils {
final List<PropertyConstraint> constraintList = new ArrayList<>();
final Type constraintType = new TypeToken<PropertyConstraint>() {
}.getType();
- final Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser())
- .create();
-
+ final Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
for (final Object constraintJson : propertyFieldConstraints) {
- final PropertyConstraint propertyConstraint = validateAndGetPropertyConstraint(propertyType, constraintType,
- gson, constraintJson);
+ final PropertyConstraint propertyConstraint = validateAndGetPropertyConstraint(propertyType, constraintType, gson, constraintJson);
constraintList.add(propertyConstraint);
}
return constraintList;
@@ -380,26 +302,22 @@ public final class ImportUtils {
}
}
return constraints;
-
}
- private static PropertyConstraint validateAndGetPropertyConstraint(String propertyType, Type constraintType,
- Gson gson, Object constraintJson) {
+ private static PropertyConstraint validateAndGetPropertyConstraint(String propertyType, Type constraintType, Gson gson, Object constraintJson) {
PropertyConstraint propertyConstraint;
try {
propertyConstraint = gson.fromJson(gson.toJson(constraintJson), constraintType);
} catch (ClassCastException | JsonParseException e) {
- throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_CONSTRAINTS_FORMAT,
- constraintJson.toString());
+ throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_CONSTRAINTS_FORMAT, constraintJson.toString());
}
if (propertyConstraint != null && propertyConstraint instanceof ValidValuesConstraint) {
try {
((ValidValuesConstraint) propertyConstraint).validateType(propertyType);
} catch (ConstraintValueDoNotMatchPropertyTypeException e) {
- BeEcompErrorManager.getInstance().logInternalFlowError("GetInitializedPropertyConstraint",
- e.getMessage(), BeEcompErrorManager.ErrorSeverity.ERROR);
- throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_CONSTRAINTS,
- ConstraintType.VALID_VALUES.name(),
+ BeEcompErrorManager.getInstance()
+ .logInternalFlowError("GetInitializedPropertyConstraint", e.getMessage(), BeEcompErrorManager.ErrorSeverity.ERROR);
+ throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_CONSTRAINTS, ConstraintType.VALID_VALUES.name(),
((ValidValuesConstraint) propertyConstraint).getValidValues().toString(), propertyType);
}
}
@@ -407,41 +325,29 @@ public final class ImportUtils {
}
public static PropertyDefinition createModuleProperty(Map<String, Object> propertyValue) {
-
PropertyDefinition propertyDef = new PropertyDefinition();
setField(propertyValue, TypeUtils.ToscaTagNamesEnum.TYPE, propertyDef::setType);
- setFieldBoolean(propertyValue, ToscaTagNamesEnum.REQUIRED,
- req -> propertyDef.setRequired(Boolean.parseBoolean(req)));
+ setFieldBoolean(propertyValue, ToscaTagNamesEnum.REQUIRED, req -> propertyDef.setRequired(Boolean.parseBoolean(req)));
setField(propertyValue, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, propertyDef::setDescription);
-
- setJsonStringField(propertyValue, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, propertyDef.getType(),
- propertyDef::setDefaultValue);
- setJsonStringField(propertyValue, TypeUtils.ToscaTagNamesEnum.VALUE, propertyDef.getType(),
- propertyDef::setValue);
-
- setFieldBoolean(propertyValue, TypeUtils.ToscaTagNamesEnum.IS_PASSWORD,
- pass -> propertyDef.setPassword(Boolean.parseBoolean(pass)));
+ setJsonStringField(propertyValue, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, propertyDef.getType(), propertyDef::setDefaultValue);
+ setJsonStringField(propertyValue, TypeUtils.ToscaTagNamesEnum.VALUE, propertyDef.getType(), propertyDef::setValue);
+ setFieldBoolean(propertyValue, TypeUtils.ToscaTagNamesEnum.IS_PASSWORD, pass -> propertyDef.setPassword(Boolean.parseBoolean(pass)));
setField(propertyValue, TypeUtils.ToscaTagNamesEnum.STATUS, propertyDef::setStatus);
setSchema(propertyValue, propertyDef);
setPropertyConstraints(propertyValue, propertyDef);
-
return propertyDef;
}
- private static void setJsonStringField(Map<String, Object> propertyValue, ToscaTagNamesEnum elementName,
- String type, Consumer<String> setter) {
- Either<Object, ResultStatusEnum> eitherValue = findToscaElement(propertyValue, elementName,
- ToscaElementTypeEnum.ALL);
+ private static void setJsonStringField(Map<String, Object> propertyValue, ToscaTagNamesEnum elementName, String type, Consumer<String> setter) {
+ Either<Object, ResultStatusEnum> eitherValue = findToscaElement(propertyValue, elementName, ToscaElementTypeEnum.ALL);
if (eitherValue.isLeft()) {
String propertyJsonStringValue = getPropertyJsonStringValue(eitherValue.left().value(), type);
setter.accept(propertyJsonStringValue);
}
}
- public static Annotation createModuleAnnotation(Map<String, Object> annotationMap,
- AnnotationTypeOperations annotationTypeOperations) {
- String parsedAnnotationType = findFirstToscaStringElement(annotationMap, TypeUtils.ToscaTagNamesEnum.TYPE)
- .left().value();
+ public static Annotation createModuleAnnotation(Map<String, Object> annotationMap, AnnotationTypeOperations annotationTypeOperations) {
+ String parsedAnnotationType = findFirstToscaStringElement(annotationMap, TypeUtils.ToscaTagNamesEnum.TYPE).left().value();
AnnotationTypeDefinition annotationTypeObject = annotationTypeOperations.getLatestType(parsedAnnotationType);
if (annotationTypeObject != null) {
Annotation annotation = new Annotation();
@@ -464,11 +370,9 @@ public final class ImportUtils {
for (Entry<String, PropertyDefinition> entry : value.entrySet()) {
String name = entry.getKey();
if (!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(name).matches()) {
- log.debug("The property with invalid name {} occurred upon import resource {}. ", name,
- annotation.getName());
- result = Either.right(componentsUtils.getResponseFormat(componentsUtils
- .convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME,
- JsonPresentationFields.PROPERTY)));
+ log.debug("The property with invalid name {} occurred upon import resource {}. ", name, annotation.getName());
+ result = Either.right(componentsUtils.getResponseFormat(
+ componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, JsonPresentationFields.PROPERTY)));
}
PropertyDefinition propertyDefinition = entry.getValue();
propertyDefinition.setValue(propertyDefinition.getName());
@@ -478,16 +382,13 @@ public final class ImportUtils {
}
annotation.setProperties(propertiesList);
} else if (properties.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND) {
- result = Either
- .right(componentsUtils.getResponseFormat(componentsUtils.convertFromResultStatusEnum(properties
- .right()
- .value(), JsonPresentationFields.PROPERTY)));
+ result = Either.right(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromResultStatusEnum(properties.right().value(), JsonPresentationFields.PROPERTY)));
}
return result;
}
- public static InputDefinition createModuleInput(final Map<String, Object> inputValue,
- final AnnotationTypeOperations annotationTypeOperations) {
+ public static InputDefinition createModuleInput(final Map<String, Object> inputValue, final AnnotationTypeOperations annotationTypeOperations) {
return parseAnnotationsAndAddItToInput(createModuleInput(inputValue), inputValue, annotationTypeOperations);
}
@@ -496,66 +397,52 @@ public final class ImportUtils {
setField(inputValue, TypeUtils.ToscaTagNamesEnum.TYPE, inputDef::setType);
setFieldBoolean(inputValue, ToscaTagNamesEnum.REQUIRED, req -> inputDef.setRequired(Boolean.parseBoolean(req)));
setField(inputValue, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, inputDef::setDescription);
-
- setJsonStringField(inputValue, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, inputDef.getType(),
- inputDef::setDefaultValue);
-
+ setJsonStringField(inputValue, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, inputDef.getType(), inputDef::setDefaultValue);
setFieldBoolean(inputValue, TypeUtils.ToscaTagNamesEnum.IS_PASSWORD, pass -> inputDef.setPassword(Boolean.parseBoolean(pass)));
setField(inputValue, TypeUtils.ToscaTagNamesEnum.STATUS, inputDef::setStatus);
setField(inputValue, TypeUtils.ToscaTagNamesEnum.LABEL, inputDef::setLabel);
setFieldBoolean(inputValue, TypeUtils.ToscaTagNamesEnum.HIDDEN, hidden -> inputDef.setHidden(Boolean.parseBoolean(hidden)));
setFieldBoolean(inputValue, TypeUtils.ToscaTagNamesEnum.IMMUTABLE, immutable -> inputDef.setImmutable(Boolean.parseBoolean(immutable)));
-
setSchema(inputValue, inputDef);
setPropertyConstraints(inputValue, inputDef);
return inputDef;
}
- public static InputDefinition parseAnnotationsAndAddItToInput(InputDefinition inputDef,
- Map<String, Object> inputValue,
+ public static InputDefinition parseAnnotationsAndAddItToInput(InputDefinition inputDef, Map<String, Object> inputValue,
AnnotationTypeOperations annotationTypeOperations) {
Function<String, Annotation> elementGenByName = ImportUtils::createAnnotation;
- Function<Map<String, Object>, Annotation> func = annotation -> createModuleAnnotation(annotation,
- annotationTypeOperations);
- return getElements(inputValue, TypeUtils.ToscaTagNamesEnum.ANNOTATIONS, elementGenByName, func).
- left().map(annotations -> modifyInputWithAnnotations(inputDef, annotations)).
- left().on(err -> {
- log.error("Parsing annotations or adding them to the PropertyDataDefinition object failed");
- return inputDef;
- });
- }
-
- private static InputDefinition modifyInputWithAnnotations(InputDefinition inputDef,
- Map<String, Annotation> annotationsMap) {
+ Function<Map<String, Object>, Annotation> func = annotation -> createModuleAnnotation(annotation, annotationTypeOperations);
+ return getElements(inputValue, TypeUtils.ToscaTagNamesEnum.ANNOTATIONS, elementGenByName, func).left()
+ .map(annotations -> modifyInputWithAnnotations(inputDef, annotations)).left().on(err -> {
+ log.error("Parsing annotations or adding them to the PropertyDataDefinition object failed");
+ return inputDef;
+ });
+ }
+
+ private static InputDefinition modifyInputWithAnnotations(InputDefinition inputDef, Map<String, Annotation> annotationsMap) {
setAnnotationsName(annotationsMap);
inputDef.setAnnotationsToInput(annotationsMap.values());
return inputDef;
}
public static AttributeDefinition createModuleAttribute(Map<String, Object> attributeMap) {
-
AttributeDefinition attributeDef = new AttributeDefinition();
setField(attributeMap, TypeUtils.ToscaTagNamesEnum.TYPE, attributeDef::setType);
setField(attributeMap, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, attributeDef::setDescription);
setField(attributeMap, TypeUtils.ToscaTagNamesEnum.STATUS, attributeDef::setStatus);
-
- setJsonStringField(attributeMap, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, attributeDef.getType(),
- attributeDef::set_default);
-
+ setJsonStringField(attributeMap, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, attributeDef.getType(), attributeDef::set_default);
setEntrySchema(attributeMap, attributeDef);
return attributeDef;
}
- private static void setSchema(final Map<String, Object> propertyValue,
- final PropertyDefinition propertyDefinition) {
+ private static void setSchema(final Map<String, Object> propertyValue, final PropertyDefinition propertyDefinition) {
final Either<Object, ResultStatusEnum> schemaElementRes = findEntrySchemaElement(propertyValue);
if (schemaElementRes.isLeft()) {
propertyDefinition.setSchema(getSchema(schemaElementRes.left().value()));
}
}
- private static void setEntrySchema(final Map<String, Object> toscaJsonMap,
- final AttributeDefinition attributeDefinition) {
+ private static void setEntrySchema(final Map<String, Object> toscaJsonMap, final AttributeDefinition attributeDefinition) {
final Either<Object, ResultStatusEnum> schemaElementRes = findEntrySchemaElement(toscaJsonMap);
if (schemaElementRes.isLeft()) {
attributeDefinition.setEntry_schema(createEntrySchema(schemaElementRes.left().value()));
@@ -592,62 +479,48 @@ public final class ImportUtils {
return entrySchema;
}
- private static void setField(Map<String, Object> toscaJson, TypeUtils.ToscaTagNamesEnum tagName,
- Consumer<String> setter) {
+ private static void setField(Map<String, Object> toscaJson, TypeUtils.ToscaTagNamesEnum tagName, Consumer<String> setter) {
Either<String, ResultStatusEnum> fieldStringValue = findFirstToscaStringElement(toscaJson, tagName);
if (fieldStringValue.isLeft()) {
setter.accept(fieldStringValue.left().value());
}
-
}
- public static void setFieldBoolean(Map<String, Object> toscaJson, TypeUtils.ToscaTagNamesEnum tagName,
- Consumer<String> setter) {
+ public static void setFieldBoolean(Map<String, Object> toscaJson, TypeUtils.ToscaTagNamesEnum tagName, Consumer<String> setter) {
Either<String, ResultStatusEnum> fieldStringValue = findFirstToscaBooleanElement(toscaJson, tagName);
if (fieldStringValue.isLeft()) {
setter.accept(fieldStringValue.left().value());
}
-
}
- public static Either<Map<String, PropertyDefinition>, ResultStatusEnum> getProperties(
- Map<String, Object> toscaJson) {
+ public static Either<Map<String, PropertyDefinition>, ResultStatusEnum> getProperties(Map<String, Object> toscaJson) {
Function<String, PropertyDefinition> elementGenByName = ImportUtils::createProperties;
Function<Map<String, Object>, PropertyDefinition> func = ImportUtils::createModuleProperty;
-
return getElements(toscaJson, TypeUtils.ToscaTagNamesEnum.PROPERTIES, elementGenByName, func);
-
}
public static Either<Map<String, AttributeDefinition>, ResultStatusEnum> getAttributes(final Map<String, Object> toscaJson) {
final Function<String, AttributeDefinition> elementGenByName = ImportUtils::createAttribute;
final Function<Map<String, Object>, AttributeDefinition> func = ImportUtils::createModuleAttribute;
-
return getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES, elementGenByName, func);
}
public static Either<Map<String, InputDefinition>, ResultStatusEnum> getInputs(Map<String, Object> toscaJson,
AnnotationTypeOperations annotationTypeOperations) {
Function<String, InputDefinition> elementGenByName = ImportUtils::createInputs;
- Function<Map<String, Object>, InputDefinition> func = object -> createModuleInput(object,
- annotationTypeOperations);
-
+ Function<Map<String, Object>, InputDefinition> func = object -> createModuleInput(object, annotationTypeOperations);
return getElements(toscaJson, TypeUtils.ToscaTagNamesEnum.INPUTS, elementGenByName, func);
-
}
public static Either<Map<String, InputDefinition>, ResultStatusEnum> getInputs(final Map<String, Object> toscaJson) {
- return getElements(toscaJson, TypeUtils.ToscaTagNamesEnum.INPUTS, ImportUtils::createInputs,
- ImportUtils::createModuleInput);
+ return getElements(toscaJson, TypeUtils.ToscaTagNamesEnum.INPUTS, ImportUtils::createInputs, ImportUtils::createModuleInput);
}
- public static <T> Either<Map<String, T>, ResultStatusEnum> getElements(Map<String, Object> toscaJson,
- TypeUtils.ToscaTagNamesEnum elementTagName,
+ public static <T> Either<Map<String, T>, ResultStatusEnum> getElements(Map<String, Object> toscaJson, TypeUtils.ToscaTagNamesEnum elementTagName,
Function<String, T> elementGenByName,
Function<Map<String, Object>, T> func) {
Either<Map<String, T>, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
- Either<Map<String, Object>, ResultStatusEnum> toscaAttributes = findFirstToscaMapElement(toscaJson,
- elementTagName);
+ Either<Map<String, Object>, ResultStatusEnum> toscaAttributes = findFirstToscaMapElement(toscaJson, elementTagName);
if (toscaAttributes.isLeft()) {
Map<String, Object> jsonAttributes = toscaAttributes.left().value();
Map<String, T> moduleAttributes = new HashMap<>();
@@ -655,8 +528,7 @@ public final class ImportUtils {
while (propertiesNameValue.hasNext()) {
Entry<String, Object> attributeNameValue = propertiesNameValue.next();
if (attributeNameValue.getValue() instanceof Map) {
- @SuppressWarnings("unchecked")
- T attribute = func.apply((Map<String, Object>) attributeNameValue.getValue());
+ @SuppressWarnings("unchecked") T attribute = func.apply((Map<String, Object>) attributeNameValue.getValue());
if (attribute != null) {
moduleAttributes.put(String.valueOf(attributeNameValue.getKey()), attribute);
}
@@ -668,15 +540,12 @@ public final class ImportUtils {
if (moduleAttributes.size() > 0) {
eitherResult = Either.left(moduleAttributes);
}
-
}
return eitherResult;
-
}
private static AttributeDefinition createAttribute(String name) {
AttributeDefinition attribute = new AttributeDefinition();
-
attribute.setName(name);
return attribute;
}
@@ -690,7 +559,6 @@ public final class ImportUtils {
private static InputDefinition createInputs(String name) {
InputDefinition input = new InputDefinition();
-
input.setName(name);
return input;
}
@@ -702,11 +570,8 @@ public final class ImportUtils {
}
public static Either<List<HeatParameterDefinition>, ResultStatusEnum> getHeatParameters(Map<String, Object> heatData, String artifactType) {
-
- Either<List<HeatParameterDefinition>, ResultStatusEnum> eitherResult = Either
- .right(ResultStatusEnum.ELEMENT_NOT_FOUND);
- Either<Map<String, Object>, ResultStatusEnum> toscaProperties = findFirstToscaMapElement(heatData,
- TypeUtils.ToscaTagNamesEnum.PARAMETERS);
+ Either<List<HeatParameterDefinition>, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
+ Either<Map<String, Object>, ResultStatusEnum> toscaProperties = findFirstToscaMapElement(heatData, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
if (toscaProperties.isLeft()) {
Map<String, Object> jsonProperties = toscaProperties.left().value();
List<HeatParameterDefinition> moduleProperties = new ArrayList<>();
@@ -715,8 +580,7 @@ public final class ImportUtils {
Entry<String, Object> propertyNameValue = propertiesNameValue.next();
if (propertyNameValue.getValue() instanceof Map || propertyNameValue.getValue() instanceof List) {
if (!artifactType.equals(ArtifactTypeEnum.HEAT_ENV.getType())) {
- @SuppressWarnings("unchecked")
- Either<HeatParameterDefinition, ResultStatusEnum> propertyStatus = createModuleHeatParameter(
+ @SuppressWarnings("unchecked") Either<HeatParameterDefinition, ResultStatusEnum> propertyStatus = createModuleHeatParameter(
(Map<String, Object>) propertyNameValue.getValue());
if (propertyStatus.isRight()) {
return Either.right(propertyStatus.right().value());
@@ -730,36 +594,29 @@ public final class ImportUtils {
} else {
addHeatParamDefinition(moduleProperties, propertyNameValue, false);
}
-
}
-
if (!isEmpty(moduleProperties)) {
eitherResult = Either.left(moduleProperties);
}
-
}
return eitherResult;
-
}
- private static void addHeatParamDefinition(List<HeatParameterDefinition> moduleProperties,
- Entry<String, Object> propertyNameValue, boolean isJson) {
+ private static void addHeatParamDefinition(List<HeatParameterDefinition> moduleProperties, Entry<String, Object> propertyNameValue,
+ boolean isJson) {
HeatParameterDefinition property = new HeatParameterDefinition();
Object value = propertyNameValue.getValue();
if (value != null) {
- property.setDefaultValue(
- isJson ? new Gson().toJson(value) : StringEscapeUtils.escapeJava(String.valueOf(value)));
+ property.setDefaultValue(isJson ? new Gson().toJson(value) : StringEscapeUtils.escapeJava(String.valueOf(value)));
}
property.setName(String.valueOf(propertyNameValue.getKey()));
moduleProperties.add(property);
}
- private static Either<HeatParameterDefinition, ResultStatusEnum> createModuleHeatParameter(
- Map<String, Object> propertyValue) {
+ private static Either<HeatParameterDefinition, ResultStatusEnum> createModuleHeatParameter(Map<String, Object> propertyValue) {
HeatParameterDefinition propertyDef = new HeatParameterDefinition();
String type;
- Either<String, ResultStatusEnum> propertyFieldType = findFirstToscaStringElement(propertyValue,
- TypeUtils.ToscaTagNamesEnum.TYPE);
+ Either<String, ResultStatusEnum> propertyFieldType = findFirstToscaStringElement(propertyValue, TypeUtils.ToscaTagNamesEnum.TYPE);
if (propertyFieldType.isLeft()) {
type = propertyFieldType.left().value();
propertyDef.setType(type);
@@ -771,20 +628,18 @@ public final class ImportUtils {
if (propertyFieldDescription.isLeft()) {
propertyDef.setDescription(propertyFieldDescription.left().value());
}
-
- Either<Object, ResultStatusEnum> propertyFieldDefaultVal = findToscaElement(propertyValue,
- TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL);
+ Either<Object, ResultStatusEnum> propertyFieldDefaultVal = findToscaElement(propertyValue, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE,
+ ToscaElementTypeEnum.ALL);
if (propertyFieldDefaultVal.isLeft()) {
if (propertyFieldDefaultVal.left().value() == null) {
return Either.right(ResultStatusEnum.INVALID_PROPERTY_VALUE);
}
Object value = propertyFieldDefaultVal.left().value();
- String defaultValue = type.equals(HeatParameterType.JSON.getType()) ? new Gson().toJson(value)
- : StringEscapeUtils.escapeJava(String.valueOf(value));
+ String defaultValue =
+ type.equals(HeatParameterType.JSON.getType()) ? new Gson().toJson(value) : StringEscapeUtils.escapeJava(String.valueOf(value));
propertyDef.setDefaultValue(defaultValue);
propertyDef.setCurrentValue(defaultValue);
}
-
return Either.left(propertyDef);
}
@@ -799,16 +654,14 @@ public final class ImportUtils {
return null;
}
ToscaPropertyType validType = ToscaPropertyType.isValidType(type);
- if (validType == null || validType == ToscaPropertyType.JSON || validType == ToscaPropertyType.MAP
- || validType == ToscaPropertyType.LIST) {
+ if (validType == null || validType == ToscaPropertyType.JSON || validType == ToscaPropertyType.MAP || validType == ToscaPropertyType.LIST) {
return gson.toJson(value);
}
return value.toString();
}
/**
- * removes from Json map (toscaJson) first element found by name (elementName) note that this method could update
- * the received argument toscaJson
+ * removes from Json map (toscaJson) first element found by name (elementName) note that this method could update the received argument toscaJson
*
* @param toscaJson
* @param elementName
@@ -825,4 +678,57 @@ public final class ImportUtils {
}
}
}
+
+ public enum ResultStatusEnum {
+ ELEMENT_NOT_FOUND, GENERAL_ERROR, OK, INVALID_PROPERTY_DEFAULT_VALUE, INVALID_PROPERTY_TYPE, INVALID_PROPERTY_VALUE, MISSING_ENTRY_SCHEMA_TYPE, INVALID_PROPERTY_NAME, INVALID_ATTRIBUTE_NAME
+ }
+
+ public enum ToscaElementTypeEnum {
+ BOOLEAN, STRING, MAP, LIST, ALL
+ }
+
+ private static class CustomResolver extends Resolver {
+
+ @Override
+ protected void addImplicitResolvers() {
+ // avoid implicit resolvers for strings that can be interpreted as boolean values
+ addImplicitResolver(Tag.STR, EMPTY, "");
+ addImplicitResolver(Tag.STR, NULL, null);
+ addImplicitResolver(Tag.NULL, NULL, "~nN\0");
+ addImplicitResolver(Tag.NULL, EMPTY, null);
+ addImplicitResolver(Tag.INT, INT, "-+0123456789");
+ addImplicitResolver(Tag.FLOAT, FLOAT, "-+0123456789.");
+ addImplicitResolver(Tag.YAML, YAML, "!&*");
+ }
+ }
+
+ private static class YamlLoader extends YamlProcessor {
+
+ public Yaml getStrictYamlLoader() {
+ return createYaml();
+ }
+ }
+
+ public static class Constants {
+
+ public static final String FIRST_NON_CERTIFIED_VERSION = "0.1";
+ public static final String VENDOR_NAME = "ONAP (Tosca)";
+ public static final String VENDOR_RELEASE = "1.0.0.wd03";
+ public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE = LifecycleStateEnum.CERTIFIED;
+ public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT;
+ public static final boolean NORMATIVE_TYPE_HIGHEST_VERSION = true;
+ public static final String ABSTRACT_CATEGORY_NAME = "Generic";
+ public static final String ABSTRACT_SUBCATEGORY = "Abstract";
+ public static final String DEFAULT_ICON = "defaulticon";
+ public static final String INNER_VFC_DESCRIPTION = "Not reusable inner VFC";
+ public static final String USER_DEFINED_RESOURCE_NAMESPACE_PREFIX = "org.openecomp.resource.";
+ public static final String UI_JSON_PAYLOAD_NAME = "payloadName";
+ public static final String CVFC_DESCRIPTION = "Complex node type that is used as nested type in VF";
+ public static final String ESCAPED_DOUBLE_QUOTE = "\"";
+ public static final String QUOTE = "'";
+ public static final String VF_DESCRIPTION = "Nested VF in service";
+
+ private Constants() {
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java
index 2f43a5b736..da84921a5b 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,10 +19,18 @@
* Modifications copyright (c) 2019 Nokia
* ================================================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.collections4.MapUtils;
@@ -76,22 +84,11 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
@org.springframework.stereotype.Component("inputsBusinessLogic")
public class InputsBusinessLogic extends BaseBusinessLogic {
private static final String CREATE_INPUT = "CreateInput";
private static final String UPDATE_INPUT = "UpdateInput";
-
private static final Logger log = Logger.getLogger(InputsBusinessLogic.class);
private static final String FAILED_TO_FOUND_COMPONENT_ERROR = "Failed to found component {}, error: {}";
private static final String GET_PROPERTIES_BY_INPUT = "get Properties by input";
@@ -101,23 +98,19 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
private static final String GOING_TO_EXECUTE_ROLLBACK_ON_UPDATE_INPUT = "Going to execute rollback on update input.";
private static final String GOING_TO_EXECUTE_COMMIT_ON_UPDATE_INPUT = "Going to execute commit on update input.";
private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(InputsBusinessLogic.class.getName());
-
private final PropertyDeclarationOrchestrator propertyDeclarationOrchestrator;
private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
private final DataTypeBusinessLogic dataTypeBusinessLogic;
@Autowired
- public InputsBusinessLogic(IElementOperation elementDao,
- IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation,
- IGroupTypeOperation groupTypeOperation,
- InterfaceOperation interfaceOperation,
- InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
- PropertyDeclarationOrchestrator propertyDeclarationOrchestrator,
- ComponentInstanceBusinessLogic componentInstanceBusinessLogic, DataTypeBusinessLogic dataTypeBusinessLogic,
- ArtifactsOperations artifactToscaOperation) {
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
- interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+ public InputsBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+ IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
+ InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+ PropertyDeclarationOrchestrator propertyDeclarationOrchestrator,
+ ComponentInstanceBusinessLogic componentInstanceBusinessLogic, DataTypeBusinessLogic dataTypeBusinessLogic,
+ ArtifactsOperations artifactToscaOperation) {
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+ artifactToscaOperation);
this.propertyDeclarationOrchestrator = propertyDeclarationOrchestrator;
this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
this.dataTypeBusinessLogic = dataTypeBusinessLogic;
@@ -131,59 +124,50 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
* @return
*/
public Either<List<InputDefinition>, ResponseFormat> getInputs(String userId, String componentId) {
-
validateUserExists(userId);
-
ComponentParametersView filters = new ComponentParametersView();
filters.disableAll();
filters.setIgnoreInputs(false);
-
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
- if(getComponentEither.isRight()){
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade
+ .getToscaElement(componentId, filters);
+ if (getComponentEither.isRight()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, componentId, actionStatus);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
}
org.openecomp.sdc.be.model.Component component = getComponentEither.left().value();
List<InputDefinition> inputs = component.getInputs();
-
return Either.left(inputs);
-
}
- public Either<List<ComponentInstanceInput>, ResponseFormat> getComponentInstanceInputs(String userId, String componentId, String componentInstanceId) {
-
+ public Either<List<ComponentInstanceInput>, ResponseFormat> getComponentInstanceInputs(String userId, String componentId,
+ String componentInstanceId) {
validateUserExists(userId);
ComponentParametersView filters = new ComponentParametersView();
filters.disableAll();
filters.setIgnoreInputs(false);
filters.setIgnoreComponentInstances(false);
filters.setIgnoreComponentInstancesInputs(false);
-
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
- if(getComponentEither.isRight()){
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade
+ .getToscaElement(componentId, filters);
+ if (getComponentEither.isRight()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, componentId, actionStatus);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
}
org.openecomp.sdc.be.model.Component component = getComponentEither.left().value();
-
- if(!ComponentValidations.validateComponentInstanceExist(component, componentInstanceId)){
+ if (!ComponentValidations.validateComponentInstanceExist(component, componentInstanceId)) {
ActionStatus actionStatus = ActionStatus.COMPONENT_INSTANCE_NOT_FOUND;
log.debug("Failed to found component instance inputs {}, error: {}", componentInstanceId, actionStatus);
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,component.getComponentMetadataForSupportLog(),
- StatusCode.ERROR,"Failed to found component instance inputs componentInstanceId: {}",componentInstanceId);
+ loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, component.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "Failed to found component instance inputs componentInstanceId: {}", componentInstanceId);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
}
- Map<String, List<ComponentInstanceInput>> ciInputs =
- Optional.ofNullable(component.getComponentInstancesInputs()).orElse(Collections.emptyMap());
-
- // Set Constraints on Input
- MapUtils.emptyIfNull(ciInputs).values()
- .forEach(inputs -> ListUtils.emptyIfNull(inputs)
- .forEach(input -> input.setConstraints(setInputConstraint(input))));
+ Map<String, List<ComponentInstanceInput>> ciInputs = Optional.ofNullable(component.getComponentInstancesInputs())
+ .orElse(Collections.emptyMap());
+ // Set Constraints on Input
+ MapUtils.emptyIfNull(ciInputs).values()
+ .forEach(inputs -> ListUtils.emptyIfNull(inputs).forEach(input -> input.setConstraints(setInputConstraint(input))));
return Either.left(ciInputs.getOrDefault(componentInstanceId, Collections.emptyList()));
}
@@ -195,59 +179,47 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
* @param inputId
* @return
*/
-
- public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesByInputId(String userId, String componentId, String instanceId, String inputId) {
+ public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesByInputId(String userId, String componentId,
+ String instanceId, String inputId) {
validateUserExists(userId);
String parentId = componentId;
org.openecomp.sdc.be.model.Component component;
ComponentParametersView filters = new ComponentParametersView();
filters.disableAll();
filters.setIgnoreComponentInstances(false);
-
- if(!instanceId.equals(inputId)){
-
-
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters);
-
- if(getComponentEither.isRight()){
+ if (!instanceId.equals(inputId)) {
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade
+ .getToscaElement(parentId, filters);
+ if (getComponentEither.isRight()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, parentId, actionStatus);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
}
component = getComponentEither.left().value();
- Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(instanceId)).findAny();
- if(ciOp.isPresent()){
+ Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findAny();
+ if (ciOp.isPresent()) {
parentId = ciOp.get().getComponentUid();
}
-
}
-
filters.setIgnoreInputs(false);
-
filters.setIgnoreComponentInstancesProperties(false);
filters.setIgnoreComponentInstancesInputs(false);
filters.setIgnoreProperties(false);
-
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters);
-
- if(getComponentEither.isRight()){
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade
+ .getToscaElement(parentId, filters);
+ if (getComponentEither.isRight()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, parentId, actionStatus);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
}
component = getComponentEither.left().value();
-
Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
- if(!op.isPresent()){
+ if (!op.isPresent()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
log.debug(FAILED_TO_FOUND_INPUT_UNDER_COMPONENT_ERROR, inputId, parentId, actionStatus);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
}
-
return Either.left(componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, inputId));
-
}
private String updateInputObjectValue(InputDefinition currentInput, InputDefinition newInput, Map<String, DataTypeDefinition> dataTypes) {
@@ -255,7 +227,6 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
String propertyType = currentInput.getType();
ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
log.debug("The type of the property {} is {}", currentInput.getUniqueId(), propertyType);
-
if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
SchemaDefinition def = currentInput.getSchema();
if (def == null) {
@@ -270,14 +241,14 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
innerType = propDef.getType();
}
// Specific Update Logic
-
- Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, newInput.getDefaultValue(), true, innerType, dataTypes);
-
+ Either<Object, Boolean> isValid = propertyOperation
+ .validateAndUpdatePropertyValue(propertyType, newInput.getDefaultValue(), true, innerType, dataTypes);
String newValue = newInput.getDefaultValue();
if (isValid.isRight()) {
Boolean res = isValid.right().value();
if (Boolean.FALSE.equals(res)) {
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
+ DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
}
} else {
Object object = isValid.left().value();
@@ -292,25 +263,22 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
return componentsOldInputs.stream().filter(in -> in.getUniqueId().equals(input.getUniqueId())).findFirst().orElse(null);
}
- public Either<List<InputDefinition>, ResponseFormat> updateInputsValue(ComponentTypeEnum componentType, String componentId, List<InputDefinition> inputs, String userId, boolean shouldLockComp, boolean inTransaction) {
-
+ public Either<List<InputDefinition>, ResponseFormat> updateInputsValue(ComponentTypeEnum componentType, String componentId,
+ List<InputDefinition> inputs, String userId, boolean shouldLockComp,
+ boolean inTransaction) {
List<InputDefinition> returnInputs = new ArrayList<>();
Either<List<InputDefinition>, ResponseFormat> result = null;
org.openecomp.sdc.be.model.Component component = null;
-
try {
validateUserExists(userId);
-
ComponentParametersView componentParametersView = new ComponentParametersView();
componentParametersView.disableAll();
componentParametersView.setIgnoreInputs(false);
componentParametersView.setIgnoreUsers(false);
- componentParametersView.setIgnoreProperties(false);
- componentParametersView.setIgnoreComponentInstancesProperties(false);
- componentParametersView.setIgnoreComponentInstances(false);
-
+ componentParametersView.setIgnoreProperties(false);
+ componentParametersView.setIgnoreComponentInstancesProperties(false);
+ componentParametersView.setIgnoreComponentInstances(false);
component = validateComponentExists(componentId, componentType, componentParametersView);
-
if (shouldLockComp) {
try {
lockComponent(component, UPDATE_INPUT);
@@ -320,21 +288,17 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
return result;
}
}
-
//Validate value and Constraint of input
- Either<Boolean, ResponseFormat> constraintValidatorResponse = validateInputValueConstraint(inputs);
+ Either<Boolean, ResponseFormat> constraintValidatorResponse = validateInputValueConstraint(inputs);
if (constraintValidatorResponse.isRight()) {
- log.error("Failed validation value and constraint of property: {}",
- constraintValidatorResponse.right().value());
+ log.error("Failed validation value and constraint of property: {}", constraintValidatorResponse.right().value());
return Either.right(constraintValidatorResponse.right().value());
}
-
validateCanWorkOnComponent(component, userId);
Map<String, DataTypeDefinition> dataTypes;
dataTypes = getAllDataTypes(applicationDataTypeCache);
-
List<InputDefinition> componentsOldInputs = Optional.ofNullable(component.getInputs()).orElse(Collections.emptyList());
- for (InputDefinition newInput: inputs) {
+ for (InputDefinition newInput : inputs) {
InputDefinition currInput = getInputFromInputsListById(componentsOldInputs, newInput);
if (currInput == null) {
ActionStatus actionStatus = ActionStatus.COMPONENT_NOT_FOUND;
@@ -350,7 +314,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
currInput.setRequired(newInput.isRequired());
}
Either<InputDefinition, StorageOperationStatus> status = toscaOperationFacade.updateInputOfComponent(component, currInput);
- if(status.isRight()){
+ if (status.isRight()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status.right().value());
result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
return result;
@@ -362,37 +326,32 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
} catch (ComponentException e) {
log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_UPDATE_INPUT);
unlockRollbackWithException(component, e);
- } catch (Exception e){
+ } catch (Exception e) {
log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_UPDATE_INPUT);
unlockRollbackWithException(component, new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR));
}
log.debug(GOING_TO_EXECUTE_COMMIT_ON_UPDATE_INPUT);
unlockWithCommit(component);
return result;
-
}
private Either<Boolean, ResponseFormat> validateInputValueConstraint(List<InputDefinition> inputs) {
- PropertyValueConstraintValidationUtil propertyValueConstraintValidationUtil =
- PropertyValueConstraintValidationUtil.getInstance();
- List<InputDefinition> inputDefinitions = new ArrayList<>();
- for (InputDefinition inputDefinition : inputs) {
- InputDefinition inputDef = new InputDefinition();
- inputDefinition.setDefaultValue(inputDefinition.getDefaultValue());
- inputDefinition.setInputPath(inputDefinition.getSubPropertyInputPath());
- inputDefinition.setType(inputDefinition.getType());
- if (Objects.nonNull(inputDefinition.getParentPropertyType())) {
- ComponentInstanceProperty propertyDefinition = new ComponentInstanceProperty();
- propertyDefinition.setType(inputDefinition.getParentPropertyType());
-
- inputDefinition.setProperties(Collections.singletonList(propertyDefinition));
- }
-
- inputDefinitions.add(inputDef);
- }
-
- return propertyValueConstraintValidationUtil.validatePropertyConstraints(inputDefinitions, applicationDataTypeCache);
- }
+ PropertyValueConstraintValidationUtil propertyValueConstraintValidationUtil = PropertyValueConstraintValidationUtil.getInstance();
+ List<InputDefinition> inputDefinitions = new ArrayList<>();
+ for (InputDefinition inputDefinition : inputs) {
+ InputDefinition inputDef = new InputDefinition();
+ inputDefinition.setDefaultValue(inputDefinition.getDefaultValue());
+ inputDefinition.setInputPath(inputDefinition.getSubPropertyInputPath());
+ inputDefinition.setType(inputDefinition.getType());
+ if (Objects.nonNull(inputDefinition.getParentPropertyType())) {
+ ComponentInstanceProperty propertyDefinition = new ComponentInstanceProperty();
+ propertyDefinition.setType(inputDefinition.getParentPropertyType());
+ inputDefinition.setProperties(Collections.singletonList(propertyDefinition));
+ }
+ inputDefinitions.add(inputDef);
+ }
+ return propertyValueConstraintValidationUtil.validatePropertyConstraints(inputDefinitions, applicationDataTypeCache);
+ }
public Either<List<ComponentInstanceInput>, ResponseFormat> getInputsForComponentInput(String userId, String componentId, String inputId) {
validateUserExists(userId);
@@ -403,59 +362,46 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
filters.setIgnoreInputs(false);
filters.setIgnoreComponentInstancesInputs(false);
filters.setIgnoreProperties(false);
-
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
-
- if(getComponentEither.isRight()){
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade
+ .getToscaElement(componentId, filters);
+ if (getComponentEither.isRight()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, componentId, actionStatus);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
}
component = getComponentEither.left().value();
-
Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
- if(!op.isPresent()){
+ if (!op.isPresent()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
log.debug(FAILED_TO_FOUND_INPUT_UNDER_COMPONENT_ERROR, inputId, componentId, actionStatus);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
}
-
return Either.left(componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, inputId));
-
}
@Override
- public Either<List<InputDefinition>, ResponseFormat> declareProperties(String userId, String componentId,
- ComponentTypeEnum componentTypeEnum, ComponentInstInputsMap componentInstInputsMap) {
-
+ public Either<List<InputDefinition>, ResponseFormat> declareProperties(String userId, String componentId, ComponentTypeEnum componentTypeEnum,
+ ComponentInstInputsMap componentInstInputsMap) {
return createMultipleInputs(userId, componentId, componentTypeEnum, componentInstInputsMap, true, false);
}
- public Either<List<InputDefinition>, ResponseFormat> createMultipleInputs(String userId, String componentId, ComponentTypeEnum componentType, ComponentInstInputsMap componentInstInputsMapUi, boolean shouldLockComp, boolean inTransaction) {
-
+ public Either<List<InputDefinition>, ResponseFormat> createMultipleInputs(String userId, String componentId, ComponentTypeEnum componentType,
+ ComponentInstInputsMap componentInstInputsMapUi, boolean shouldLockComp,
+ boolean inTransaction) {
Either<List<InputDefinition>, ResponseFormat> result = null;
org.openecomp.sdc.be.model.Component component = null;
-
try {
validateUserExists(userId);
-
component = getAndValidateComponentForCreate(userId, componentId, componentType, shouldLockComp);
-
- result = propertyDeclarationOrchestrator.declarePropertiesToInputs(component, componentInstInputsMapUi)
- .left()
- .bind(inputsToCreate -> prepareInputsForCreation(userId, componentId, inputsToCreate))
- .right()
- .map(componentsUtils::getResponseFormat);
-
+ result = propertyDeclarationOrchestrator.declarePropertiesToInputs(component, componentInstInputsMapUi).left()
+ .bind(inputsToCreate -> prepareInputsForCreation(userId, componentId, inputsToCreate)).right()
+ .map(componentsUtils::getResponseFormat);
return result;
-
} catch (ByResponseFormatComponentException e) {
log.error("#createMultipleInputs: Exception thrown: ", e);
result = Either.right(e.getResponseFormat());
return result;
} finally {
-
if (!inTransaction) {
if (result == null || result.isRight()) {
log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP);
@@ -469,29 +415,25 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
if (shouldLockComp && component != null) {
graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
}
-
}
}
/**
* Creates a list input with a data type which has properties specified.
*
- * @param userId User ID
- * @param componentId Component ID
- * @param componentType Component type
+ * @param userId User ID
+ * @param componentId Component ID
+ * @param componentType Component type
* @param componentListInput Properties to be declared and input to be created
- * @param shouldLockComp true if the component should be locked
- * @param inTransaction true if already in transaction
+ * @param shouldLockComp true if the component should be locked
+ * @param inTransaction true if already in transaction
*/
- public Either<List<InputDefinition>, ResponseFormat> createListInput(String userId, String componentId,
- ComponentTypeEnum componentType, ComponentInstListInput componentListInput, boolean shouldLockComp,
- boolean inTransaction) {
-
+ public Either<List<InputDefinition>, ResponseFormat> createListInput(String userId, String componentId, ComponentTypeEnum componentType,
+ ComponentInstListInput componentListInput, boolean shouldLockComp,
+ boolean inTransaction) {
Either<List<InputDefinition>, ResponseFormat> result = null;
org.openecomp.sdc.be.model.Component component = null;
-
log.trace("#createListInput: enter");
-
try {
/* check if user exists */
validateUserExists(userId);
@@ -608,22 +550,24 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
return dataType;
}
- private Either<List<InputDefinition>, StorageOperationStatus> prepareInputsForCreation(String userId, String cmptId, List<InputDefinition> inputsToCreate) {
+ private Either<List<InputDefinition>, StorageOperationStatus> prepareInputsForCreation(String userId, String cmptId,
+ List<InputDefinition> inputsToCreate) {
Map<String, InputDefinition> inputsToPersist = MapUtil.toMap(inputsToCreate, InputDefinition::getName);
assignOwnerIdToInputs(userId, inputsToPersist);
- inputsToPersist.values()
- .forEach(input -> input.setConstraints(componentInstanceBusinessLogic.setInputConstraint(input)));
+ inputsToPersist.values()
+ .forEach(input -> input.setConstraints(componentInstanceBusinessLogic.setInputConstraint(input)));
return toscaOperationFacade.addInputsToComponent(inputsToPersist, cmptId)
- .left()
- .map(persistedInputs -> inputsToCreate);
+ .left()
+ .map(persistedInputs -> inputsToCreate);
}
private void assignOwnerIdToInputs(String userId, Map<String, InputDefinition> inputsToCreate) {
inputsToCreate.values().forEach(inputDefinition -> inputDefinition.setOwnerId(userId));
}
- public Either<List<InputDefinition>, ResponseFormat> createInputsInGraph(Map<String, InputDefinition> inputs, org.openecomp.sdc.be.model.Component component) {
+ public Either<List<InputDefinition>, ResponseFormat> createInputsInGraph(Map<String, InputDefinition> inputs,
+ org.openecomp.sdc.be.model.Component component) {
List<InputDefinition> resourceProperties = component.getInputs();
@@ -634,22 +578,24 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
inputDefinition.getValue().setName(inputName);
Either<InputDefinition, ResponseFormat> preparedInputEither = prepareAndValidateInputBeforeCreate(inputDefinition.getValue(), dataTypes);
- if(preparedInputEither.isRight()){
+ if (preparedInputEither.isRight()) {
return Either.right(preparedInputEither.right().value());
}
}
if (resourceProperties != null) {
- Map<String, InputDefinition> generatedInputs = resourceProperties.stream().collect(Collectors.toMap(PropertyDataDefinition::getName, i -> i));
+ Map<String, InputDefinition> generatedInputs = resourceProperties.stream()
+ .collect(Collectors.toMap(PropertyDataDefinition::getName, i -> i));
Either<Map<String, InputDefinition>, String> mergeEither = ToscaDataDefinition.mergeDataMaps(generatedInputs, inputs);
- if(mergeEither.isRight()){
+ if (mergeEither.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, mergeEither.right().value()));
}
inputs = mergeEither.left().value();
}
- Either<List<InputDefinition>, StorageOperationStatus> associateInputsEither = toscaOperationFacade.createAndAssociateInputs(inputs, component.getUniqueId());
- if(associateInputsEither.isRight()){
+ Either<List<InputDefinition>, StorageOperationStatus> associateInputsEither = toscaOperationFacade
+ .createAndAssociateInputs(inputs, component.getUniqueId());
+ if (associateInputsEither.isRight()) {
log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), associateInputsEither.right().value());
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(associateInputsEither.right().value())));
@@ -658,12 +604,13 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
}
private Either<List<InputDefinition>, ResponseFormat> createListInputsInGraph(Map<String, InputDefinition> inputs,
- Map<String, DataTypeDefinition> privateDataTypes, org.openecomp.sdc.be.model.Component component) {
+ Map<String, DataTypeDefinition> privateDataTypes,
+ org.openecomp.sdc.be.model.Component component) {
log.trace("#createListInputsInGraph: enter");
Map<String, DataTypeDefinition> dataTypes = getAllDataTypes(
- applicationDataTypeCache);
+ applicationDataTypeCache);
dataTypes.putAll(privateDataTypes);
for (Map.Entry<String, InputDefinition> inputDefinition : inputs.entrySet()) {
@@ -698,99 +645,86 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
* @return
*/
public InputDefinition deleteInput(String componentId, String userId, String inputId) {
-
Either<InputDefinition, ResponseFormat> deleteEither = null;
if (log.isDebugEnabled()) {
log.debug("Going to delete input id: {}", inputId);
}
-
validateUserExists(userId);
-
ComponentParametersView componentParametersView = getBaseComponentParametersView();
componentParametersView.setIgnoreInterfaces(false);
componentParametersView.setIgnoreDataType(false);
componentParametersView.setIgnoreProperties(false);
-
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentEither =
- toscaOperationFacade.getToscaElement(componentId, componentParametersView);
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentEither = toscaOperationFacade
+ .getToscaElement(componentId, componentParametersView);
if (componentEither.isRight()) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(componentEither.right().value()));
}
org.openecomp.sdc.be.model.Component component = componentEither.left().value();
-
// Validate inputId is child of the component
Optional<InputDefinition> optionalInput = component.getInputs().stream().
- // filter by ID
- filter(input -> input.getUniqueId().equals(inputId)).
- // Get the input
- findAny();
+ // filter by ID
+ filter(input -> input.getUniqueId().equals(inputId)).
+ // Get the input
+ findAny();
if (!optionalInput.isPresent()) {
throw new ByActionStatusComponentException(ActionStatus.INPUT_IS_NOT_CHILD_OF_COMPONENT, inputId, componentId);
}
-
InputDefinition inputForDelete = optionalInput.get();
-
// Lock component
lockComponent(componentId, component, "deleteInput");
// Delete input operations
boolean failed = false;
try {
- StorageOperationStatus status =
- toscaOperationFacade.deleteInputOfResource(component, inputForDelete.getName());
+ StorageOperationStatus status = toscaOperationFacade.deleteInputOfResource(component, inputForDelete.getName());
if (status != StorageOperationStatus.OK) {
log.debug("Component id: {} delete input id: {} failed", componentId, inputId);
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), component.getName());
}
-
- if (BooleanUtils.isTrue(inputForDelete.getIsDeclaredListInput())){
+ if (BooleanUtils.isTrue(inputForDelete.getIsDeclaredListInput())) {
deleteEither = deleteListInput(componentId, inputId, component, inputForDelete, status);
- if (deleteEither.isRight()){
+ if (deleteEither.isRight()) {
throw new ByResponseFormatComponentException(deleteEither.right().value());
}
return deleteEither.left().value();
}
-
- StorageOperationStatus storageOperationStatus =
- propertyDeclarationOrchestrator.unDeclarePropertiesAsInputs(component, inputForDelete);
+ StorageOperationStatus storageOperationStatus = propertyDeclarationOrchestrator.unDeclarePropertiesAsInputs(component, inputForDelete);
if (storageOperationStatus != StorageOperationStatus.OK) {
log.debug("Component id: {} update properties declared as input for input id: {} failed", componentId, inputId);
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), component.getName());
}
- return inputForDelete;
- }catch (ComponentException e){
+ return inputForDelete;
+ } catch (ComponentException e) {
failed = true;
throw e;
- }finally {
+ } finally {
unlockComponent(failed, component);
}
}
private Either<InputDefinition, ResponseFormat> deleteListInput(String componentId, String inputId,
- org.openecomp.sdc.be.model.Component component,
- InputDefinition inputForDelete, StorageOperationStatus status) {
+ org.openecomp.sdc.be.model.Component component, InputDefinition inputForDelete,
+ StorageOperationStatus status) {
// the input is created by 'Declare List'.
- // need to 1. undeclare properties, 2. delete input, 3. delete private data type
- StorageOperationStatus storageOperationStatus =
- propertyDeclarationOrchestrator.unDeclarePropertiesAsListInputs(component, inputForDelete);
+ // need to 1. undeclare properties, 2. delete input, 3. delete private data type
+ StorageOperationStatus storageOperationStatus = propertyDeclarationOrchestrator.unDeclarePropertiesAsListInputs(component, inputForDelete);
if (storageOperationStatus != StorageOperationStatus.OK) {
log.debug("Component id: {} update properties declared as input for input id: {} failed", componentId, inputId);
- return Either.right(componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(status), component.getName()));
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
}
- Either<DataTypeDefinition, StorageOperationStatus> deleteResult =
- dataTypeBusinessLogic.deletePrivateDataType(component, inputForDelete.getSchemaType());
+ Either<DataTypeDefinition, StorageOperationStatus> deleteResult = dataTypeBusinessLogic
+ .deletePrivateDataType(component, inputForDelete.getSchemaType());
if (deleteResult.isRight()) {
log.debug("Component id: {} delete datatype name: {} failed", componentId, inputForDelete.getSchemaType());
- return Either.right(componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(deleteResult.right().value()), component.getName()));
+ return Either.right(
+ componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteResult.right().value()), component.getName()));
}
log.trace("deleteInput: deletePrivateDataType (OK)");
return Either.left(inputForDelete);
}
- private Either<InputDefinition, ResponseFormat> prepareAndValidateInputBeforeCreate(InputDefinition newInputDefinition, Map<String, DataTypeDefinition> dataTypes) {
-
+ private Either<InputDefinition, ResponseFormat> prepareAndValidateInputBeforeCreate(InputDefinition newInputDefinition,
+ Map<String, DataTypeDefinition> dataTypes) {
// validate input default values
Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newInputDefinition, dataTypes);
if (defaultValuesValidation.isRight()) {
@@ -818,10 +752,10 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
return Either.left(newInputDefinition);
}
- public Either<InputDefinition, ResponseFormat> getInputsAndPropertiesForComponentInput(String userId, String componentId, String inputId, boolean inTransaction) {
+ public Either<InputDefinition, ResponseFormat> getInputsAndPropertiesForComponentInput(String userId, String componentId, String inputId,
+ boolean inTransaction) {
Either<InputDefinition, ResponseFormat> result = null;
try {
-
validateUserExists(userId);
ComponentParametersView filters = new ComponentParametersView();
filters.disableAll();
@@ -830,41 +764,29 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
filters.setIgnoreComponentInstancesInputs(false);
filters.setIgnoreComponentInstancesProperties(false);
filters.setIgnoreProperties(false);
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
- if(getComponentEither.isRight()){
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade
+ .getToscaElement(componentId, filters);
+ if (getComponentEither.isRight()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, componentId, actionStatus);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
}
org.openecomp.sdc.be.model.Component component = getComponentEither.left().value();
Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
- if(!op.isPresent()){
+ if (!op.isPresent()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
log.debug(FAILED_TO_FOUND_INPUT_UNDER_COMPONENT_ERROR, inputId, componentId, actionStatus);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
}
-
InputDefinition resObj = op.get();
-
- List<ComponentInstanceInput> inputCIInput = componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, inputId) ;
-
+ List<ComponentInstanceInput> inputCIInput = componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, inputId);
resObj.setInputs(inputCIInput);
-
-
- List<ComponentInstanceProperty> inputProps = componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, inputId) ;
-
+ List<ComponentInstanceProperty> inputProps = componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, inputId);
resObj.setProperties(inputProps);
-
-
result = Either.left(resObj);
-
return result;
-
} finally {
-
if (!inTransaction) {
-
if (result == null || result.isRight()) {
log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP);
janusGraphDao.rollback();
@@ -872,69 +794,48 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
log.debug(GOING_TO_EXECUTE_COMMIT_ON_CREATE_GROUP);
janusGraphDao.commit();
}
-
}
-
}
-
}
- public Either<EntryData<String, InputDefinition>, ResponseFormat> addInputToComponent(String componentId,
- String inputName,
- InputDefinition newInputDefinition,
- String userId) {
+ public Either<EntryData<String, InputDefinition>, ResponseFormat> addInputToComponent(String componentId, String inputName,
+ InputDefinition newInputDefinition, String userId) {
Either<EntryData<String, InputDefinition>, ResponseFormat> result = null;
-
validateUserExists(userId);
-
- Either<Component, StorageOperationStatus> serviceElement =
- toscaOperationFacade.getToscaElement(componentId);
+ Either<Component, StorageOperationStatus> serviceElement = toscaOperationFacade.getToscaElement(componentId);
if (serviceElement.isRight()) {
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
return result;
}
-
Component component = serviceElement.left().value();
NodeTypeEnum nodeType = component.getComponentType().getNodeType();
-
StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, nodeType);
if (!lockResult.equals(StorageOperationStatus.OK)) {
- BeEcompErrorManager.getInstance()
- .logBeFailedLockObjectError(CREATE_INPUT, nodeType.name().toLowerCase(), componentId);
+ BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_INPUT, nodeType.name().toLowerCase(), componentId);
log.info("Failed to lock component {}. Error - {}", componentId, lockResult);
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
return result;
}
-
try {
if (!ComponentValidationUtils.canWorkOnComponent(component, userId)) {
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
return result;
}
-
List<InputDefinition> inputs = component.getInputs();
-
if (CollectionUtils.isEmpty(inputs)) {
inputs = new ArrayList<>();
}
-
if (isInputExistInComponent(inputs, inputName)) {
-
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus
- .INPUT_ALREADY_EXIST, inputName));
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INPUT_ALREADY_EXIST, inputName));
return result;
}
-
Map<String, DataTypeDefinition> allDataTypes = getAllDataTypes(applicationDataTypeCache);
-
// validate input default values
- Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(
- newInputDefinition, allDataTypes);
+ Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newInputDefinition, allDataTypes);
if (defaultValuesValidation.isRight()) {
result = Either.right(defaultValuesValidation.right().value());
return result;
}
-
// convert Input
ToscaPropertyType type = getType(newInputDefinition.getType());
if (type != null) {
@@ -949,24 +850,18 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
}
}
if (newInputDefinition.getDefaultValue() != null) {
- String convertedValue = converter
- .convert(newInputDefinition.getDefaultValue(), innerType, allDataTypes);
+ String convertedValue = converter.convert(newInputDefinition.getDefaultValue(), innerType, allDataTypes);
newInputDefinition.setDefaultValue(convertedValue);
}
}
-
newInputDefinition.setMappedToComponentProperty(false);
- Either<InputDefinition, StorageOperationStatus> addInputEither =
- toscaOperationFacade.addInputToComponent(inputName, newInputDefinition, component);
-
+ Either<InputDefinition, StorageOperationStatus> addInputEither = toscaOperationFacade
+ .addInputToComponent(inputName, newInputDefinition, component);
if (addInputEither.isRight()) {
- log.info("Failed to add new input {}. Error - {}", componentId,
- addInputEither.right().value());
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus
- .GENERAL_ERROR));
+ log.info("Failed to add new input {}. Error - {}", componentId, addInputEither.right().value());
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
return result;
}
-
result = Either.left(new EntryData<>(inputName, newInputDefinition));
return result;
} finally {
@@ -977,8 +872,6 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
}
private boolean isInputExistInComponent(List<InputDefinition> inputs, String inputName) {
- return CollectionUtils.isNotEmpty(inputs) &&
- inputs.stream().anyMatch(input -> input.getName().equals(inputName));
+ return CollectionUtils.isNotEmpty(inputs) && inputs.stream().anyMatch(input -> input.getName().equals(inputName));
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceDefinitionHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceDefinitionHandler.java
index 71005ef0f0..62e6ce5182 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceDefinitionHandler.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceDefinitionHandler.java
@@ -16,7 +16,6 @@
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import static org.openecomp.sdc.be.components.impl.ImportUtils.Constants.QUOTE;
@@ -64,7 +63,6 @@ import org.springframework.stereotype.Component;
public class InterfaceDefinitionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(InterfaceDefinitionHandler.class);
-
private final InterfaceOperationBusinessLogic interfaceOperationBusinessLogic;
public InterfaceDefinitionHandler(final InterfaceOperationBusinessLogic interfaceOperationBusinessLogic) {
@@ -78,9 +76,7 @@ public class InterfaceDefinitionHandler {
* @return an interface definition representation
*/
public InterfaceDefinition create(final Map<String, Object> interfaceDefinitionToscaMap) {
-
final InterfaceDefinition interfaceDefinition = new InterfaceDefinition();
-
if (interfaceDefinitionToscaMap.containsKey(TYPE.getElementName())) {
final Object typeObj = interfaceDefinitionToscaMap.get(TYPE.getElementName());
if (!(typeObj instanceof String)) {
@@ -90,11 +86,10 @@ public class InterfaceDefinitionHandler {
interfaceDefinition.setType(type);
interfaceDefinition.setUniqueId(type.toLowerCase());
}
-
final Map<String, InputDefinition> inputDefinitionMap = handleInputs(interfaceDefinitionToscaMap);
if (!inputDefinitionMap.isEmpty()) {
- final Map<String, InputDataDefinition> collect = inputDefinitionMap.entrySet().stream().
- collect(Collectors.toMap(Entry::getKey, value -> new InputDataDefinition(value.getValue())));
+ final Map<String, InputDataDefinition> collect = inputDefinitionMap.entrySet().stream()
+ .collect(Collectors.toMap(Entry::getKey, value -> new InputDataDefinition(value.getValue())));
interfaceDefinition.setInputs(collect);
}
final Map<String, OperationDataDefinition> operationMap;
@@ -109,88 +104,63 @@ public class InterfaceDefinitionHandler {
validateOperations(interfaceDefinition.getType(), operationMap);
interfaceDefinition.setOperations(operationMap);
}
-
return interfaceDefinition;
}
- private void validateOperations(final String interfaceType,
- final Map<String, OperationDataDefinition> operationMap) {
+ private void validateOperations(final String interfaceType, final Map<String, OperationDataDefinition> operationMap) {
if (MapUtils.isEmpty(operationMap)) {
return;
}
- Either<Map<String, InterfaceDefinition>, ResponseFormat> interfaceDefinitionMapEither =
- interfaceOperationBusinessLogic.getAllInterfaceLifecycleTypes();
+ Either<Map<String, InterfaceDefinition>, ResponseFormat> interfaceDefinitionMapEither = interfaceOperationBusinessLogic
+ .getAllInterfaceLifecycleTypes();
if (interfaceDefinitionMapEither.isRight() || MapUtils.isEmpty(interfaceDefinitionMapEither.left().value())) {
throw new ByActionStatusComponentException(ActionStatus.INTERFACE_UNKNOWN, interfaceType);
}
-
final Map<String, InterfaceDefinition> interfaceDefinitionMap = interfaceDefinitionMapEither.left().value();
final Optional<InterfaceDefinition> interfaceDefinitionOptional = interfaceDefinitionMap.entrySet().stream()
- .filter(interfaceDefinitionEntry -> interfaceDefinitionEntry.getKey().equalsIgnoreCase(interfaceType))
- .map(Entry::getValue).findFirst();
+ .filter(interfaceDefinitionEntry -> interfaceDefinitionEntry.getKey().equalsIgnoreCase(interfaceType)).map(Entry::getValue).findFirst();
if (interfaceDefinitionOptional.isEmpty()) {
throw new ByActionStatusComponentException(ActionStatus.INTERFACE_UNKNOWN, interfaceType);
}
final InterfaceDefinition interfaceDefinition = interfaceDefinitionOptional.get();
operationMap.keySet().forEach(operation1 -> {
if (!interfaceDefinition.hasOperation(operation1)) {
- throw new ByActionStatusComponentException(ActionStatus.INTERFACE_OPERATION_NOT_DEFINED,
- operation1, interfaceType);
+ throw new ByActionStatusComponentException(ActionStatus.INTERFACE_OPERATION_NOT_DEFINED, operation1, interfaceType);
}
});
}
- private Map<String, OperationDataDefinition> handleOperations(
- final Map<String, Object> interfaceDefinitionToscaMap) {
+ private Map<String, OperationDataDefinition> handleOperations(final Map<String, Object> interfaceDefinitionToscaMap) {
if (!interfaceDefinitionToscaMap.containsKey(OPERATIONS.getElementName())) {
return Collections.emptyMap();
}
- final Map<String, Object> operationMap =
- (Map<String, Object>) interfaceDefinitionToscaMap.get(OPERATIONS.getElementName());
+ final Map<String, Object> operationMap = (Map<String, Object>) interfaceDefinitionToscaMap.get(OPERATIONS.getElementName());
return operationMap.entrySet().stream()
- .map(interfaceEntry -> createOperation(interfaceEntry.getKey(),
- (Map<String, Object>) interfaceEntry.getValue()))
- .collect(
- Collectors.toMap(OperationDataDefinition::getName, operationDataDefinition -> operationDataDefinition));
+ .map(interfaceEntry -> createOperation(interfaceEntry.getKey(), (Map<String, Object>) interfaceEntry.getValue()))
+ .collect(Collectors.toMap(OperationDataDefinition::getName, operationDataDefinition -> operationDataDefinition));
}
- private Map<String, OperationDataDefinition> handleLegacyOperations(
- final Map<String, Object> interfaceDefinitionToscaMap) {
+ private Map<String, OperationDataDefinition> handleLegacyOperations(final Map<String, Object> interfaceDefinitionToscaMap) {
final List<String> notALegacyOperationEntry = Arrays
- .asList(OPERATIONS.getElementName(),
- TYPE.getElementName(),
- INPUTS.getElementName(),
- NOTIFICATIONS.getElementName());
- return interfaceDefinitionToscaMap.entrySet().stream()
- .filter(interfaceEntry -> !notALegacyOperationEntry.contains(interfaceEntry.getKey()))
- .map(interfaceEntry -> createOperation(interfaceEntry.getKey(),
- (Map<String, Object>) interfaceEntry.getValue()))
- .collect(
- Collectors.toMap(OperationDataDefinition::getName, operationDataDefinition -> operationDataDefinition));
+ .asList(OPERATIONS.getElementName(), TYPE.getElementName(), INPUTS.getElementName(), NOTIFICATIONS.getElementName());
+ return interfaceDefinitionToscaMap.entrySet().stream().filter(interfaceEntry -> !notALegacyOperationEntry.contains(interfaceEntry.getKey()))
+ .map(interfaceEntry -> createOperation(interfaceEntry.getKey(), (Map<String, Object>) interfaceEntry.getValue()))
+ .collect(Collectors.toMap(OperationDataDefinition::getName, operationDataDefinition -> operationDataDefinition));
}
-
- private OperationDataDefinition createOperation(final String operationName,
- final Map<String, Object> operationDefinitionMap) {
+ private OperationDataDefinition createOperation(final String operationName, final Map<String, Object> operationDefinitionMap) {
final OperationDataDefinition operation = new OperationDataDefinition();
operation.setUniqueId(UUID.randomUUID().toString());
operation.setName(operationName);
-
- operation.setImplementation(
- handleOperationImplementation(operationDefinitionMap)
- .orElse(new ArtifactDataDefinition())
- );
+ operation.setImplementation(handleOperationImplementation(operationDefinitionMap).orElse(new ArtifactDataDefinition()));
if (operationDefinitionMap.containsKey(INPUTS.getElementName())) {
- final Map<String, Object> interfaceInputs =
- (Map<String, Object>) operationDefinitionMap.get(INPUTS.getElementName());
+ final Map<String, Object> interfaceInputs = (Map<String, Object>) operationDefinitionMap.get(INPUTS.getElementName());
operation.setInputs(handleInterfaceOperationInputs(interfaceInputs));
}
-
return operation;
}
- private ListDataDefinition<OperationInputDefinition> handleInterfaceOperationInputs(
- final Map<String, Object> interfaceInputs) {
+ private ListDataDefinition<OperationInputDefinition> handleInterfaceOperationInputs(final Map<String, Object> interfaceInputs) {
final ListDataDefinition<OperationInputDefinition> inputs = new ListDataDefinition<>();
for (final Entry<String, Object> interfaceInput : interfaceInputs.entrySet()) {
final OperationInputDefinition operationInput = new OperationInputDefinition();
@@ -198,10 +168,9 @@ public class InterfaceDefinitionHandler {
operationInput.setInputId(operationInput.getUniqueId());
operationInput.setName(interfaceInput.getKey());
if (interfaceInput.getValue() instanceof Map) {
- final LinkedHashMap<String, Object> inputPropertyValue =
- (LinkedHashMap<String, Object>) interfaceInput.getValue();
- LOGGER.info("createModuleInterface: i interfaceInput.getKey() {}, {} , {} ",
- interfaceInput.getKey(), inputPropertyValue.keySet(), inputPropertyValue.values());
+ final LinkedHashMap<String, Object> inputPropertyValue = (LinkedHashMap<String, Object>) interfaceInput.getValue();
+ LOGGER.info("createModuleInterface: i interfaceInput.getKey() {}, {} , {} ", interfaceInput.getKey(), inputPropertyValue.keySet(),
+ inputPropertyValue.values());
if (inputPropertyValue.get(TYPE.getElementName()) != null) {
operationInput.setType(inputPropertyValue.get(TYPE.getElementName()).toString());
}
@@ -209,8 +178,7 @@ public class InterfaceDefinitionHandler {
operationInput.setDescription(inputPropertyValue.get(DESCRIPTION.getElementName()).toString());
}
if (inputPropertyValue.get(REQUIRED.getElementName()) != null) {
- operationInput.setRequired(
- Boolean.getBoolean(inputPropertyValue.get(REQUIRED.getElementName()).toString()));
+ operationInput.setRequired(Boolean.getBoolean(inputPropertyValue.get(REQUIRED.getElementName()).toString()));
}
if (inputPropertyValue.get(DEFAULT.getElementName()) != null) {
operationInput.setToscaDefaultValue(inputPropertyValue.get(DEFAULT.getElementName()).toString());
@@ -218,7 +186,6 @@ public class InterfaceDefinitionHandler {
if (inputPropertyValue.get(STATUS.getElementName()) != null) {
operationInput.setStatus(inputPropertyValue.get(STATUS.getElementName()).toString());
}
-
} else if (interfaceInput.getValue() instanceof String) {
final String value = (String) interfaceInput.getValue();
operationInput.setDefaultValue(value);
@@ -230,8 +197,7 @@ public class InterfaceDefinitionHandler {
return inputs;
}
- private Optional<ArtifactDataDefinition> handleOperationImplementation(
- final Map<String, Object> operationDefinitionMap) {
+ private Optional<ArtifactDataDefinition> handleOperationImplementation(final Map<String, Object> operationDefinitionMap) {
if (!operationDefinitionMap.containsKey(IMPLEMENTATION.getElementName())) {
return Optional.empty();
}
@@ -249,14 +215,10 @@ public class InterfaceDefinitionHandler {
if (!interfaceDefinitionToscaMap.containsKey(INPUTS.getElementName())) {
return Collections.emptyMap();
}
-
- final Either<Map<String, InputDefinition>, ResultStatusEnum> inputMapEither =
- ImportUtils.getInputs(interfaceDefinitionToscaMap);
+ final Either<Map<String, InputDefinition>, ResultStatusEnum> inputMapEither = ImportUtils.getInputs(interfaceDefinitionToscaMap);
if (inputMapEither.isRight()) {
return Collections.emptyMap();
}
-
return inputMapEither.left().value();
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java
index f1b4442e18..1c5411434f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
@@ -46,18 +45,15 @@ import org.springframework.stereotype.Component;
@Component("interfaceLifecycleTypeImportManager")
public class InterfaceLifecycleTypeImportManager {
+ private static final Logger log = Logger.getLogger(InterfaceLifecycleTypeImportManager.class);
@Resource
private IInterfaceLifecycleOperation interfaceLifecycleOperation;
-
@Resource
private ComponentsUtils componentsUtils;
@Resource
private CommonImportManager commonImportManager;
- private static final Logger log = Logger.getLogger(InterfaceLifecycleTypeImportManager.class);
-
public Either<List<InterfaceDefinition>, ResponseFormat> createLifecycleTypes(String interfaceLifecycleTypesYml) {
-
Either<List<InterfaceDefinition>, ActionStatus> interfaces = createInterfaceTypeFromYml(interfaceLifecycleTypesYml);
if (interfaces.isRight()) {
ActionStatus status = interfaces.right().value();
@@ -65,12 +61,10 @@ public class InterfaceLifecycleTypeImportManager {
return Either.right(responseFormat);
}
return createInterfacesByDao(interfaces.left().value());
-
}
private Either<List<InterfaceDefinition>, ActionStatus> createInterfaceTypeFromYml(final String interfaceTypesYml) {
return commonImportManager.createElementTypesFromYml(interfaceTypesYml, this::createInterfaceDefinition);
-
}
private Either<List<InterfaceDefinition>, ResponseFormat> createInterfacesByDao(List<InterfaceDefinition> interfacesToCreate) {
@@ -80,18 +74,17 @@ public class InterfaceLifecycleTypeImportManager {
boolean stopDao = false;
while (interfaceItr.hasNext() && !stopDao) {
InterfaceDefinition interfaceDef = interfaceItr.next();
-
log.info("send interfaceDefinition {} to dao for create", interfaceDef.getType());
-
Either<InterfaceDefinition, StorageOperationStatus> dataModelResponse = interfaceLifecycleOperation.createInterfaceType(interfaceDef);
if (dataModelResponse.isRight()) {
log.info("failed to create interface : {} error: {}", interfaceDef.getType(), dataModelResponse.right().value().name());
if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForLifecycleType(dataModelResponse.right().value()), interfaceDef.getType());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponseForLifecycleType(dataModelResponse.right().value()),
+ interfaceDef.getType());
eitherResult = Either.right(responseFormat);
stopDao = true;
}
-
} else {
createdInterfaces.add(dataModelResponse.left().value());
}
@@ -102,8 +95,7 @@ public class InterfaceLifecycleTypeImportManager {
return eitherResult;
}
- private InterfaceDefinition createInterfaceDefinition(final String interfaceDefinition,
- final Map<String, Object> toscaJson) {
+ private InterfaceDefinition createInterfaceDefinition(final String interfaceDefinition, final Map<String, Object> toscaJson) {
final InterfaceDefinition interfaceDef = new InterfaceDefinition();
interfaceDef.setType(interfaceDefinition);
final Object descriptionObj = toscaJson.get(ToscaTagNamesEnum.DESCRIPTION.getElementName());
@@ -118,25 +110,19 @@ public class InterfaceLifecycleTypeImportManager {
if (versionObj instanceof String) {
interfaceDef.setVersion((String) versionObj);
}
-
final Object metadataObj = toscaJson.get(ToscaTagNamesEnum.METADATA.getElementName());
if (metadataObj instanceof Map) {
interfaceDef.setToscaPresentationValue(JsonPresentationFields.METADATA, metadataObj);
}
-
final Map<String, Object> operationsMap;
if (toscaJson.containsKey(ToscaTagNamesEnum.OPERATIONS.getElementName())) {
operationsMap = (Map<String, Object>) toscaJson.get(ToscaTagNamesEnum.OPERATIONS.getElementName());
} else {
final List<String> entitySchemaEntryList = Arrays
- .asList(ToscaTagNamesEnum.DERIVED_FROM.getElementName(),
- ToscaTagNamesEnum.DESCRIPTION.getElementName(),
- ToscaTagNamesEnum.VERSION.getElementName(),
- ToscaTagNamesEnum.METADATA.getElementName(),
- ToscaTagNamesEnum.INPUTS.getElementName(),
- ToscaTagNamesEnum.NOTIFICATIONS.getElementName());
- operationsMap = toscaJson.entrySet().stream()
- .filter(interfaceEntry -> !entitySchemaEntryList.contains(interfaceEntry.getKey()))
+ .asList(ToscaTagNamesEnum.DERIVED_FROM.getElementName(), ToscaTagNamesEnum.DESCRIPTION.getElementName(),
+ ToscaTagNamesEnum.VERSION.getElementName(), ToscaTagNamesEnum.METADATA.getElementName(),
+ ToscaTagNamesEnum.INPUTS.getElementName(), ToscaTagNamesEnum.NOTIFICATIONS.getElementName());
+ operationsMap = toscaJson.entrySet().stream().filter(interfaceEntry -> !entitySchemaEntryList.contains(interfaceEntry.getKey()))
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
}
interfaceDef.setOperationsMap(handleOperations(operationsMap));
@@ -148,8 +134,7 @@ public class InterfaceLifecycleTypeImportManager {
return Collections.emptyMap();
}
return operationsToscaEntry.entrySet().stream()
- .collect(Collectors.toMap(Entry::getKey,
- operationEntry -> createOperation((Map<String, Object>) operationEntry.getValue())));
+ .collect(Collectors.toMap(Entry::getKey, operationEntry -> createOperation((Map<String, Object>) operationEntry.getValue())));
}
private Operation createOperation(final Map<String, Object> toscaOperationMap) {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java
index 3aabe82db5..e23818c957 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java
@@ -13,12 +13,31 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-
package org.openecomp.sdc.be.components.impl;
+import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedCapabilityPropertyDefaultValue;
+import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedInputPropertyDefaultValue;
+import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedOutputDefaultValue;
+import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceId;
+import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceType;
+import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getOperationFromInterfaceDefinition;
+import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.isOperationInputMappedToComponentInput;
+import static org.openecomp.sdc.be.components.utils.PropertiesUtils.getPropertyCapabilityFromAllCapProps;
+import static org.openecomp.sdc.be.components.utils.PropertiesUtils.isCapabilityProperty;
+import static org.openecomp.sdc.be.tosca.InterfacesOperationsConverter.SELF;
+
import com.google.gson.Gson;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
@@ -57,147 +76,101 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.UUID;
-import java.util.stream.Collectors;
-
-import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedCapabilityPropertyDefaultValue;
-import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedInputPropertyDefaultValue;
-import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedOutputDefaultValue;
-import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceId;
-import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceType;
-import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getOperationFromInterfaceDefinition;
-import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.isOperationInputMappedToComponentInput;
-import static org.openecomp.sdc.be.components.utils.PropertiesUtils.getPropertyCapabilityFromAllCapProps;
-import static org.openecomp.sdc.be.components.utils.PropertiesUtils.isCapabilityProperty;
-import static org.openecomp.sdc.be.tosca.InterfacesOperationsConverter.SELF;
-
@Component("interfaceOperationBusinessLogic")
public class InterfaceOperationBusinessLogic extends BaseBusinessLogic {
private static final Logger LOGGER = LoggerFactory.getLogger(InterfaceOperationBusinessLogic.class);
- private static final String EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION =
- "Exception occurred during {}. Response is {}";
+ private static final String EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION = "Exception occurred during {}. Response is {}";
private static final String DELETE_INTERFACE_OPERATION = "deleteInterfaceOperation";
private static final String GET_INTERFACE_OPERATION = "getInterfaceOperation";
private static final String CREATE_INTERFACE_OPERATION = "createInterfaceOperation";
private static final String UPDATE_INTERFACE_OPERATION = "updateInterfaceOperation";
-
private final ArtifactCassandraDao artifactCassandraDao;
private final InterfaceOperationValidation interfaceOperationValidation;
@Autowired
- public InterfaceOperationBusinessLogic(IElementOperation elementDao,
- IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation,
- IGroupTypeOperation groupTypeOperation,
- InterfaceOperation interfaceOperation,
- InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactCassandraDao artifactCassandraDao,
- InterfaceOperationValidation interfaceOperationValidation, ArtifactsOperations artifactToscaOperation) {
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
- interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+ public InterfaceOperationBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
+ IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation,
+ InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+ ArtifactCassandraDao artifactCassandraDao, InterfaceOperationValidation interfaceOperationValidation,
+ ArtifactsOperations artifactToscaOperation) {
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+ artifactToscaOperation);
this.artifactCassandraDao = artifactCassandraDao;
this.interfaceOperationValidation = interfaceOperationValidation;
}
- public Either<List<InterfaceDefinition>, ResponseFormat> deleteInterfaceOperation(String componentId,
- String interfaceId, List<String> operationsToDelete, User user, boolean lock) {
+ public Either<List<InterfaceDefinition>, ResponseFormat> deleteInterfaceOperation(String componentId, String interfaceId,
+ List<String> operationsToDelete, User user, boolean lock) {
validateUserExists(user.getUserId());
-
Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId);
if (componentEither.isRight()) {
return Either.right(componentEither.right().value());
}
org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value();
-
lockComponentResult(lock, storedComponent, DELETE_INTERFACE_OPERATION);
-
-
try {
- Optional<InterfaceDefinition> optionalInterface = getInterfaceDefinitionFromComponentByInterfaceId(
- storedComponent, interfaceId);
+ Optional<InterfaceDefinition> optionalInterface = getInterfaceDefinitionFromComponentByInterfaceId(storedComponent, interfaceId);
if (!optionalInterface.isPresent()) {
- return Either.right(
- componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceId));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceId));
}
InterfaceDefinition interfaceDefinition = optionalInterface.get();
-
Map<String, Operation> operationsCollection = new HashMap<>();
for (String operationId : operationsToDelete) {
- Optional<Map.Entry<String, Operation>> optionalOperation =
- getOperationFromInterfaceDefinition(interfaceDefinition, operationId);
+ Optional<Map.Entry<String, Operation>> optionalOperation = getOperationFromInterfaceDefinition(interfaceDefinition, operationId);
if (!optionalOperation.isPresent()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND,
- storedComponent.getUniqueId()));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, storedComponent.getUniqueId()));
}
-
Operation storedOperation = optionalOperation.get().getValue();
- Either<Boolean, ResponseFormat> validateDeleteOperationContainsNoMappedOutputResponse =
- interfaceOperationValidation.validateDeleteOperationContainsNoMappedOutput(storedOperation,
- storedComponent, interfaceDefinition);
+ Either<Boolean, ResponseFormat> validateDeleteOperationContainsNoMappedOutputResponse = interfaceOperationValidation
+ .validateDeleteOperationContainsNoMappedOutput(storedOperation, storedComponent, interfaceDefinition);
if (validateDeleteOperationContainsNoMappedOutputResponse.isRight()) {
return Either.right(validateDeleteOperationContainsNoMappedOutputResponse.right().value());
}
-
String artifactUniqueId = storedOperation.getImplementation().getUniqueId();
- if(!InterfaceOperationUtils.isArtifactInUse(storedComponent, operationId, artifactUniqueId)){
- Either<ArtifactDefinition, StorageOperationStatus> getArtifactEither =
- artifactToscaOperation.getArtifactById(storedComponent.getUniqueId(), artifactUniqueId);
- if(getArtifactEither.isLeft()){
- Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromComponent =
- artifactToscaOperation.removeArifactFromResource(componentId, artifactUniqueId,
- NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()),
- true);
- if(removeArifactFromComponent.isRight()){
+ if (!InterfaceOperationUtils.isArtifactInUse(storedComponent, operationId, artifactUniqueId)) {
+ Either<ArtifactDefinition, StorageOperationStatus> getArtifactEither = artifactToscaOperation
+ .getArtifactById(storedComponent.getUniqueId(), artifactUniqueId);
+ if (getArtifactEither.isLeft()) {
+ Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromComponent = artifactToscaOperation
+ .removeArifactFromResource(componentId, artifactUniqueId,
+ NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()), true);
+ if (removeArifactFromComponent.isRight()) {
janusGraphDao.rollback();
- ResponseFormat responseFormatByArtifactId = componentsUtils.getResponseFormatByArtifactId(
- componentsUtils.convertFromStorageResponse(removeArifactFromComponent.right().value()),
+ ResponseFormat responseFormatByArtifactId = componentsUtils
+ .getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(removeArifactFromComponent.right().value()),
storedOperation.getImplementation().getArtifactDisplayName());
return Either.right(responseFormatByArtifactId);
}
-
CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(artifactUniqueId);
if (cassandraStatus != CassandraOperationStatus.OK) {
janusGraphDao.rollback();
ResponseFormat responseFormatByArtifactId = componentsUtils.getResponseFormatByArtifactId(
- componentsUtils.convertFromStorageResponse(
- componentsUtils.convertToStorageOperationStatus(cassandraStatus)),
- storedOperation.getImplementation().getArtifactDisplayName());
+ componentsUtils.convertFromStorageResponse(componentsUtils.convertToStorageOperationStatus(cassandraStatus)),
+ storedOperation.getImplementation().getArtifactDisplayName());
return Either.right(responseFormatByArtifactId);
}
}
}
-
operationsCollection.put(operationId, interfaceDefinition.getOperationsMap().get(operationId));
interfaceDefinition.getOperations().remove(operationId);
}
-
- Either<List<InterfaceDefinition>, StorageOperationStatus> deleteOperationEither =
- interfaceOperation.updateInterfaces(storedComponent.getUniqueId(),
- Collections.singletonList(interfaceDefinition));
+ Either<List<InterfaceDefinition>, StorageOperationStatus> deleteOperationEither = interfaceOperation
+ .updateInterfaces(storedComponent.getUniqueId(), Collections.singletonList(interfaceDefinition));
if (deleteOperationEither.isRight()) {
janusGraphDao.rollback();
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
- deleteOperationEither.right().value(), storedComponent.getComponentType())));
+ return Either.right(componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(deleteOperationEither.right().value(), storedComponent.getComponentType())));
}
-
if (interfaceDefinition.getOperations().isEmpty()) {
- Either<String, StorageOperationStatus> deleteInterfaceEither = interfaceOperation.deleteInterface(
- storedComponent.getUniqueId(), interfaceDefinition.getUniqueId());
+ Either<String, StorageOperationStatus> deleteInterfaceEither = interfaceOperation
+ .deleteInterface(storedComponent.getUniqueId(), interfaceDefinition.getUniqueId());
if (deleteInterfaceEither.isRight()) {
janusGraphDao.rollback();
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
- deleteInterfaceEither.right().value(), storedComponent.getComponentType())));
+ return Either.right(componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(deleteInterfaceEither.right().value(), storedComponent.getComponentType())));
}
}
-
janusGraphDao.commit();
interfaceDefinition.getOperations().putAll(operationsCollection);
interfaceDefinition.getOperations().keySet().removeIf(key -> !(operationsToDelete.contains(key)));
@@ -207,177 +180,144 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic {
janusGraphDao.rollback();
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_DELETED));
} finally {
- graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
- NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+ graphLockOperation
+ .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
}
}
private Either<org.openecomp.sdc.be.model.Component, ResponseFormat> getComponentDetails(String componentId) {
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentStorageOperationStatusEither =
- toscaOperationFacade.getToscaElement(componentId);
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade
+ .getToscaElement(componentId);
if (componentStorageOperationStatusEither.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(componentStorageOperationStatusEither.right().value())));
+ return Either.right(
+ componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentStorageOperationStatusEither.right().value())));
}
return Either.left(componentStorageOperationStatusEither.left().value());
}
- private Either<Boolean, ResponseFormat> lockComponentResult(boolean lock,
- org.openecomp.sdc.be.model.Component component, String action) {
+ private Either<Boolean, ResponseFormat> lockComponentResult(boolean lock, org.openecomp.sdc.be.model.Component component, String action) {
if (lock) {
try {
lockComponent(component.getUniqueId(), component, action);
} catch (ComponentException e) {
- janusGraphDao.rollback();
- throw e;
+ janusGraphDao.rollback();
+ throw e;
+ }
}
- }
return Either.left(true);
}
- public Either<List<InterfaceDefinition>, ResponseFormat> getInterfaceOperation(String componentId,
- String interfaceId, List<String> operationsToGet, User user, boolean lock) {
+ public Either<List<InterfaceDefinition>, ResponseFormat> getInterfaceOperation(String componentId, String interfaceId,
+ List<String> operationsToGet, User user, boolean lock) {
validateUserExists(user);
-
Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId);
if (componentEither.isRight()) {
return Either.right(componentEither.right().value());
}
org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value();
-
lockComponentResult(lock, storedComponent, GET_INTERFACE_OPERATION);
-
try {
- Optional<InterfaceDefinition> optionalInterface = getInterfaceDefinitionFromComponentByInterfaceId(
- storedComponent, interfaceId);
+ Optional<InterfaceDefinition> optionalInterface = getInterfaceDefinitionFromComponentByInterfaceId(storedComponent, interfaceId);
if (!optionalInterface.isPresent()) {
- return Either.right(
- componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceId));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceId));
}
InterfaceDefinition interfaceDefinition = optionalInterface.get();
-
for (String operationId : operationsToGet) {
- Optional<Map.Entry<String, Operation>> optionalOperation =
- getOperationFromInterfaceDefinition(interfaceDefinition, operationId);
+ Optional<Map.Entry<String, Operation>> optionalOperation = getOperationFromInterfaceDefinition(interfaceDefinition, operationId);
if (!optionalOperation.isPresent()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND,
- storedComponent.getUniqueId()));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, storedComponent.getUniqueId()));
}
}
-
janusGraphDao.commit();
interfaceDefinition.getOperations().keySet().removeIf(key -> !(operationsToGet.contains(key)));
return Either.left(Collections.singletonList(interfaceDefinition));
} catch (Exception e) {
LOGGER.error(EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION, "get", e);
janusGraphDao.rollback();
- return Either.right(
- componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentId));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentId));
} finally {
- graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
- NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+ graphLockOperation
+ .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
}
}
public Either<List<InterfaceDefinition>, ResponseFormat> createInterfaceOperation(String componentId,
- List<InterfaceDefinition> interfaceDefinitions, User user, boolean lock) {
- return createOrUpdateInterfaceOperation(componentId, interfaceDefinitions, user, false,
- CREATE_INTERFACE_OPERATION, lock);
+ List<InterfaceDefinition> interfaceDefinitions, User user,
+ boolean lock) {
+ return createOrUpdateInterfaceOperation(componentId, interfaceDefinitions, user, false, CREATE_INTERFACE_OPERATION, lock);
}
private Either<List<InterfaceDefinition>, ResponseFormat> createOrUpdateInterfaceOperation(String componentId,
- List<InterfaceDefinition> interfaceDefinitions, User user, boolean isUpdate, String errorContext,
- boolean lock) {
+ List<InterfaceDefinition> interfaceDefinitions,
+ User user, boolean isUpdate, String errorContext,
+ boolean lock) {
validateUserExists(user);
-
Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId);
if (componentEither.isRight()) {
return Either.right(componentEither.right().value());
}
org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value();
-
lockComponentResult(lock, storedComponent, errorContext);
-
-
- Either<Map<String, InterfaceDefinition>, ResponseFormat> interfaceLifecycleTypes =
- getAllInterfaceLifecycleTypes();
+ Either<Map<String, InterfaceDefinition>, ResponseFormat> interfaceLifecycleTypes = getAllInterfaceLifecycleTypes();
if (interfaceLifecycleTypes.isRight()) {
return Either.right(interfaceLifecycleTypes.right().value());
}
-
try {
List<InterfaceDefinition> interfacesCollection = new ArrayList<>();
Map<String, Operation> operationsCollection = new HashMap<>();
for (InterfaceDefinition inputInterfaceDefinition : interfaceDefinitions) {
- Optional<InterfaceDefinition> optionalInterface =
- getInterfaceDefinitionFromComponentByInterfaceType(
- storedComponent, inputInterfaceDefinition.getType());
- Either<Boolean, ResponseFormat> interfaceOperationValidationResponseEither =
- interfaceOperationValidation
- .validateInterfaceOperations(inputInterfaceDefinition, storedComponent,
- optionalInterface.orElse(null), interfaceLifecycleTypes.left().value(),
- isUpdate);
+ Optional<InterfaceDefinition> optionalInterface = getInterfaceDefinitionFromComponentByInterfaceType(storedComponent,
+ inputInterfaceDefinition.getType());
+ Either<Boolean, ResponseFormat> interfaceOperationValidationResponseEither = interfaceOperationValidation
+ .validateInterfaceOperations(inputInterfaceDefinition, storedComponent, optionalInterface.orElse(null),
+ interfaceLifecycleTypes.left().value(), isUpdate);
if (interfaceOperationValidationResponseEither.isRight()) {
return Either.right(interfaceOperationValidationResponseEither.right().value());
}
-
Map<String, Operation> operationsToAddOrUpdate = inputInterfaceDefinition.getOperationsMap();
operationsCollection.putAll(operationsToAddOrUpdate);
inputInterfaceDefinition.getOperations().clear();
-
- Either<InterfaceDefinition, ResponseFormat> getInterfaceEither =
- getOrCreateInterfaceDefinition(storedComponent, inputInterfaceDefinition,
- optionalInterface.orElse(null));
+ Either<InterfaceDefinition, ResponseFormat> getInterfaceEither = getOrCreateInterfaceDefinition(storedComponent,
+ inputInterfaceDefinition, optionalInterface.orElse(null));
if (getInterfaceEither.isRight()) {
return Either.right(getInterfaceEither.right().value());
}
InterfaceDefinition interfaceDef = getInterfaceEither.left().value();
-
updateOperationInputDefs(storedComponent, operationsToAddOrUpdate.values());
-
for (Operation operation : operationsToAddOrUpdate.values()) {
if (!isUpdate) {
addOperationToInterface(interfaceDef, operation);
} else {
- Optional<Map.Entry<String, Operation>> optionalOperation =
- getOperationFromInterfaceDefinition(interfaceDef,
- operation.getUniqueId());
+ Optional<Map.Entry<String, Operation>> optionalOperation = getOperationFromInterfaceDefinition(interfaceDef,
+ operation.getUniqueId());
if (!optionalOperation.isPresent()) {
janusGraphDao.rollback();
- return Either.right(componentsUtils
- .getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND,
- storedComponent.getUniqueId()));
+ return Either
+ .right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, storedComponent.getUniqueId()));
}
-
Operation storedOperation = optionalOperation.get().getValue();
String artifactUuId = storedOperation.getImplementation().getArtifactUUID();
String artifactUniqueId = storedOperation.getImplementation().getUniqueId();
-
- if(!InterfaceOperationUtils.isArtifactInUse(storedComponent, storedOperation.getUniqueId(), artifactUniqueId)){
- Either<ArtifactDefinition, StorageOperationStatus> getArtifactEither =
- artifactToscaOperation.getArtifactById(storedComponent.getUniqueId(), artifactUniqueId);
- if(getArtifactEither.isLeft()){
- Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromComponent =
- artifactToscaOperation.removeArifactFromResource(componentId, artifactUniqueId,
- NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()),
- true);
- if(removeArifactFromComponent.isRight()){
+ if (!InterfaceOperationUtils.isArtifactInUse(storedComponent, storedOperation.getUniqueId(), artifactUniqueId)) {
+ Either<ArtifactDefinition, StorageOperationStatus> getArtifactEither = artifactToscaOperation
+ .getArtifactById(storedComponent.getUniqueId(), artifactUniqueId);
+ if (getArtifactEither.isLeft()) {
+ Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromComponent = artifactToscaOperation
+ .removeArifactFromResource(componentId, artifactUniqueId,
+ NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()), true);
+ if (removeArifactFromComponent.isRight()) {
janusGraphDao.rollback();
ResponseFormat responseFormatByArtifactId = componentsUtils.getResponseFormatByArtifactId(
- componentsUtils.convertFromStorageResponse(removeArifactFromComponent.right().value()),
- storedOperation.getImplementation().getArtifactDisplayName());
+ componentsUtils.convertFromStorageResponse(removeArifactFromComponent.right().value()),
+ storedOperation.getImplementation().getArtifactDisplayName());
return Either.right(responseFormatByArtifactId);
}
-
CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(artifactUniqueId);
if (cassandraStatus != CassandraOperationStatus.OK) {
janusGraphDao.rollback();
- ResponseFormat responseFormatByArtifactId =
- componentsUtils.getResponseFormatByArtifactId(
- componentsUtils.convertFromStorageResponse(
- componentsUtils.convertToStorageOperationStatus(
- cassandraStatus)),
- storedOperation.getImplementation().getArtifactDisplayName());
+ ResponseFormat responseFormatByArtifactId = componentsUtils.getResponseFormatByArtifactId(
+ componentsUtils.convertFromStorageResponse(componentsUtils.convertToStorageOperationStatus(cassandraStatus)),
+ storedOperation.getImplementation().getArtifactDisplayName());
return Either.right(responseFormatByArtifactId);
}
}
@@ -387,73 +327,64 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic {
}
interfacesCollection.add(interfaceDef);
}
-
- Either<List<InterfaceDefinition>, StorageOperationStatus> addCreateOperationEither =
- interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), interfacesCollection);
+ Either<List<InterfaceDefinition>, StorageOperationStatus> addCreateOperationEither = interfaceOperation
+ .updateInterfaces(storedComponent.getUniqueId(), interfacesCollection);
if (addCreateOperationEither.isRight()) {
janusGraphDao.rollback();
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
- addCreateOperationEither.right().value(), storedComponent.getComponentType())));
+ return Either.right(componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(addCreateOperationEither.right().value(), storedComponent.getComponentType())));
}
-
janusGraphDao.commit();
interfacesCollection.forEach(interfaceDefinition -> interfaceDefinition.getOperations().entrySet().removeIf(
- entry -> !operationsCollection.values().stream().map(OperationDataDefinition::getName)
- .collect(Collectors.toList()).contains(entry.getValue().getName())));
+ entry -> !operationsCollection.values().stream().map(OperationDataDefinition::getName).collect(Collectors.toList())
+ .contains(entry.getValue().getName())));
return Either.left(interfacesCollection);
} catch (Exception e) {
janusGraphDao.rollback();
LOGGER.error(EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION, "addOrUpdate", e);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
} finally {
- graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
- NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+ graphLockOperation
+ .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
}
}
public Either<Map<String, InterfaceDefinition>, ResponseFormat> getAllInterfaceLifecycleTypes() {
-
- Either<Map<String, InterfaceDefinition>, StorageOperationStatus> interfaceLifecycleTypes =
- interfaceLifecycleTypeOperation.getAllInterfaceLifecycleTypes();
+ Either<Map<String, InterfaceDefinition>, StorageOperationStatus> interfaceLifecycleTypes = interfaceLifecycleTypeOperation
+ .getAllInterfaceLifecycleTypes();
if (interfaceLifecycleTypes.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_LIFECYCLE_TYPES_NOT_FOUND));
}
- interfaceLifecycleTypes.left().value().values().forEach(id -> id.setOperations(
- id.getOperations().keySet().stream().collect(Collectors.toMap(key -> key.replaceFirst(
- id.getUniqueId() + ".", ""), i -> id.getOperations().get(i)))));
-
+ interfaceLifecycleTypes.left().value().values().forEach(id -> id.setOperations(id.getOperations().keySet().stream()
+ .collect(Collectors.toMap(key -> key.replaceFirst(id.getUniqueId() + ".", ""), i -> id.getOperations().get(i)))));
return Either.left(interfaceLifecycleTypes.left().value());
}
- private Either<InterfaceDefinition, ResponseFormat> getOrCreateInterfaceDefinition(
- org.openecomp.sdc.be.model.Component component, InterfaceDefinition interfaceDefinition,
- InterfaceDefinition storedInterfaceDef) {
+ private Either<InterfaceDefinition, ResponseFormat> getOrCreateInterfaceDefinition(org.openecomp.sdc.be.model.Component component,
+ InterfaceDefinition interfaceDefinition,
+ InterfaceDefinition storedInterfaceDef) {
if (storedInterfaceDef != null) {
return Either.left(storedInterfaceDef);
}
interfaceDefinition.setUniqueId(UUID.randomUUID().toString());
interfaceDefinition.setToscaResourceName(interfaceDefinition.getType());
- Either<List<InterfaceDefinition>, StorageOperationStatus> interfaceCreateEither =
- interfaceOperation.addInterfaces(component.getUniqueId(),
- Collections.singletonList(interfaceDefinition));
+ Either<List<InterfaceDefinition>, StorageOperationStatus> interfaceCreateEither = interfaceOperation
+ .addInterfaces(component.getUniqueId(), Collections.singletonList(interfaceDefinition));
if (interfaceCreateEither.isRight()) {
janusGraphDao.rollback();
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
- interfaceCreateEither.right().value(), component.getComponentType())));
+ return Either.right(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(interfaceCreateEither.right().value(), component.getComponentType())));
}
return Either.left(interfaceCreateEither.left().value().get(0));
}
- private void updateOperationInputDefs(org.openecomp.sdc.be.model.Component component,
- Collection<Operation> interfaceOperations) {
+ private void updateOperationInputDefs(org.openecomp.sdc.be.model.Component component, Collection<Operation> interfaceOperations) {
interfaceOperations.stream().filter(operation -> Objects.nonNull(operation.getInputs())).forEach(
- operation -> operation.getInputs().getListToscaDataDefinition().forEach(
- inp -> component.getInputs()
- .forEach(in -> updateOperationInputDefinition(component, inp, in))));
+ operation -> operation.getInputs().getListToscaDataDefinition()
+ .forEach(inp -> component.getInputs().forEach(in -> updateOperationInputDefinition(component, inp, in))));
}
- private void updateOperationInputDefinition(org.openecomp.sdc.be.model.Component component,
- OperationInputDefinition operationInput,
+ private void updateOperationInputDefinition(org.openecomp.sdc.be.model.Component component, OperationInputDefinition operationInput,
InputDefinition componentInput) {
if (operationInput.getInputId().equals(componentInput.getUniqueId())) {
//Set the default value, value and schema only for inputs mapped to component inputs
@@ -461,41 +392,32 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic {
operationInput.setToscaDefaultValue(getInputToscaDefaultValue(operationInput, component));
operationInput.setValue(componentInput.getValue());
operationInput.setSchema(componentInput.getSchema());
- operationInput.setParentPropertyType(componentInput.getParentPropertyType());
- operationInput.setSubPropertyInputPath(componentInput.getSubPropertyInputPath());
+ operationInput.setParentPropertyType(componentInput.getParentPropertyType());
+ operationInput.setSubPropertyInputPath(componentInput.getSubPropertyInputPath());
}
//Set the tosca default value for inputs mapped to component inputs as well as other outputs
operationInput.setToscaDefaultValue(getInputToscaDefaultValue(operationInput, component));
}
- private String getInputToscaDefaultValue(OperationInputDefinition input,
- org.openecomp.sdc.be.model.Component component) {
+ private String getInputToscaDefaultValue(OperationInputDefinition input, org.openecomp.sdc.be.model.Component component) {
Map<String, List<String>> defaultInputValue = null;
if (isOperationInputMappedToComponentInput(input, component.getInputs())) {
String propertyName = input.getInputId().substring(input.getInputId().indexOf('.') + 1);
- setParentPropertyTypeAndInputPath(input, component);
+ setParentPropertyTypeAndInputPath(input, component);
defaultInputValue = createMappedInputPropertyDefaultValue(propertyName);
} else if (isCapabilityProperty(input.getInputId(), component).isPresent()) {
- Optional<ComponentInstanceProperty> instancePropertyOpt = isCapabilityProperty(input.getInputId(),
- component);
+ Optional<ComponentInstanceProperty> instancePropertyOpt = isCapabilityProperty(input.getInputId(), component);
Optional<String> parentPropertyIdOpt = instancePropertyOpt.map(PropertyDataDefinition::getParentUniqueId);
Map<String, List<CapabilityDefinition>> componentCapabilities = component.getCapabilities();
- if(MapUtils.isNotEmpty(componentCapabilities)) {
- List<CapabilityDefinition> capabilityDefinitionList = componentCapabilities.values().stream()
- .flatMap(Collection::stream)
- .filter(capabilityDefinition -> capabilityDefinition.getOwnerId().equals(component.getUniqueId()))
- .collect(Collectors.toList());
-
+ if (MapUtils.isNotEmpty(componentCapabilities)) {
+ List<CapabilityDefinition> capabilityDefinitionList = componentCapabilities.values().stream().flatMap(Collection::stream)
+ .filter(capabilityDefinition -> capabilityDefinition.getOwnerId().equals(component.getUniqueId())).collect(Collectors.toList());
defaultInputValue = parentPropertyIdOpt
- .flatMap(parentPropertyId ->
- getPropertyCapabilityFromAllCapProps(parentPropertyId, capabilityDefinitionList))
- .flatMap(capability ->
- instancePropertyOpt.map(instanceProperty ->
- new ImmutablePair<>(capability.getName(), instanceProperty.getName())))
- .map(tuple -> {
+ .flatMap(parentPropertyId -> getPropertyCapabilityFromAllCapProps(parentPropertyId, capabilityDefinitionList)).flatMap(
+ capability -> instancePropertyOpt
+ .map(instanceProperty -> new ImmutablePair<>(capability.getName(), instanceProperty.getName()))).map(tuple -> {
String propertyName = tuple.right;
String capabilityName = tuple.left;
-
return createMappedCapabilityPropertyDefaultValue(capabilityName, propertyName);
}).orElse(null);
}
@@ -506,36 +428,28 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic {
return new Gson().toJson(defaultInputValue);
}
- private void setParentPropertyTypeAndInputPath(OperationInputDefinition input,
- org.openecomp.sdc.be.model.Component component) {
- if (CollectionUtils.isEmpty(component.getInputs())) {
- return;
- }
-
- component.getInputs()
- .stream()
- .filter(inp -> inp.getUniqueId().equals(
- input.getInputId().substring(0, input.getInputId().lastIndexOf('.'))))
- .forEach(inp -> {
- input.setParentPropertyType(inp.getParentPropertyType());
- if (Objects.nonNull(input.getName())) {
- input.setSubPropertyInputPath(input.getName().replaceAll("\\.", "#"));
- }
- });
- }
+ private void setParentPropertyTypeAndInputPath(OperationInputDefinition input, org.openecomp.sdc.be.model.Component component) {
+ if (CollectionUtils.isEmpty(component.getInputs())) {
+ return;
+ }
+ component.getInputs().stream().filter(inp -> inp.getUniqueId().equals(input.getInputId().substring(0, input.getInputId().lastIndexOf('.'))))
+ .forEach(inp -> {
+ input.setParentPropertyType(inp.getParentPropertyType());
+ if (Objects.nonNull(input.getName())) {
+ input.setSubPropertyInputPath(input.getName().replaceAll("\\.", "#"));
+ }
+ });
+ }
private void addOperationToInterface(InterfaceDefinition interfaceDefinition, Operation interfaceOperation) {
interfaceOperation.setUniqueId(UUID.randomUUID().toString());
interfaceOperation.setImplementation(createArtifactDefinition(UUID.randomUUID().toString(), interfaceOperation));
- interfaceDefinition.getOperations()
- .put(interfaceOperation.getUniqueId(), new OperationDataDefinition(interfaceOperation));
+ interfaceDefinition.getOperations().put(interfaceOperation.getUniqueId(), new OperationDataDefinition(interfaceOperation));
}
- private void updateOperationOnInterface(InterfaceDefinition interfaceDefinition, Operation interfaceOperation,
- String artifactUuId) {
+ private void updateOperationOnInterface(InterfaceDefinition interfaceDefinition, Operation interfaceOperation, String artifactUuId) {
interfaceOperation.setImplementation(createArtifactDefinition(artifactUuId, interfaceOperation));
- interfaceDefinition.getOperations()
- .put(interfaceOperation.getUniqueId(), new OperationDataDefinition(interfaceOperation));
+ interfaceDefinition.getOperations().put(interfaceOperation.getUniqueId(), new OperationDataDefinition(interfaceOperation));
}
private ArtifactDefinition createArtifactDefinition(String artifactUuId, Operation operation) {
@@ -551,60 +465,50 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic {
}
public Either<List<InterfaceDefinition>, ResponseFormat> updateInterfaceOperation(String componentId,
- List<InterfaceDefinition> interfaceDefinitions, User user, boolean lock) {
- return createOrUpdateInterfaceOperation(componentId, interfaceDefinitions, user, true,
- UPDATE_INTERFACE_OPERATION, lock);
+ List<InterfaceDefinition> interfaceDefinitions, User user,
+ boolean lock) {
+ return createOrUpdateInterfaceOperation(componentId, interfaceDefinitions, user, true, UPDATE_INTERFACE_OPERATION, lock);
}
- public Either<List<OperationInputDefinition>, ResponseFormat> getInputsListForOperation(String componentId,
- String componentInstanceId, String interfaceId, String operationId, User user) {
+ public Either<List<OperationInputDefinition>, ResponseFormat> getInputsListForOperation(String componentId, String componentInstanceId,
+ String interfaceId, String operationId, User user) {
Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId);
- if (componentEither.isRight()){
+ if (componentEither.isRight()) {
return Either.right(componentEither.right().value());
}
-
org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value();
validateUserExists(user.getUserId());
-
Either<Boolean, ResponseFormat> lockResult = lockComponentResult(true, storedComponent, GET_INTERFACE_OPERATION);
if (lockResult.isRight()) {
return Either.right(lockResult.right().value());
}
-
- try{
+ try {
org.openecomp.sdc.be.model.Component parentComponent = componentEither.left().value();
- Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces =
- parentComponent.getComponentInstancesInterfaces();
- if(MapUtils.isEmpty(componentInstanceInterfaces)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND,
- componentInstanceId));
+ Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces = parentComponent.getComponentInstancesInterfaces();
+ if (MapUtils.isEmpty(componentInstanceInterfaces)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentInstanceId));
}
-
- List<ComponentInstanceInterface> componentInstanceInterfaceList =
- componentInstanceInterfaces.get(componentInstanceId);
- for(ComponentInstanceInterface componentInstanceInterface : componentInstanceInterfaceList) {
- if(componentInstanceInterface.getInterfaceId().equals(interfaceId)){
+ List<ComponentInstanceInterface> componentInstanceInterfaceList = componentInstanceInterfaces.get(componentInstanceId);
+ for (ComponentInstanceInterface componentInstanceInterface : componentInstanceInterfaceList) {
+ if (componentInstanceInterface.getInterfaceId().equals(interfaceId)) {
Map<String, OperationDataDefinition> operations = componentInstanceInterface.getOperations();
- if(MapUtils.isNotEmpty(operations) && operations.containsKey(operationId)) {
+ if (MapUtils.isNotEmpty(operations) && operations.containsKey(operationId)) {
ListDataDefinition<OperationInputDefinition> inputs = operations.get(operationId).getInputs();
- return Either.left(CollectionUtils.isEmpty(inputs.getListToscaDataDefinition())
- ? new ArrayList<>() : inputs.getListToscaDataDefinition());
+ return Either.left(
+ CollectionUtils.isEmpty(inputs.getListToscaDataDefinition()) ? new ArrayList<>() : inputs.getListToscaDataDefinition());
}
}
}
return Either.left(new ArrayList<>());
- }
- catch (Exception e) {
+ } catch (Exception e) {
LOGGER.error(EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION, "get", e);
janusGraphDao.rollback();
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND));
- }
- finally {
+ } finally {
if (lockResult.isLeft() && lockResult.left().value()) {
- graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
- NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+ graphLockOperation
+ .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
}
}
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/NodeFilterUploadCreator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/NodeFilterUploadCreator.java
index 927c8b17b7..9d72eeca87 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/NodeFilterUploadCreator.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/NodeFilterUploadCreator.java
@@ -13,20 +13,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.openecomp.sdc.be.components.impl;
-import org.onap.sdc.tosca.services.YamlUtil;
-import org.openecomp.sdc.be.model.UploadNodeFilterCapabilitiesInfo;
-import org.openecomp.sdc.be.model.UploadNodeFilterInfo;
-import org.openecomp.sdc.be.model.UploadNodeFilterPropertyInfo;
-import org.openecomp.sdc.be.utils.TypeUtils;
-
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
+import org.onap.sdc.tosca.services.YamlUtil;
+import org.openecomp.sdc.be.model.UploadNodeFilterCapabilitiesInfo;
+import org.openecomp.sdc.be.model.UploadNodeFilterInfo;
+import org.openecomp.sdc.be.model.UploadNodeFilterPropertyInfo;
+import org.openecomp.sdc.be.utils.TypeUtils;
public class NodeFilterUploadCreator {
@@ -35,7 +33,6 @@ public class NodeFilterUploadCreator {
return null;
}
Map<String, Object> nodeFilterMap = (Map<String, Object>) obj;
-
UploadNodeFilterInfo uploadNodeFilterInfo = new UploadNodeFilterInfo();
final String propertiesElementName = TypeUtils.ToscaTagNamesEnum.PROPERTIES.getElementName();
if (nodeFilterMap.containsKey(propertiesElementName)) {
@@ -43,8 +40,7 @@ public class NodeFilterUploadCreator {
}
final String capabilitiesElementName = TypeUtils.ToscaTagNamesEnum.CAPABILITIES.getElementName();
if (nodeFilterMap.containsKey(capabilitiesElementName)) {
- uploadNodeFilterInfo
- .setCapabilities(createNodeFilterCapabilities(nodeFilterMap.get(capabilitiesElementName)));
+ uploadNodeFilterInfo.setCapabilities(createNodeFilterCapabilities(nodeFilterMap.get(capabilitiesElementName)));
}
final String toscaId = TypeUtils.ToscaTagNamesEnum.TOSCA_ID.getElementName();
if (nodeFilterMap.containsKey(toscaId)) {
@@ -67,8 +63,7 @@ public class NodeFilterUploadCreator {
valueList.add(valueToProperty(entry.getValue()));
retVal.add(new UploadNodeFilterPropertyInfo(entry.getKey(), valueList));
} else if (value instanceof List) {
- List<String> propertiesVals =
- (List<String>) ((List) value).stream().map(this::valueToProperty).collect(Collectors.toList());
+ List<String> propertiesVals = (List<String>) ((List) value).stream().map(this::valueToProperty).collect(Collectors.toList());
retVal.add(new UploadNodeFilterPropertyInfo(entry.getKey(), propertiesVals));
}
}
@@ -76,7 +71,6 @@ public class NodeFilterUploadCreator {
}
private String valueToProperty(Object o) {
-
if (o instanceof Map) {
return new YamlUtil().objectToYaml(o);
}
@@ -97,7 +91,6 @@ public class NodeFilterUploadCreator {
retVal.put(entry.getKey(), uploadNodeFilterCapabilitiesInfo);
}
return retVal;
-
}
private List<UploadNodeFilterPropertyInfo> createCapabilitiesProperties(Object o) {
@@ -112,6 +105,4 @@ public class NodeFilterUploadCreator {
}
return null;
}
-
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OnDeleteEntityOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OnDeleteEntityOperation.java
index f64c11a077..2a9157ac14 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OnDeleteEntityOperation.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OnDeleteEntityOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -27,10 +26,10 @@ public interface OnDeleteEntityOperation {
/**
* side effect operation to be executed when a given entity is deleted
- * @param container the container which holds the entity to be deleted
+ *
+ * @param container the container which holds the entity to be deleted
* @param deletedEntityId the id of the entity that was deleted
* @return the status of the on delete operation
*/
ActionStatus onDelete(Component container, String deletedEntityId);
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OutputsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OutputsBusinessLogic.java
index cfb6004620..2d6a619cc7 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OutputsBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OutputsBusinessLogic.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
@@ -57,7 +56,6 @@ import org.springframework.beans.factory.annotation.Autowired;
public class OutputsBusinessLogic extends BaseBusinessLogic {
private static final String CREATE_OUTPUT = "CreateOutput";
-
private static final Logger log = Logger.getLogger(OutputsBusinessLogic.class);
private static final String FAILED_TO_FOUND_COMPONENT_ERROR = "Failed to found component {}, error: {}";
private static final String GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP = "Going to execute rollback on create group.";
@@ -65,16 +63,12 @@ public class OutputsBusinessLogic extends BaseBusinessLogic {
private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(OutputsBusinessLogic.class);
private static final String FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_COMPONENT_INSTANCE_ID = "Failed to found component instance outputs componentInstanceId: {}";
private static final String FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_ERROR = "Failed to found component instance outputs {}, error: {}";
-
private final AttributeDeclarationOrchestrator attributeDeclarationOrchestrator;
@Autowired
- public OutputsBusinessLogic(final IElementOperation elementDao,
- final IGroupOperation groupOperation,
- final IGroupInstanceOperation groupInstanceOperation,
- final IGroupTypeOperation groupTypeOperation,
- final InterfaceOperation interfaceOperation,
- final InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+ public OutputsBusinessLogic(final IElementOperation elementDao, final IGroupOperation groupOperation,
+ final IGroupInstanceOperation groupInstanceOperation, final IGroupTypeOperation groupTypeOperation,
+ final InterfaceOperation interfaceOperation, final InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
final AttributeDeclarationOrchestrator attributeDeclarationOrchestrator,
final ArtifactsOperations artifactToscaOperation) {
super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
@@ -82,76 +76,58 @@ public class OutputsBusinessLogic extends BaseBusinessLogic {
this.attributeDeclarationOrchestrator = attributeDeclarationOrchestrator;
}
- public Either<List<ComponentInstanceOutput>, ResponseFormat> getComponentInstanceOutputs(final String userId,
- final String componentId,
+ public Either<List<ComponentInstanceOutput>, ResponseFormat> getComponentInstanceOutputs(final String userId, final String componentId,
final String componentInstanceId) {
-
validateUserExists(userId);
final ComponentParametersView filters = new ComponentParametersView();
filters.disableAll();
filters.setIgnoreOutputs(false);
filters.setIgnoreComponentInstances(false);
filters.setIgnoreComponentInstancesOutputs(false);
-
final Either<Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
- if(getComponentEither.isRight()){
+ if (getComponentEither.isRight()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, componentId, actionStatus);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
}
final Component component = getComponentEither.left().value();
-
if (!ComponentValidations.validateComponentInstanceExist(component, componentInstanceId)) {
final ActionStatus actionStatus = ActionStatus.COMPONENT_INSTANCE_NOT_FOUND;
log.debug(FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_ERROR, componentInstanceId, actionStatus);
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, component.getComponentMetadataForSupportLog(),
- StatusCode.ERROR, FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_COMPONENT_INSTANCE_ID, componentInstanceId);
+ loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, component.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_COMPONENT_INSTANCE_ID, componentInstanceId);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
}
final Map<String, List<ComponentInstanceOutput>> ciOutputs = Optional.ofNullable(component.getComponentInstancesOutputs())
.orElse(Collections.emptyMap());
-
return Either.left(ciOutputs.getOrDefault(componentInstanceId, Collections.emptyList()));
}
@Override
- public Either<List<OutputDefinition>, ResponseFormat> declareAttributes(final String userId,
- final String componentId,
+ public Either<List<OutputDefinition>, ResponseFormat> declareAttributes(final String userId, final String componentId,
final ComponentTypeEnum componentTypeEnum,
final ComponentInstOutputsMap componentInstOutputsMap) {
-
return createMultipleOutputs(userId, componentId, componentTypeEnum, componentInstOutputsMap, true, false);
}
- public Either<List<OutputDefinition>, ResponseFormat> createMultipleOutputs(final String userId,
- final String componentId,
+ public Either<List<OutputDefinition>, ResponseFormat> createMultipleOutputs(final String userId, final String componentId,
final ComponentTypeEnum componentType,
final ComponentInstOutputsMap componentInstOutputsMapUi,
- final boolean shouldLockComp,
- final boolean inTransaction) {
-
+ final boolean shouldLockComp, final boolean inTransaction) {
Either<List<OutputDefinition>, ResponseFormat> result = null;
org.openecomp.sdc.be.model.Component component = null;
-
try {
validateUserExists(userId);
-
component = getAndValidateComponentForCreate(userId, componentId, componentType, shouldLockComp);
-
- result = attributeDeclarationOrchestrator.declareAttributesToOutputs(component, componentInstOutputsMapUi)
- .left()
- .bind(outputsToCreate -> prepareOutputsForCreation(userId, componentId, outputsToCreate))
- .right()
+ result = attributeDeclarationOrchestrator.declareAttributesToOutputs(component, componentInstOutputsMapUi).left()
+ .bind(outputsToCreate -> prepareOutputsForCreation(userId, componentId, outputsToCreate)).right()
.map(componentsUtils::getResponseFormat);
return result;
-
} catch (final ByResponseFormatComponentException e) {
log.error("#createMultipleOutputs: Exception thrown: ", e);
result = Either.right(e.getResponseFormat());
return result;
} finally {
-
if (!inTransaction) {
if (result == null || result.isRight()) {
log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP);
@@ -165,12 +141,10 @@ public class OutputsBusinessLogic extends BaseBusinessLogic {
if (shouldLockComp && component != null) {
graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
}
-
}
}
- private org.openecomp.sdc.be.model.Component getAndValidateComponentForCreate(final String userId,
- final String componentId,
+ private org.openecomp.sdc.be.model.Component getAndValidateComponentForCreate(final String userId, final String componentId,
final ComponentTypeEnum componentType,
final boolean shouldLockComp) {
final ComponentParametersView componentParametersView = getBaseComponentParametersView();
@@ -183,15 +157,11 @@ public class OutputsBusinessLogic extends BaseBusinessLogic {
return component;
}
- private Either<List<OutputDefinition>, StorageOperationStatus> prepareOutputsForCreation(final String userId,
- final String cmptId,
+ private Either<List<OutputDefinition>, StorageOperationStatus> prepareOutputsForCreation(final String userId, final String cmptId,
final List<OutputDefinition> outputsToCreate) {
final Map<String, OutputDefinition> outputsToPersist = MapUtil.toMap(outputsToCreate, OutputDefinition::getName);
assignOwnerIdToOutputs(userId, outputsToPersist);
-
- return toscaOperationFacade.addOutputsToComponent(outputsToPersist, cmptId)
- .left()
- .map(persistedOutputs -> outputsToCreate);
+ return toscaOperationFacade.addOutputsToComponent(outputsToPersist, cmptId).left().map(persistedOutputs -> outputsToCreate);
}
private void assignOwnerIdToOutputs(final String userId, final Map<String, OutputDefinition> outputsToCreate) {
@@ -219,24 +189,19 @@ public class OutputsBusinessLogic extends BaseBusinessLogic {
* @return
*/
public OutputDefinition deleteOutput(final String componentId, final String userId, final String outputId) {
-
Either<OutputDefinition, ResponseFormat> deleteEither = null;
if (log.isDebugEnabled()) {
log.debug("Going to delete output id: {}", outputId);
}
-
validateUserExists(userId);
-
final ComponentParametersView componentParametersView = getBaseComponentParametersView();
componentParametersView.setIgnoreAttributes(false);
-
- final Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentEither =
- toscaOperationFacade.getToscaElement(componentId, componentParametersView);
+ final Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentEither = toscaOperationFacade
+ .getToscaElement(componentId, componentParametersView);
if (componentEither.isRight()) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(componentEither.right().value()));
}
final org.openecomp.sdc.be.model.Component component = componentEither.left().value();
-
// Validate outputId is child of the component
final Optional<OutputDefinition> optionalOutput = component.getOutputs().stream().
// filter by ID
@@ -246,23 +211,19 @@ public class OutputsBusinessLogic extends BaseBusinessLogic {
if (!optionalOutput.isPresent()) {
throw new ByActionStatusComponentException(ActionStatus.OUTPUT_IS_NOT_CHILD_OF_COMPONENT, outputId, componentId);
}
-
final OutputDefinition outputForDelete = optionalOutput.get();
-
// Lock component
lockComponent(componentId, component, "deleteOutput");
// Delete output operations
boolean failed = false;
try {
- final StorageOperationStatus status =
- toscaOperationFacade.deleteOutputOfResource(component, outputForDelete.getName());
+ final StorageOperationStatus status = toscaOperationFacade.deleteOutputOfResource(component, outputForDelete.getName());
if (status != StorageOperationStatus.OK) {
log.debug("Component id: {} delete output id: {} failed", componentId, outputId);
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), component.getName());
}
-
- final StorageOperationStatus storageOperationStatus =
- attributeDeclarationOrchestrator.unDeclareAttributesAsOutputs(component, outputForDelete);
+ final StorageOperationStatus storageOperationStatus = attributeDeclarationOrchestrator
+ .unDeclareAttributesAsOutputs(component, outputForDelete);
if (storageOperationStatus != StorageOperationStatus.OK) {
log.debug("Component id: {} update attributes declared as output for outputId: {} failed", componentId, outputId);
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), component.getName());
@@ -275,5 +236,4 @@ public class OutputsBusinessLogic extends BaseBusinessLogic {
unlockComponent(failed, component);
}
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java
index f872074f26..70e387915d 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,13 +17,25 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
+import static java.util.stream.Collectors.toMap;
+import static org.openecomp.sdc.be.components.validation.PolicyUtils.getExcludedPolicyTypesByComponent;
+import static org.openecomp.sdc.be.components.validation.PolicyUtils.getNextPolicyCounter;
+import static org.openecomp.sdc.be.components.validation.PolicyUtils.validatePolicyFields;
+
import fj.data.Either;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collections;
import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
@@ -62,20 +74,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
-import static java.util.stream.Collectors.toMap;
-import static org.openecomp.sdc.be.components.validation.PolicyUtils.getExcludedPolicyTypesByComponent;
-import static org.openecomp.sdc.be.components.validation.PolicyUtils.getNextPolicyCounter;
-import static org.openecomp.sdc.be.components.validation.PolicyUtils.validatePolicyFields;
-
/**
* Provides specified business logic to create, retrieve, update, delete a policy
*/
@@ -85,20 +83,15 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
private static final String FAILED_TO_VALIDATE_COMPONENT = "#{} - failed to validate the component {} before policy processing. ";
private static final String DECLARE_PROPERTIES_TO_POLICIES = "declare properties to policies";
private static final Logger log = Logger.getLogger(PolicyBusinessLogic.class);
- private static final LoggerSupportability loggerSupportability= LoggerSupportability.getLogger(PolicyBusinessLogic.class.getName());
-
+ private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(PolicyBusinessLogic.class.getName());
private PropertyDeclarationOrchestrator propertyDeclarationOrchestrator;
@Autowired
- public PolicyBusinessLogic(IElementOperation elementDao,
- IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation,
- IGroupTypeOperation groupTypeOperation,
- InterfaceOperation interfaceOperation,
- InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
- ArtifactsOperations artifactToscaOperation) {
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
- interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+ public PolicyBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+ IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
+ InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+ artifactToscaOperation);
}
@Autowired
@@ -116,25 +109,24 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
* @param shouldLock the flag defining if the component should be locked
* @return a policy or an error in a response format
*/
-
- public PolicyDefinition createPolicy(ComponentTypeEnum componentType, String componentId, String policyTypeName, String userId, boolean shouldLock) {
-
+ public PolicyDefinition createPolicy(ComponentTypeEnum componentType, String componentId, String policyTypeName, String userId,
+ boolean shouldLock) {
log.trace("#createPolicy - starting to create policy of the type {} on the component {}. ", policyTypeName, componentId);
Component component = null;
boolean failed = false;
try {
component = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock);
return createPolicy(policyTypeName, component);
- }catch (ComponentException e){
+ } catch (ComponentException e) {
failed = true;
throw e;
- }finally {
+ } finally {
unlockComponent(shouldLock, failed, component);
}
}
public Map<String, PolicyDefinition> createPoliciesFromParsedCsar(Component component,
- final Map<String, PolicyDefinition> incomingPolicyDefinitions) {
+ final Map<String, PolicyDefinition> incomingPolicyDefinitions) {
if (MapUtils.isEmpty(incomingPolicyDefinitions)) {
return Collections.emptyMap();
}
@@ -143,8 +135,9 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
PolicyDefinition incomingPolicyDefinition = policyEntry.getValue();
String policyName = incomingPolicyDefinition.getName();
log.trace("Going to create policy {}", incomingPolicyDefinition);
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(),
- StatusCode.STARTED,"Start to create policy: {} for component {}", policyName, component.getName());
+ loggerSupportability
+ .log(LoggerSupportabilityActions.CREATE_GROUP_POLICY, component.getComponentMetadataForSupportLog(), StatusCode.STARTED,
+ "Start to create policy: {} for component {}", policyName, component.getName());
String policyType = incomingPolicyDefinition.getType();
if (StringUtils.isEmpty(policyType)) {
log.debug("Policy type '{}' for policy '{}' not found.", policyType, policyName);
@@ -164,26 +157,25 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
List<PropertyDataDefinition> properties = incomingPolicyDefinition.getProperties();
createdPolicyDefinition = setUpdatePolicyProperties(component, createdPolicyDefinition, properties);
createdPolicies.put(policyName, createdPolicyDefinition);
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_POLICIES,component.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,"policy {} has been created ", policyName);
+ loggerSupportability.log(LoggerSupportabilityActions.CREATE_POLICIES, component.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
+ "policy {} has been created ", policyName);
}
return createdPolicies;
}
- private PolicyDefinition setUpdatePolicyProperties(Component component, PolicyDefinition policyDefinition, List<PropertyDataDefinition> properties) {
+ private PolicyDefinition setUpdatePolicyProperties(Component component, PolicyDefinition policyDefinition,
+ List<PropertyDataDefinition> properties) {
if (CollectionUtils.isNotEmpty(properties)) {
PropertyDataDefinition[] propertiesArray = properties.toArray(new PropertyDataDefinition[properties.size()]);
- List<PropertyDataDefinition> updatedPropertiesList = setComponentValidateUpdatePolicyProperties(
- policyDefinition.getUniqueId(),
- propertiesArray,
- component
- );
+ List<PropertyDataDefinition> updatedPropertiesList = setComponentValidateUpdatePolicyProperties(policyDefinition.getUniqueId(),
+ propertiesArray, component);
policyDefinition.setProperties(updatedPropertiesList);
}
return policyDefinition;
}
private PolicyDefinition setUpdatePolicyTargets(Component component, PolicyDefinition policyDefinition,
- Map<PolicyTargetType, List<String>> targets) {
+ Map<PolicyTargetType, List<String>> targets) {
if (MapUtils.isEmpty(targets)) {
return policyDefinition;
}
@@ -196,19 +188,13 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
for (String targetName : targetsToUpdate) {
Optional<ComponentInstance> componentInstance = component.getComponentInstanceByName(targetName);
String componentUniqueId = componentInstance
- .orElseThrow(
- () -> new ByActionStatusComponentException(
- ActionStatus.COMPONENT_INSTANCE_NOT_FOUND
- )
- )
- .getUniqueId();
+ .orElseThrow(() -> new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND)).getUniqueId();
targetsUniqueIds.add(componentUniqueId);
}
EnumMap<PolicyTargetType, List<String>> updatedTargets = new EnumMap<>(PolicyTargetType.class);
updatedTargets.put(PolicyTargetType.COMPONENT_INSTANCES, targetsUniqueIds);
policyDefinition.setTargets(updatedTargets);
- policyDefinition = validateAndUpdatePolicyTargets(component, policyDefinition.getUniqueId(),
- policyDefinition.getTargets());
+ policyDefinition = validateAndUpdatePolicyTargets(component, policyDefinition.getUniqueId(), policyDefinition.getTargets());
return policyDefinition;
}
@@ -236,7 +222,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
}
return result;
}*/
-
public Either<List<PolicyDefinition>, ResponseFormat> getPoliciesList(ComponentTypeEnum componentType, String componentId, String userId) {
Either<List<PolicyDefinition>, ResponseFormat> result;
log.trace("#getPolicies - starting to retrieve policies of component {}. ", componentId);
@@ -250,8 +235,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
return result;
}
-
-
/**
* Retrieves the policy of the component by UniqueId
*
@@ -266,7 +249,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
Component component = validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId);
return getPolicyById(component, policyId);
}
-
/*public Either<PolicyDefinition, ResponseFormat> getPolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId) {
Either<PolicyDefinition, ResponseFormat> result;
log.trace("#getPolicy - starting to retrieve the policy {} of the component {}. ", policyId, componentId);
@@ -291,7 +273,8 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
* @param shouldLock the flag defining if the component should be locked
* @return a policy or an error in a response format
*/
- public PolicyDefinition updatePolicy(ComponentTypeEnum componentType, String componentId, PolicyDefinition policy, String userId, boolean shouldLock) {
+ public PolicyDefinition updatePolicy(ComponentTypeEnum componentType, String componentId, PolicyDefinition policy, String userId,
+ boolean shouldLock) {
Component component = null;
boolean failed = false;
log.trace("#updatePolicy - starting to update the policy {} on the component {}. ", policy.getUniqueId(), componentId);
@@ -300,15 +283,14 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
return validateAndUpdatePolicy(component, policy);
} catch (ComponentException e) {
failed = true;
- log.error("#updatePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policy.getUniqueId(), componentId, e);
+ log.error("#updatePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policy.getUniqueId(),
+ componentId, e);
throw e;
} finally {
//TODO Andrey result = boolean
unlockComponent(shouldLock, failed, component);
}
}
-
-
/*public Either<PolicyDefinition, ResponseFormat> updatePolicy(ComponentTypeEnum componentType, String componentId, PolicyDefinition policy, String userId, boolean shouldLock) {
Either<PolicyDefinition, ResponseFormat> result = null;
log.trace("#updatePolicy - starting to update the policy {} on the component {}. ", policy.getUniqueId(), componentId);
@@ -344,20 +326,20 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
PolicyDefinition result = null;
log.trace("#deletePolicy - starting to update the policy {} on the component {}. ", policyId, componentId);
Component component = null;
- boolean failed= false;
+ boolean failed = false;
try {
component = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock);
return deletePolicy(component, policyId);
} catch (ComponentException e) {
failed = true;
- log.error("#deletePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policyId, componentId, e);
+ log.error("#deletePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policyId, componentId,
+ e);
throw e;
} finally {
unlockComponent(shouldLock, failed, component);
}
}
-
/*public Either<PolicyDefinition, ResponseFormat> deletePolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId, boolean shouldLock) {
Either<PolicyDefinition, ResponseFormat> result = null;
log.trace("#deletePolicy - starting to update the policy {} on the component {}. ", policyId, componentId);
@@ -409,39 +391,35 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
unlockComponent(shouldLock, result, component);
}
}*/
-
- public Either<PolicyDefinition, ResponseFormat> undeclarePolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId, boolean shouldLock) {
+ public Either<PolicyDefinition, ResponseFormat> undeclarePolicy(ComponentTypeEnum componentType, String componentId, String policyId,
+ String userId, boolean shouldLock) {
Either<PolicyDefinition, ResponseFormat> result = null;
log.trace("#undeclarePolicy - starting to undeclare policy {} on component {}. ", policyId, componentId);
Wrapper<Component> component = new Wrapper<>();
try {
validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock);
-
ComponentParametersView componentParametersView = new ComponentParametersView();
componentParametersView.disableAll();
componentParametersView.setIgnoreComponentInstances(false);
componentParametersView.setIgnoreComponentInstancesProperties(false);
componentParametersView.setIgnorePolicies(false);
-
- Either<Component, StorageOperationStatus> componentWithFilters =
- toscaOperationFacade.getToscaElement(componentId, componentParametersView);
+ Either<Component, StorageOperationStatus> componentWithFilters = toscaOperationFacade
+ .getToscaElement(componentId, componentParametersView);
if (componentWithFilters.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentWithFilters.right().value())));
+ return Either
+ .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentWithFilters.right().value())));
}
-
Component containerComponent = componentWithFilters.left().value();
-
Optional<PolicyDefinition> policyCandidate = getPolicyForUndeclaration(policyId, containerComponent);
- if(policyCandidate.isPresent()) {
+ if (policyCandidate.isPresent()) {
result = undeclarePolicy(policyCandidate.get(), containerComponent);
}
-
return result;
- }catch (Exception e) {
+ } catch (Exception e) {
log.error("#undeclarePolicy - the exception occurred upon update of a policy of type {} for component {}: ", policyId, componentId, e);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, e.getMessage()));
} finally {
- if (result == null || result.isRight()){
+ if (result == null || result.isRight()) {
unlockComponent(shouldLock, true, component);
} else {
unlockComponent(shouldLock, false, component);
@@ -449,56 +427,45 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
}
}
- private Either<PolicyDefinition, ResponseFormat> undeclarePolicy(PolicyDefinition policyDefinition, Component containerComponent) {
- StorageOperationStatus undeclareStatus = propertyDeclarationOrchestrator
- .unDeclarePropertiesAsPolicies(containerComponent, policyDefinition);
- if(undeclareStatus != StorageOperationStatus.OK){
- return Either.right(componentsUtils.getResponseFormat(undeclareStatus));
- } else {
- return Either.left(policyDefinition);
- }
+ private Either<PolicyDefinition, ResponseFormat> undeclarePolicy(PolicyDefinition policyDefinition, Component containerComponent) {
+ StorageOperationStatus undeclareStatus = propertyDeclarationOrchestrator.unDeclarePropertiesAsPolicies(containerComponent, policyDefinition);
+ if (undeclareStatus != StorageOperationStatus.OK) {
+ return Either.right(componentsUtils.getResponseFormat(undeclareStatus));
+ } else {
+ return Either.left(policyDefinition);
}
+ }
-
- private Optional<PolicyDefinition> getPolicyForUndeclaration(String policyId, Component component) {
- Map<String, PolicyDefinition> policies = component.getPolicies();
- if(MapUtils.isNotEmpty(policies) && policies.containsKey(policyId)) {
- return Optional.of(policies.get(policyId));
- }
-
- Map<String, List<ComponentInstanceProperty>> componentInstancesProperties =
- MapUtils.isEmpty(component.getComponentInstancesProperties()) ? new HashMap<>() : component.getComponentInstancesProperties();
-
- for(Map.Entry<String, List<ComponentInstanceProperty>> instancePropertyEntry : componentInstancesProperties.entrySet()) {
- Optional<ComponentInstanceProperty> propertyCandidate = getPropertyForDeclaredPolicy(policyId, instancePropertyEntry.getValue());
-
- if(propertyCandidate.isPresent()) {
- return Optional.of(
- PolicyUtils.getDeclaredPolicyDefinition(instancePropertyEntry.getKey(), propertyCandidate.get()));
- }
+ private Optional<PolicyDefinition> getPolicyForUndeclaration(String policyId, Component component) {
+ Map<String, PolicyDefinition> policies = component.getPolicies();
+ if (MapUtils.isNotEmpty(policies) && policies.containsKey(policyId)) {
+ return Optional.of(policies.get(policyId));
+ }
+ Map<String, List<ComponentInstanceProperty>> componentInstancesProperties =
+ MapUtils.isEmpty(component.getComponentInstancesProperties()) ? new HashMap<>() : component.getComponentInstancesProperties();
+ for (Map.Entry<String, List<ComponentInstanceProperty>> instancePropertyEntry : componentInstancesProperties.entrySet()) {
+ Optional<ComponentInstanceProperty> propertyCandidate = getPropertyForDeclaredPolicy(policyId, instancePropertyEntry.getValue());
+ if (propertyCandidate.isPresent()) {
+ return Optional.of(PolicyUtils.getDeclaredPolicyDefinition(instancePropertyEntry.getKey(), propertyCandidate.get()));
}
-
- return Optional.empty();
}
+ return Optional.empty();
+ }
- private Optional<ComponentInstanceProperty> getPropertyForDeclaredPolicy(String policyId, List<ComponentInstanceProperty> componentInstanceProperties) {
- for(ComponentInstanceProperty property : componentInstanceProperties) {
- Optional<GetPolicyValueDataDefinition> getPolicyCandidate = property.safeGetGetPolicyValues().stream()
- .filter(getPolicyValue -> getPolicyValue.getPolicyId()
- .equals(policyId))
- .findAny();
-
- if(getPolicyCandidate.isPresent()) {
- return Optional.of(property);
- }
+ private Optional<ComponentInstanceProperty> getPropertyForDeclaredPolicy(String policyId,
+ List<ComponentInstanceProperty> componentInstanceProperties) {
+ for (ComponentInstanceProperty property : componentInstanceProperties) {
+ Optional<GetPolicyValueDataDefinition> getPolicyCandidate = property.safeGetGetPolicyValues().stream()
+ .filter(getPolicyValue -> getPolicyValue.getPolicyId().equals(policyId)).findAny();
+ if (getPolicyCandidate.isPresent()) {
+ return Optional.of(property);
}
-
- return Optional.empty();
}
+ return Optional.empty();
+ }
-
- public PolicyDefinition updatePolicyTargets(ComponentTypeEnum componentTypeEnum, String componentId, String policyId, Map<PolicyTargetType, List<String>> targets, String userId) {
-
+ public PolicyDefinition updatePolicyTargets(ComponentTypeEnum componentTypeEnum, String componentId, String policyId,
+ Map<PolicyTargetType, List<String>> targets, String userId) {
Either<PolicyDefinition, ResponseFormat> result = null;
log.debug("updating the policy id {} targets with the components {}. ", policyId, componentId);
boolean failed = false;
@@ -506,10 +473,10 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
//not right error response
Component component = validateAndLockComponentAndUserBeforeWriteOperation(componentTypeEnum, componentId, userId, true);
return validateAndUpdatePolicyTargets(component, policyId, targets);
- }catch (ComponentException e){
+ } catch (ComponentException e) {
failed = true;
throw e;
- }finally {
+ } finally {
unlockComponentById(failed, componentId);
}
}
@@ -528,7 +495,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
return validateTargetExists(parentComponent, targets.entrySet());
}
-
private Component validateTargetExists(Component parentComponent, Set<Map.Entry<PolicyTargetType, List<String>>> entries) {
for (Map.Entry<PolicyTargetType, List<String>> entry : entries) {
checkTargetNotExistOnComponentByType(parentComponent, entry);
@@ -537,7 +503,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
}
private Component checkTargetNotExistOnComponentByType(Component parentComponent, Map.Entry<PolicyTargetType, List<String>> targetEntry) {
-
for (String id : targetEntry.getValue()) {
if (checkNotPresenceInComponentByType(parentComponent, id, targetEntry.getKey().getName())) {
throw new ByActionStatusComponentException(ActionStatus.POLICY_TARGET_DOES_NOT_EXIST, id);
@@ -560,7 +525,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
return policyDefinition;
}
-
/**
* @param componentType the type of the component
* @param componentId the id of the component which the policy resides under
@@ -577,7 +541,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
janusGraphDao.commit();
}
}
-
/*public Either<List<PropertyDataDefinition>, ResponseFormat> getPolicyProperties(ComponentTypeEnum componentType, String componentId, String policyId, String userId) {
log.debug("#getPolicyProperties - fetching policy properties for component {} and policy {}", componentId, policyId);
try {
@@ -600,7 +563,8 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
* @param shouldLock the flag defining if the component should be locked
* @return a list of policy properties or anerrorin a response format
*/
- public List<PropertyDataDefinition> updatePolicyProperties(ComponentTypeEnum componentType, String componentId, String policyId, PropertyDataDefinition[] properties, String userId, boolean shouldLock) {
+ public List<PropertyDataDefinition> updatePolicyProperties(ComponentTypeEnum componentType, String componentId, String policyId,
+ PropertyDataDefinition[] properties, String userId, boolean shouldLock) {
List<PropertyDataDefinition> result;
Component component = null;
log.trace("#updatePolicyProperties - starting to update properties of the policy {} on the component {}. ", policyId, componentId);
@@ -618,47 +582,39 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
}
@Override
- public Either<List<PolicyDefinition>, ResponseFormat> declareProperties(String userId, String componentId,
- ComponentTypeEnum componentTypeEnum, ComponentInstInputsMap componentInstInputsMap) {
+ public Either<List<PolicyDefinition>, ResponseFormat> declareProperties(String userId, String componentId, ComponentTypeEnum componentTypeEnum,
+ ComponentInstInputsMap componentInstInputsMap) {
return declarePropertiesToPolicies(userId, componentId, componentTypeEnum, componentInstInputsMap, true, false);
-
}
private Either<List<PolicyDefinition>, ResponseFormat> declarePropertiesToPolicies(String userId, String componentId,
- ComponentTypeEnum componentTypeEnum, ComponentInstInputsMap componentInstInputsMap, boolean shouldLock,
- boolean inTransaction) {
+ ComponentTypeEnum componentTypeEnum,
+ ComponentInstInputsMap componentInstInputsMap,
+ boolean shouldLock, boolean inTransaction) {
Either<List<PolicyDefinition>, ResponseFormat> result = null;
org.openecomp.sdc.be.model.Component component = null;
-
try {
validateUserExists(userId);
-
ComponentParametersView componentParametersView = new ComponentParametersView();
componentParametersView.disableAll();
componentParametersView.setIgnoreComponentInstances(false);
componentParametersView.setIgnoreComponentInstancesProperties(false);
componentParametersView.setIgnorePolicies(false);
componentParametersView.setIgnoreUsers(false);
-
component = validateComponentExists(componentId, componentTypeEnum, componentParametersView);
-
if (shouldLock) {
lockComponent(component, DECLARE_PROPERTIES_TO_POLICIES);
}
-
validateCanWorkOnComponent(component, userId);
-
- Either<List<PolicyDefinition>, StorageOperationStatus> declarePropertiesEither =
- propertyDeclarationOrchestrator.declarePropertiesToPolicies(component, componentInstInputsMap);
-
- if(declarePropertiesEither.isRight()) {
+ Either<List<PolicyDefinition>, StorageOperationStatus> declarePropertiesEither = propertyDeclarationOrchestrator
+ .declarePropertiesToPolicies(component, componentInstInputsMap);
+ if (declarePropertiesEither.isRight()) {
return Either.right(componentsUtils.getResponseFormat(declarePropertiesEither.right().value()));
}
-
result = Either.left(declarePropertiesEither.left().value());
return result;
} finally {
- if(!inTransaction) {
+ if (!inTransaction) {
commitOrRollback(result);
}
// unlock resource
@@ -668,9 +624,9 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
}
}
- private List<PropertyDataDefinition> setComponentValidateUpdatePolicyProperties(String policyId, PropertyDataDefinition[] properties, Component component) {
+ private List<PropertyDataDefinition> setComponentValidateUpdatePolicyProperties(String policyId, PropertyDataDefinition[] properties,
+ Component component) {
Set<String> updatedPropertyNames = Arrays.stream(properties).map(PropertyDataDefinition::getName).collect(Collectors.toSet());
-
PolicyDefinition policyDefinition = validateAndUpdatePolicyProperties(component, policyId, properties);
return getFilteredProperties(policyDefinition.getProperties(), updatedPropertyNames);
}
@@ -685,7 +641,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
}
}
-
private void unlockComponent(boolean shouldLock, boolean result, Wrapper<Component> component) {
if (shouldLock && !component.isEmpty()) {
unlockComponent(result, component.getInnerElement());
@@ -710,11 +665,10 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
/*private Either<PolicyDefinition, ResponseFormat> createPolicy(String policyTypeName, Component component) {
return validatePolicyTypeOnCreatePolicy(policyTypeName, component).left().bind(type -> addPolicyToComponent(type, component));
}*/
-
private PolicyDefinition addPolicyToComponent(PolicyTypeDefinition policyType, Component component) {
- Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent =
- toscaOperationFacade.associatePolicyToComponent(component.getUniqueId(), new PolicyDefinition(policyType), getNextPolicyCounter(component.getPolicies()));
- if(associatePolicyToComponent.isRight()){
+ Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent = toscaOperationFacade
+ .associatePolicyToComponent(component.getUniqueId(), new PolicyDefinition(policyType), getNextPolicyCounter(component.getPolicies()));
+ if (associatePolicyToComponent.isRight()) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(associatePolicyToComponent.right().value()));
}
return associatePolicyToComponent.left().value();
@@ -724,10 +678,9 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
return toscaOperationFacade.associatePolicyToComponent(component.getUniqueId(), new PolicyDefinition(policyType), getNextPolicyCounter(component.getPolicies()))
.either(Either::left, r -> Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(r))));
}*/
-
private PolicyTypeDefinition validatePolicyTypeOnCreatePolicy(String policyTypeName, Component component) {
Either<PolicyTypeDefinition, StorageOperationStatus> latestPolicyTypeByType = policyTypeOperation.getLatestPolicyTypeByType(policyTypeName);
- if(latestPolicyTypeByType.isRight()){
+ if (latestPolicyTypeByType.isRight()) {
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(latestPolicyTypeByType.right().value()));
}
return validatePolicyTypeNotExcluded(latestPolicyTypeByType.left().value(), component);
@@ -737,19 +690,21 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
return policyTypeOperation.getLatestPolicyTypeByType(policyTypeName)
.either(l -> validatePolicyTypeNotExcluded(l, component), r -> Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(r))));
}*/
-
private PolicyTypeDefinition validatePolicyTypeNotExcluded(PolicyTypeDefinition policyType, Component component) {
if (getExcludedPolicyTypesByComponent(component).contains(policyType.getType())) {
- throw new ByActionStatusComponentException(ActionStatus.EXCLUDED_POLICY_TYPE, policyType.getType(), getComponentOrResourceTypeName(component));
+ throw new ByActionStatusComponentException(ActionStatus.EXCLUDED_POLICY_TYPE, policyType.getType(),
+ getComponentOrResourceTypeName(component));
}
return policyType;
}
private String getComponentOrResourceTypeName(Component component) {
- return component.getComponentType() == ComponentTypeEnum.SERVICE ? ComponentTypeEnum.SERVICE.name() : ((Resource) component).getResourceType().name();
+ return component.getComponentType() == ComponentTypeEnum.SERVICE ? ComponentTypeEnum.SERVICE.name()
+ : ((Resource) component).getResourceType().name();
}
- private Component validateAndLockComponentAndUserBeforeWriteOperation(ComponentTypeEnum componentType, String componentId, String userId, boolean shouldLock) {
+ private Component validateAndLockComponentAndUserBeforeWriteOperation(ComponentTypeEnum componentType, String componentId, String userId,
+ boolean shouldLock) {
Component component = validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId);
validateComponentIsTopologyTemplate(component);
validateCanWorkOnComponent(component, userId);
@@ -775,13 +730,12 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
return Either.right(r);
});
}*/
-
private Component validateComponentIsTopologyTemplate(Component component) {
if (!component.isTopologyTemplate()) {
log.error("#validateComponentIsTopologyTemplate - policy association to a component of Tosca type {} is not allowed. ",
- component.getToscaType());
+ component.getToscaType());
throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_POLICIES,
- "#validateAndLockComponentAndUserBeforeWriteOperation", component.getUniqueId(), component.getToscaType());
+ "#validateAndLockComponentAndUserBeforeWriteOperation", component.getUniqueId(), component.getToscaType());
}
return component;
}
@@ -800,7 +754,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
}
private Component validateComponentExists(ComponentTypeEnum componentType, String componentId) {
-
ComponentParametersView filter = new ComponentParametersView(true);
filter.setIgnorePolicies(false);
filter.setIgnoreUsers(false);
@@ -809,7 +762,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
return validateComponentExists(componentId, componentType, filter);
}
-
private PolicyDefinition validateAndUpdatePolicy(Component component, PolicyDefinition policy) {
PolicyDefinition policyById = getPolicyById(component, policy.getUniqueId());
PolicyDefinition policyDefinition = validateUpdatePolicyBeforeUpdate(policy, policyById, component.getPolicies());
@@ -823,34 +775,33 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
.left()
.bind(p -> updatePolicyOfComponent(component, p));
}*/
-
private PolicyDefinition validateAndUpdatePolicyProperties(Component component, String policyId, PropertyDataDefinition[] properties) {
-
PolicyDefinition policyById = getPolicyById(component, policyId);
policyById = validateUpdatePolicyPropertiesBeforeUpdate(policyById, properties);
return updatePolicyOfComponent(component.getUniqueId(), policyById);
}
private PolicyDefinition updatePolicyOfComponent(String componentId, PolicyDefinition policy) {
- return toscaOperationFacade.updatePolicyOfComponent(componentId, policy, PromoteVersionEnum.MINOR)
- .left()
- .on(ce->componentExceptionPolicyDefinition(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(ce))));
+ return toscaOperationFacade.updatePolicyOfComponent(componentId, policy, PromoteVersionEnum.MINOR).left()
+ .on(ce -> componentExceptionPolicyDefinition(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(ce))));
}
private PolicyDefinition validateUpdatePolicyPropertiesBeforeUpdate(PolicyDefinition policy, PropertyDataDefinition[] newProperties) {
if (CollectionUtils.isEmpty(policy.getProperties())) {
- log.error("#validateUpdatePolicyPropertiesBeforeUpdate - failed to update properites of the policy. Properties were not found on the policy. ");
+ log.error(
+ "#validateUpdatePolicyPropertiesBeforeUpdate - failed to update properites of the policy. Properties were not found on the policy. ");
throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND);
}
return updatePropertyValues(policy, newProperties);
}
private PolicyDefinition updatePropertyValues(PolicyDefinition policy, PropertyDataDefinition[] newProperties) {
-
- Map<String, PropertyDataDefinition> oldProperties = policy.getProperties().stream().collect(toMap(PropertyDataDefinition::getName, Function.identity()));
+ Map<String, PropertyDataDefinition> oldProperties = policy.getProperties().stream()
+ .collect(toMap(PropertyDataDefinition::getName, Function.identity()));
for (PropertyDataDefinition newProperty : newProperties) {
if (!oldProperties.containsKey(newProperty.getName())) {
- log.error("#updatePropertyValues - failed to update properites of the policy {}. Properties were not found on the policy. ", policy.getName());
+ log.error("#updatePropertyValues - failed to update properites of the policy {}. Properties were not found on the policy. ",
+ policy.getName());
throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, newProperty.getName());
}
String newPropertyValueEither = updateInputPropertyObjectValue(newProperty);
@@ -865,10 +816,11 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
}
private PolicyDefinition updatePolicyOfComponent(Component component, PolicyDefinition policy) {
-
- Either<PolicyDefinition, StorageOperationStatus> updatePolicyRes = toscaOperationFacade.updatePolicyOfComponent(component.getUniqueId(), policy, PromoteVersionEnum.MINOR);
+ Either<PolicyDefinition, StorageOperationStatus> updatePolicyRes = toscaOperationFacade
+ .updatePolicyOfComponent(component.getUniqueId(), policy, PromoteVersionEnum.MINOR);
if (updatePolicyRes.isRight()) {
- log.error("#updatePolicyOfComponent - failed to update policy {} of the component {}. The status is {}. ", policy.getUniqueId(), component.getName(), updatePolicyRes.right().value());
+ log.error("#updatePolicyOfComponent - failed to update policy {} of the component {}. The status is {}. ", policy.getUniqueId(),
+ component.getName(), updatePolicyRes.right().value());
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(updatePolicyRes.right().value()));
} else {
log.trace("#updatePolicyOfComponent - the policy with the name {} was updated. ", updatePolicyRes.left().value().getName());
@@ -879,7 +831,8 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
private PolicyDefinition removePolicyFromComponent(Component component, PolicyDefinition policy) {
StorageOperationStatus updatePolicyStatus = toscaOperationFacade.removePolicyFromComponent(component.getUniqueId(), policy.getUniqueId());
if (updatePolicyStatus != StorageOperationStatus.OK) {
- log.error("#removePolicyFromComponent - failed to remove policy {} from the component {}. The status is {}. ", policy.getUniqueId(), component.getName(), updatePolicyStatus);
+ log.error("#removePolicyFromComponent - failed to remove policy {} from the component {}. The status is {}. ", policy.getUniqueId(),
+ component.getName(), updatePolicyStatus);
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(updatePolicyStatus));
} else {
log.trace("#removePolicyFromComponent - the policy with the name {} was deleted. ", updatePolicyStatus);
@@ -887,10 +840,11 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
}
}
- private PolicyDefinition validateUpdatePolicyBeforeUpdate(PolicyDefinition recievedPolicy, PolicyDefinition oldPolicy, Map<String, PolicyDefinition> policies) {
-
- Either<PolicyDefinition, ActionStatus> policyDefinitionActionStatusEither = validatePolicyFields(recievedPolicy, new PolicyDefinition(oldPolicy), policies);
- if(policyDefinitionActionStatusEither.isRight()){
+ private PolicyDefinition validateUpdatePolicyBeforeUpdate(PolicyDefinition recievedPolicy, PolicyDefinition oldPolicy,
+ Map<String, PolicyDefinition> policies) {
+ Either<PolicyDefinition, ActionStatus> policyDefinitionActionStatusEither = validatePolicyFields(recievedPolicy,
+ new PolicyDefinition(oldPolicy), policies);
+ if (policyDefinitionActionStatusEither.isRight()) {
throw new ByActionStatusComponentException(policyDefinitionActionStatusEither.right().value(), recievedPolicy.getName());
}
return policyDefinitionActionStatusEither.left().value();
@@ -901,13 +855,12 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
.right()
.bind(r -> Either.right(componentsUtils.getResponseFormat(r, recievedPolicy.getName())));
}*/
-
- private PolicyDefinition updateTargets(String componentId, PolicyDefinition policy, Map<PolicyTargetType, List<String>> targets, String policyId) {
+ private PolicyDefinition updateTargets(String componentId, PolicyDefinition policy, Map<PolicyTargetType, List<String>> targets,
+ String policyId) {
if (policy == null) {
throw new ByActionStatusComponentException(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER, policyId, componentId);
}
PolicyDefinition updatedPolicy = setPolicyTargets(policy, targets);
return updatePolicyOfComponent(componentId, updatedPolicy);
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java
index b8541f18f2..6070b9ab37 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,9 +17,13 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
+import static java.util.Collections.emptySet;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
import org.openecomp.sdc.be.components.validation.UserValidations;
@@ -33,12 +37,6 @@ import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import static java.util.Collections.emptySet;
-
@Component
public class PolicyTypeBusinessLogic {
@@ -47,7 +45,8 @@ public class PolicyTypeBusinessLogic {
private ComponentsUtils componentsUtils;
private UserValidations userValidations;
- public PolicyTypeBusinessLogic(PolicyTypeOperation policyTypeOperation, JanusGraphDao janusGraphDao, ComponentsUtils componentsUtils, UserValidations userValidations) {
+ public PolicyTypeBusinessLogic(PolicyTypeOperation policyTypeOperation, JanusGraphDao janusGraphDao, ComponentsUtils componentsUtils,
+ UserValidations userValidations) {
this.policyTypeOperation = policyTypeOperation;
this.janusGraphDao = janusGraphDao;
this.componentsUtils = componentsUtils;
@@ -62,16 +61,15 @@ public class PolicyTypeBusinessLogic {
}
public PolicyTypeDefinition getLatestPolicyTypeByType(String policyTypeName) {
- return policyTypeOperation.getLatestPolicyTypeByType(policyTypeName)
- .left()
- .on(e -> failOnPolicyType(e, policyTypeName));
+ return policyTypeOperation.getLatestPolicyTypeByType(policyTypeName).left().on(e -> failOnPolicyType(e, policyTypeName));
}
public Set<String> getExcludedPolicyTypes(String internalComponentType) {
if (StringUtils.isEmpty(internalComponentType)) {
return emptySet();
}
- Map<String, Set<String>> excludedPolicyTypesMapping = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping();
+ Map<String, Set<String>> excludedPolicyTypesMapping = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getExcludedPolicyTypesMapping();
Set<String> excludedTypes = excludedPolicyTypesMapping.get(internalComponentType);
return excludedTypes == null ? emptySet() : excludedTypes;
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java
index 377feb470d..2b9f58ce51 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,10 +17,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Consumer;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum;
import org.openecomp.sdc.be.components.impl.model.ToscaTypeImportData;
@@ -38,10 +40,6 @@ import org.openecomp.sdc.be.utils.TypeUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.stereotype.Component;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Consumer;
-
@Component("policyTypeImportManager")
public class PolicyTypeImportManager {
@@ -52,9 +50,9 @@ public class PolicyTypeImportManager {
private final CommonImportManager commonImportManager;
private final GroupTypeOperation groupTypeOperation;
- public PolicyTypeImportManager(IPolicyTypeOperation policyTypeOperation, ComponentsUtils componentsUtils,
- GroupOperation groupOperation, ToscaOperationFacade toscaOperationFacade,
- CommonImportManager commonImportManager, GroupTypeOperation groupTypeOperation) {
+ public PolicyTypeImportManager(IPolicyTypeOperation policyTypeOperation, ComponentsUtils componentsUtils, GroupOperation groupOperation,
+ ToscaOperationFacade toscaOperationFacade, CommonImportManager commonImportManager,
+ GroupTypeOperation groupTypeOperation) {
this.policyTypeOperation = policyTypeOperation;
this.componentsUtils = componentsUtils;
this.groupOperation = groupOperation;
@@ -71,12 +69,15 @@ public class PolicyTypeImportManager {
return commonImportManager.createElementTypesFromYml(policyTypesYml, this::createPolicyType);
}
- private Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat> upsertPolicyTypesByDao(List<PolicyTypeDefinition> policyTypesToCreate) {
- return commonImportManager.createElementTypesByDao(policyTypesToCreate, this::validatePolicyType, policyType -> new ImmutablePair<>(ElementTypeEnum.POLICY_TYPE, policyType.getType()),
- policyTypeOperation::getLatestPolicyTypeByType, policyTypeOperation::addPolicyType, this::updatePolicyType);
+ private Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat> upsertPolicyTypesByDao(
+ List<PolicyTypeDefinition> policyTypesToCreate) {
+ return commonImportManager.createElementTypesByDao(policyTypesToCreate, this::validatePolicyType,
+ policyType -> new ImmutablePair<>(ElementTypeEnum.POLICY_TYPE, policyType.getType()), policyTypeOperation::getLatestPolicyTypeByType,
+ policyTypeOperation::addPolicyType, this::updatePolicyType);
}
- private Either<PolicyTypeDefinition, StorageOperationStatus> updatePolicyType(PolicyTypeDefinition newPolicyType, PolicyTypeDefinition oldPolicyType) {
+ private Either<PolicyTypeDefinition, StorageOperationStatus> updatePolicyType(PolicyTypeDefinition newPolicyType,
+ PolicyTypeDefinition oldPolicyType) {
if (PolicyTypeImportUtils.isPolicyTypesEquals(newPolicyType, oldPolicyType)) {
return policyTypeAlreadyExists();
}
@@ -96,35 +97,29 @@ public class PolicyTypeImportManager {
}
if (result.isLeft()) {
for (String targetId : policyType.getTargets()) {
- boolean isValid = toscaOperationFacade.getLatestByToscaResourceName(targetId).isLeft();
-
- if (!isValid) { // check if it is a groupType
- final Either<GroupTypeDefinition, StorageOperationStatus> groupTypeFound = groupTypeOperation
- .getLatestGroupTypeByType(targetId, false);
- isValid = groupTypeFound.isLeft() && !groupTypeFound.left().value().isEmpty();
- }
-
- if (!isValid) {
- isValid = groupOperation.isGroupExist(targetId, false);
- }
-
- if (!isValid) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TARGETS_NON_VALID, policyType.getType(), targetId);
- result = Either.right(responseFormat);
- break;
- }
+ boolean isValid = toscaOperationFacade.getLatestByToscaResourceName(targetId).isLeft();
+ if (!isValid) { // check if it is a groupType
+ final Either<GroupTypeDefinition, StorageOperationStatus> groupTypeFound = groupTypeOperation
+ .getLatestGroupTypeByType(targetId, false);
+ isValid = groupTypeFound.isLeft() && !groupTypeFound.left().value().isEmpty();
+ }
+ if (!isValid) {
+ isValid = groupOperation.isGroupExist(targetId, false);
+ }
+ if (!isValid) {
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.TARGETS_NON_VALID, policyType.getType(), targetId);
+ result = Either.right(responseFormat);
+ break;
}
}
}
-
-
+ }
return result;
}
private PolicyTypeDefinition createPolicyType(String groupTypeName, Map<String, Object> toscaJson) {
-
PolicyTypeDefinition policyType = new PolicyTypeDefinition();
-
if (toscaJson != null) {
// Description
final Consumer<String> descriptionSetter = policyType::setDescription;
@@ -138,16 +133,12 @@ public class PolicyTypeImportManager {
final Consumer<Map<String, String>> metadataSetter = policyType::setMetadata;
commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.METADATA.getElementName(), metadataSetter);
// Targets
- final Consumer <List<String>> targetsSetter = policyType::setTargets;
+ final Consumer<List<String>> targetsSetter = policyType::setTargets;
commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.TARGETS.getElementName(), targetsSetter);
-
policyType.setType(groupTypeName);
-
policyType.setHighestVersion(true);
-
policyType.setVersion(TypeUtils.getFirstCertifiedVersionVersion());
}
return policyType;
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java
index c643d9f937..aca253682c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,10 +19,16 @@
* Modifications copyright (c) 2019 Nokia
* ================================================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.components.validation.component.ComponentContactIdValidator;
@@ -61,14 +67,6 @@ import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.stream.Collectors;
-
@org.springframework.stereotype.Component("productBusinessLogic")
public class ProductBusinessLogic extends ComponentBusinessLogic {
@@ -80,37 +78,24 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
private static List<Role> creationRoles;
private static List<Role> updateRoles;
private static List<Role> contactsRoles;
-
private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
@Autowired
- public ProductBusinessLogic(IElementOperation elementDao,
- IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation,
- IGroupTypeOperation groupTypeOperation,
- GroupBusinessLogic groupBusinessLogic,
- InterfaceOperation interfaceOperation,
- InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
- ArtifactsBusinessLogic artifactsBusinessLogic,
- ComponentInstanceBusinessLogic componentInstanceBusinessLogic,
- ArtifactsOperations artifactToscaOperation,
- ComponentContactIdValidator componentContactIdValidator,
- ComponentNameValidator componentNameValidator,
- ComponentTagsValidator componentTagsValidator,
- ComponentValidator componentValidator,
- ComponentIconValidator componentIconValidator,
- ComponentProjectCodeValidator componentProjectCodeValidator,
- ComponentDescriptionValidator componentDescriptionValidator){
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic,
- interfaceOperation, interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation,
- componentContactIdValidator, componentNameValidator, componentTagsValidator, componentValidator,
- componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator);
+ public ProductBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+ IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic, InterfaceOperation interfaceOperation,
+ InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsBusinessLogic artifactsBusinessLogic,
+ ComponentInstanceBusinessLogic componentInstanceBusinessLogic, ArtifactsOperations artifactToscaOperation,
+ ComponentContactIdValidator componentContactIdValidator, ComponentNameValidator componentNameValidator,
+ ComponentTagsValidator componentTagsValidator, ComponentValidator componentValidator,
+ ComponentIconValidator componentIconValidator, ComponentProjectCodeValidator componentProjectCodeValidator,
+ ComponentDescriptionValidator componentDescriptionValidator) {
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic, interfaceOperation,
+ interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, componentContactIdValidator, componentNameValidator,
+ componentTagsValidator, componentValidator, componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator);
this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
-
creationRoles = new ArrayList<>();
updateRoles = new ArrayList<>();
contactsRoles = new ArrayList<>();
-
// only PM is allowed to create/update products
creationRoles.add(Role.PRODUCT_MANAGER);
updateRoles.add(Role.PRODUCT_MANAGER);
@@ -121,61 +106,49 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
public Either<Product, ResponseFormat> createProduct(Product product, User user) {
AuditingActionEnum actionEnum = AuditingActionEnum.CREATE_RESOURCE;
ComponentTypeEnum typeEnum = ComponentTypeEnum.PRODUCT;
-
// validate user - should be first to get the maximum auditing info in
+
// case of subsequent failures
log.debug("get user from DB");
user = validateUser(user, CREATE_PRODUCT, product, actionEnum, false);
// validate user role
validateUserRole(user, product, creationRoles, actionEnum, null);
-
if (product == null) {
log.debug("Invalid product json. Check product servlet log for createProduct entry params");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, typeEnum);
return Either.right(responseFormat);
}
-
// warn about non-updatable fields
checkUnupdatableProductFields(product);
-
Either<Product, ResponseFormat> validateProductResponse = validateProductBeforeCreate(product, user, actionEnum);
if (validateProductResponse.isRight()) {
return Either.right(validateProductResponse.right().value());
}
-
log.debug("send product {} to dao for create", product.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
-
Either<Boolean, ResponseFormat> lockResult = lockComponentByName(product.getSystemName(), product, CREATE_PRODUCT);
if (lockResult.isRight()) {
ResponseFormat responseFormat = lockResult.right().value();
componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
return Either.right(responseFormat);
}
-
log.debug("Product name locked is {}, status = {}", product.getSystemName(), lockResult);
-
try {
Either<Product, StorageOperationStatus> createProductEither = toscaOperationFacade.createToscaComponent(product);
-
if (createProductEither.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(createProductEither.right().value()), product, typeEnum);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(createProductEither.right().value()), product, typeEnum);
componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, typeEnum);
return Either.right(responseFormat);
}
-
log.debug("Product created successfully");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, typeEnum);
-
Product createdProduct = createProductEither.left().value();
-
return Either.left(createdProduct);
-
} finally {
graphLockOperation.unlockComponentByName(product.getSystemName(), product.getUniqueId(), NodeTypeEnum.Product);
}
-
}
private void checkUnupdatableProductFields(Product product) {
@@ -186,60 +159,53 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
}
private Either<Product, ResponseFormat> validateProductBeforeCreate(Product product, User user, AuditingActionEnum actionEnum) {
-
Either<Boolean, ResponseFormat> validateProductFields = validateProductFieldsBeforeCreate(user, product, actionEnum);
if (validateProductFields.isRight()) {
return Either.right(validateProductFields.right().value());
}
-
if (product.getIsActive() == null) {
log.debug("no isActive value was provided, setting to default: false");
product.setIsActive(false);
}
-
product.setCreatorUserId(user.getUserId());
-
// enrich object
log.debug("enrich product with version and state");
product.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
product.setVersion(INITIAL_VERSION);
-
// Generate invariant UUID - must be here and not in operation since it
+
// should stay constant during clone
String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
product.setInvariantUUID(invariantUUID);
-
return Either.left(product);
}
private Either<Boolean, ResponseFormat> validateProductFieldsBeforeCreate(User user, Product product, AuditingActionEnum actionEnum) {
-
// To be removed in 1607
+
// See below
String oldName = product.getName();
-
Either<Boolean, ResponseFormat> componentNameValidation = validateProductNameAndCleanup(user, product, actionEnum);
if (componentNameValidation.isRight()) {
return componentNameValidation;
}
-
try {
componentNameValidator.validateComponentNameUnique(user, product, actionEnum);
} catch (ComponentException exp) {
return Either.right(exp.getResponseFormat());
}
-
// To be removed in 1607 and replaced with generic
+
// validateTagsListAndRemoveDuplicates()
+
// See comments on the validateTagsListAndRemoveDuplicates(user,
+
// product, oldName, actionEnum) function
Either<Boolean, ResponseFormat> tagsValidation = validateTagsListAndRemoveDuplicates(user, product, oldName, actionEnum);
if (tagsValidation.isRight()) {
return tagsValidation;
}
-
componentTagsValidator.validateAndCorrectField(user, product, actionEnum);
-
try {
componentProjectCodeValidator.validateAndCorrectField(user, product, actionEnum);
} catch (ComponentException exp) {
@@ -249,38 +215,32 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
if (categoryValidation.isRight()) {
return categoryValidation;
}
-
Either<Boolean, ResponseFormat> contactsListValidation = validateAndUpdateProductContactsList(user, product, actionEnum);
if (contactsListValidation.isRight()) {
return contactsListValidation;
}
-
Either<Boolean, ResponseFormat> productFullNameValidation = validateProductFullNameAndCleanup(user, product, actionEnum);
if (productFullNameValidation.isRight()) {
return productFullNameValidation;
}
-
componentDescriptionValidator.validateAndCorrectField(user, product, actionEnum);
-
return Either.left(true);
}
public Either<Map<String, Boolean>, ResponseFormat> validateProductNameExists(String productName, String userId) {
-
validateUserExists(userId);
- Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(productName, null, ComponentTypeEnum.PRODUCT);
+ Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
+ .validateComponentNameUniqueness(productName, null, ComponentTypeEnum.PRODUCT);
// DE242223
janusGraphDao.commit();
-
if (dataModelResponse.isLeft()) {
Map<String, Boolean> result = new HashMap<>();
result.put("isValid", dataModelResponse.left().value());
log.debug("validation was successfully performed.");
return Either.left(result);
}
-
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
-
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
return Either.right(responseFormat);
}
@@ -292,7 +252,6 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
return Either.right(responseFormat);
}
-
boolean isProductCreatorInContacts = false;
String modifierUserId = user.getUserId();
for (String contact : contacts) {
@@ -304,35 +263,30 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
}
if (!ValidationUtils.validateContactId(contact)) {
log.debug("Product contacts has invalid userId {} for product {}", contact, product.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.PRODUCT.getValue());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.PRODUCT.getValue());
componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
return Either.right(responseFormat);
}
-
User contactUser;
- try{
+ try {
contactUser = validateUserExists(contact);
validateUserRole(contactUser, contactsRoles);
- } catch(ByActionStatusComponentException e){
+ } catch (ByActionStatusComponentException e) {
log.debug("Cannot set contact with userId {} as product contact, error: {}", contact, e.getActionStatus());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PRODUCT_CONTACT, contact);
componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
throw new ByActionStatusComponentException(e.getActionStatus(), e.getParams());
}
}
-
if (!isProductCreatorInContacts) {
log.debug("modifier userId {} not found in product contacts - adding it", modifierUserId);
contacts.add(modifierUserId);
}
-
// passed - setting all contacts userIds to lowercase
- List<String> tempContacts = contacts.stream()
- .map(String::toLowerCase)
- .collect(Collectors.toList());
+ List<String> tempContacts = contacts.stream().map(String::toLowerCase).collect(Collectors.toList());
ValidationUtils.removeDuplicateFromList(tempContacts);
product.setContacts(tempContacts);
-
return Either.left(true);
}
@@ -349,7 +303,8 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
if (!ValidationUtils.validateStringNotEmpty(catName)) {
// error missing cat name
log.debug("Missing category name for product: {}", product.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.PRODUCT.getValue());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.PRODUCT.getValue());
componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
return Either.right(responseFormat);
}
@@ -372,7 +327,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
// error missing sub cat name for cat
log.debug("Missing or empty sub-category for category {} in product {}", catName, product.getName());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
- componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
return Either.right(responseFormat);
}
Set<String> subcatEntry = catEntry.get(subCatName);
@@ -385,7 +340,8 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
String groupName = group.getName();
if (!ValidationUtils.validateStringNotEmpty(groupName)) {
// error missing grouping for sub cat name and cat
- log.debug("Missing or empty groupng name for sub-category: {} for categor: {} in product: {}", subCatName, catName, product.getName());
+ log.debug("Missing or empty groupng name for sub-category: {} for categor: {} in product: {}", subCatName, catName,
+ product.getName());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
return Either.right(responseFormat);
@@ -398,9 +354,9 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
}
}
} // for end of checking duplicated
- // validate existence
- Either<List<CategoryDefinition>, ActionStatus> allProductCategories = elementDao.getAllProductCategories();
+ // validate existence
+ Either<List<CategoryDefinition>, ActionStatus> allProductCategories = elementDao.getAllProductCategories();
if (allProductCategories.isRight()) {
log.debug("No product categories {}", allProductCategories.right().value());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(allProductCategories.right().value());
@@ -409,9 +365,9 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
}
boolean catExist;
// convert non-duplicated to data modeling format and update in the
+
// input object
List<CategoryDefinition> newCatList = new ArrayList<>();
-
// over all categories from request
for (Map.Entry<String, Map<String, Set<String>>> entry : nonDuplicatedCategories.entrySet()) {
catExist = false;
@@ -426,7 +382,6 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
// copy data
categoryDefinition = new CategoryDefinition(catInDb);
SubCategoryDefinition subCategory = null;
-
Map<String, Set<String>> subcats = entry.getValue();
for (Map.Entry<String, Set<String>> subcat : subcats.entrySet()) {
subcatExist = false;
@@ -453,9 +408,13 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
}
if (!groupExist) {
// error grouping isn't defined
+
// in JanusGraph
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.GROUPING.getValue(), group);
- componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.GROUPING.getValue(),
+ group);
+ componentsUtils
+ .auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
return Either.right(responseFormat);
}
subCategory.addGrouping(groupingDefinition);
@@ -465,7 +424,9 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
}
if (!subcatExist) {
// error sub category isn't defined in JanusGraph
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.SUBCATEGORY.getValue(), subcat.getKey());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.SUBCATEGORY.getValue(),
+ subcat.getKey());
componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
return Either.right(responseFormat);
}
@@ -476,7 +437,8 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
}
if (!catExist) {
// error category isn't defined in JanusGraph
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.CATEGORY.getValue(), entry.getKey());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.CATEGORY.getValue(), entry.getKey());
componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
return Either.right(responseFormat);
}
@@ -490,16 +452,15 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
String ecompErrorContext = "Get product";
validateUserNotEmpty(user, ecompErrorContext);
validateUserExists(user);
-
Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(productId);
-
if (storageStatus.isRight()) {
log.debug("failed to get resource by id {}", productId);
if (storageStatus.right().value() == StorageOperationStatus.NOT_FOUND) {
// TODO check error
return Either.right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.getValue()));
} else {
- return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
+ return Either.right(
+ componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
}
}
return Either.left(storageStatus.left().value());
@@ -509,12 +470,11 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
String ecompErrorContext = "Delete product";
validateUserNotEmpty(user, ecompErrorContext);
validateUserExists(user);
-
Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.deleteToscaComponent(productId);
-
if (storageStatus.isRight()) {
log.debug("failed to delete resource by id {}", productId);
- return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
+ return Either
+ .right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
}
return Either.left(storageStatus.left().value());
}
@@ -522,28 +482,27 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
private Either<Boolean, ResponseFormat> validateProductFullNameAndCleanup(User user, Product product, AuditingActionEnum actionEnum) {
String fullName = product.getFullName();
if (!ValidationUtils.validateStringNotEmpty(fullName)) {
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME);
+ ResponseFormat errorResponse = componentsUtils
+ .getResponseFormat(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME);
componentsUtils.auditComponentAdmin(errorResponse, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
return Either.right(errorResponse);
}
-
fullName = ValidationUtils.removeNoneUtf8Chars(fullName);
fullName = ValidationUtils.removeHtmlTags(fullName);
fullName = ValidationUtils.normaliseWhitespace(fullName);
fullName = ValidationUtils.stripOctets(fullName);
-
if (!ValidationUtils.validateProductFullNameLength(fullName)) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME);
componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
return Either.right(responseFormat);
}
-
if (!ValidationUtils.validateIsEnglish(fullName)) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME);
componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
return Either.right(responseFormat);
}
-
product.setFullName(fullName);
return Either.left(true);
}
@@ -551,49 +510,55 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
private Either<Boolean, ResponseFormat> validateProductNameAndCleanup(User user, Product product, AuditingActionEnum actionEnum) {
String name = product.getName();
if (!ValidationUtils.validateStringNotEmpty(name)) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME);
componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
return Either.right(responseFormat);
}
-
// Product name is required to have same validation and normalization as
+
// category
if (!ValidationUtils.validateCategoryDisplayNameFormat(name)) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, ComponentTypeEnum.PRODUCT.getValue(),
+ PRODUCT_ABBREVIATED_NAME);
componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
return Either.right(responseFormat);
}
-
String normalizedName4Display = ValidationUtils.normalizeCategoryName4Display(name);
-
if (!ValidationUtils.validateCategoryDisplayNameLength(normalizedName4Display)) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, ComponentTypeEnum.PRODUCT.getValue(),
+ PRODUCT_ABBREVIATED_NAME);
componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
return Either.right(responseFormat);
}
-
product.setName(normalizedName4Display);
String normalizedName4Uniqueness = ValidationUtils.normaliseComponentName(normalizedName4Display);
product.setNormalizedName(normalizedName4Uniqueness);
-
return Either.left(true);
}
-
// This is a workaround for a current tag--->product name behaviour, which
+
// will be changed in 1607.
+
// It was agreed with Ella on 23/2/16 that the tag validation of product
+
// will be made against the old product name (before normalization),
+
// and in 1607 US will be defined where UI will no longer pass tag of
+
// component name, and BE will add it by itself after all needed
+
// normalizations.
- private Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Product product, String oldProductName, AuditingActionEnum actionEnum) {
+ private Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Product product, String oldProductName,
+ AuditingActionEnum actionEnum) {
componentTagsValidator.validateAndCorrectField(user, product, actionEnum);
return Either.left(true);
}
@Override
public void setDeploymentArtifactsPlaceHolder(org.openecomp.sdc.be.model.Component component, User user) {
-
}
public Either<Product, ResponseFormat> updateProductMetadata(String productId, Product updatedProduct, User user) {
@@ -606,28 +571,25 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
return Either.right(responseFormat);
}
-
Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(productId);
if (storageStatus.isRight()) {
if (storageStatus.right().value() == StorageOperationStatus.NOT_FOUND) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.name().toLowerCase()));
+ return Either
+ .right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.name().toLowerCase()));
}
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), typeEnum), ""));
+ return Either
+ .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), typeEnum), ""));
}
-
Product currentProduct = storageStatus.left().value();
-
if (!ComponentValidationUtils.canWorkOnComponent(productId, toscaOperationFacade, user.getUserId())) {
- log.info("Restricted operation for user: {}, on product: {}" , user.getUserId(), currentProduct.getCreatorUserId());
+ log.info("Restricted operation for user: {}, on product: {}", user.getUserId(), currentProduct.getCreatorUserId());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
-
Either<Product, ResponseFormat> validationRsponse = validateAndUpdateProductMetadata(user, currentProduct, updatedProduct);
if (validationRsponse.isRight()) {
log.info("product update metadata: validations field.");
return validationRsponse;
}
-
Product productToUpdate = validationRsponse.left().value();
// lock resource
lockComponent(currentProduct.getUniqueId(), currentProduct, "Update Product Metadata");
@@ -646,69 +608,57 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
}
private Either<Product, ResponseFormat> validateAndUpdateProductMetadata(User user, Product currentProduct, Product updatedProduct) {
-
boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentProduct.getVersion());
Either<Boolean, ResponseFormat> response = validateAndUpdateProductName(user, currentProduct, updatedProduct);
if (response.isRight()) {
ResponseFormat errorResponse = response.right().value();
return Either.right(errorResponse);
}
-
response = validateAndUpdateFullName(user, currentProduct, updatedProduct);
if (response.isRight()) {
ResponseFormat errorResponse = response.right().value();
return Either.right(errorResponse);
}
-
response = validateAndUpdateDescription(user, currentProduct, updatedProduct, null);
if (response.isRight()) {
ResponseFormat errorResponse = response.right().value();
return Either.right(errorResponse);
}
-
response = validateAndUpdateCategory(user, currentProduct, updatedProduct);
if (response.isRight()) {
ResponseFormat errorResponse = response.right().value();
return Either.right(errorResponse);
}
-
response = validateAndUpdateContactList(user, currentProduct, updatedProduct);
if (response.isRight()) {
ResponseFormat errorResponse = response.right().value();
return Either.right(errorResponse);
}
-
response = validateAndUpdateTags(user, currentProduct, updatedProduct);
if (response.isRight()) {
ResponseFormat errorResponse = response.right().value();
return Either.right(errorResponse);
}
-
response = validateAndUpdateProjectCode(user, currentProduct, updatedProduct);
if (response.isRight()) {
ResponseFormat errorResponse = response.right().value();
return Either.right(errorResponse);
}
-
if (updatedProduct.getIsActive() != null) {
currentProduct.setIsActive(updatedProduct.getIsActive());
}
-
response = validateAndUpdateIcon(user, currentProduct, updatedProduct, hasBeenCertified);
if (response.isRight()) {
ResponseFormat errorResponse = response.right().value();
return Either.right(errorResponse);
}
-
String currentInvariantUuid = currentProduct.getInvariantUUID();
String updatedInvariantUuid = updatedProduct.getInvariantUUID();
-
if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
log.warn("Product invariant UUID is automatically set and cannot be updated");
updatedProduct.setInvariantUUID(currentInvariantUuid);
}
return Either.left(currentProduct);
-
}
private Either<Boolean, ResponseFormat> validateAndUpdateProductName(User user, Product currentProduct, Product updatedProduct) {
@@ -731,9 +681,11 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
currentProduct.setName(updatedProductName);
tags = updatedProductName;
updatedProductName = ValidationUtils.normalizeCategoryName4Display(updatedProductName);
- currentProduct.getComponentMetadataDefinition().getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(updatedProductName));
+ currentProduct.getComponentMetadataDefinition().getMetadataDataDefinition()
+ .setNormalizedName(ValidationUtils.normaliseComponentName(updatedProductName));
List<String> updatedTags = updatedProduct.getTags();
// As discussed with Ella currently (1604) we are not removing
+
// the old name from tags.
if (updatedTags == null) {
updatedTags = currentProduct.getTags();
@@ -759,13 +711,11 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
}
private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Product currentProduct, Product updatedProduct) {
-
Either<Boolean, ResponseFormat> validateCategoryResponse = validateGrouping(user, updatedProduct, null);
if (validateCategoryResponse.isRight()) {
ResponseFormat errorResponse = validateCategoryResponse.right().value();
return Either.right(errorResponse);
}
-
List<CategoryDefinition> categoryUpdated = updatedProduct.getCategories();
if (categoryUpdated != null) {
currentProduct.setCategories(categoryUpdated);
@@ -794,7 +744,8 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
List<String> tagsCurrent = currentProduct.getTags();
if (tagsUpdated != null) {
if (!(tagsCurrent.containsAll(tagsUpdated) && tagsUpdated.containsAll(tagsCurrent))) {
- Either<Boolean, ResponseFormat> validatResponse = validateTagsListAndRemoveDuplicates(user, updatedProduct, currentProduct.getName(), null);
+ Either<Boolean, ResponseFormat> validatResponse = validateTagsListAndRemoveDuplicates(user, updatedProduct, currentProduct.getName(),
+ null);
if (validatResponse.isRight()) {
ResponseFormat errorRespons = validatResponse.right().value();
return Either.right(errorRespons);
@@ -813,10 +764,13 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
public Either<Product, ResponseFormat> getProductByNameAndVersion(String productName, String productVersion, String userId) {
validateUserExists(userId);
- Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.PRODUCT, productName, productVersion);
+ Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade
+ .getComponentByNameAndVersion(ComponentTypeEnum.PRODUCT, productName, productVersion);
if (storageStatus.isRight()) {
log.debug("failed to get service by name {} and version {}", productName, productVersion);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.PRODUCT), productName));
+ return Either.right(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.PRODUCT),
+ productName));
}
Product product = storageStatus.left().value();
return Either.left(product);
@@ -834,9 +788,8 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
@Override
public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId,
- List<String> dataParamsToReturn) {
+ List<String> dataParamsToReturn) {
// TODO Auto-generated method stub
return null;
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java
index 66a6a27e16..baab08d0cd 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java
@@ -17,11 +17,15 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import com.google.gson.JsonElement;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
@@ -59,32 +63,19 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-
-
@org.springframework.stereotype.Component("propertyBusinessLogic")
public class PropertyBusinessLogic extends BaseBusinessLogic {
private static final String CREATE_PROPERTY = "CreateProperty";
-
private static final Logger log = Logger.getLogger(PropertyBusinessLogic.class);
-
private static final String EMPTY_VALUE = null;
@Autowired
- public PropertyBusinessLogic(IElementOperation elementDao,
- IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation,
- IGroupTypeOperation groupTypeOperation,
- InterfaceOperation interfaceOperation,
- InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
- ArtifactsOperations artifactToscaOperation) {
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
- interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+ public PropertyBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+ IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
+ InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+ artifactToscaOperation);
}
public Map<String, DataTypeDefinition> getAllDataTypes() {
@@ -100,54 +91,39 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
* @param userId
* @return either properties or response format
*/
-
- public Either<EntryData<String, PropertyDefinition>, ResponseFormat> addPropertyToComponent(String componentId,
- String propertyName,
+ public Either<EntryData<String, PropertyDefinition>, ResponseFormat> addPropertyToComponent(String componentId, String propertyName,
PropertyDefinition newPropertyDefinition,
String userId) {
Either<EntryData<String, PropertyDefinition>, ResponseFormat> result = null;
-
validateUserExists(userId);
-
- Either<Component, StorageOperationStatus> serviceElement =
- toscaOperationFacade.getToscaElement(componentId);
+ Either<Component, StorageOperationStatus> serviceElement = toscaOperationFacade.getToscaElement(componentId);
if (serviceElement.isRight()) {
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
return result;
}
Component component = serviceElement.left().value();
NodeTypeEnum nodeType = component.getComponentType().getNodeType();
- StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, nodeType );
+ StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, nodeType);
if (!lockResult.equals(StorageOperationStatus.OK)) {
BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, nodeType.name().toLowerCase(), componentId);
log.info("Failed to lock component {}. Error - {}", componentId, lockResult);
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
return result;
}
-
try {
if (!ComponentValidationUtils.canWorkOnComponent(component, userId)) {
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
return result;
}
-
List<PropertyDefinition> properties = component.getProperties();
-
- if(CollectionUtils.isEmpty(properties)) {
+ if (CollectionUtils.isEmpty(properties)) {
properties = new ArrayList<>();
}
-
- if(isPropertyExistInComponent(properties, propertyName)) {
-
- result =
- Either.right(componentsUtils.getResponseFormat(ActionStatus
- .PROPERTY_ALREADY_EXIST, propertyName));
+ if (isPropertyExistInComponent(properties, propertyName)) {
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, propertyName));
return result;
-
} else {
-
Map<String, DataTypeDefinition> allDataTypes = getAllDataTypes(applicationDataTypeCache);
-
// validate property default values
Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newPropertyDefinition, allDataTypes);
if (defaultValuesValidation.isRight()) {
@@ -170,21 +146,16 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
}
String convertedValue = null;
if (newPropertyDefinition.getDefaultValue() != null) {
- convertedValue = converter.convert(
- newPropertyDefinition.getDefaultValue(), innerType, allDataTypes);
+ convertedValue = converter.convert(newPropertyDefinition.getDefaultValue(), innerType, allDataTypes);
newPropertyDefinition.setDefaultValue(convertedValue);
}
}
}
- Either<PropertyDefinition, StorageOperationStatus> addPropertyEither =
- toscaOperationFacade
- .addPropertyToComponent(propertyName, newPropertyDefinition, component);
-
+ Either<PropertyDefinition, StorageOperationStatus> addPropertyEither = toscaOperationFacade
+ .addPropertyToComponent(propertyName, newPropertyDefinition, component);
if (addPropertyEither.isRight()) {
- log.info("Failed to add new property {}. Error - {}", componentId,
- addPropertyEither.right().value());
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus
- .GENERAL_ERROR));
+ log.info("Failed to add new property {}. Error - {}", componentId, addPropertyEither.right().value());
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
return result;
}
}
@@ -200,67 +171,58 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
/**
* Copies a list of properties to a component.
*
- * @param component the component to add the copied properties
+ * @param component the component to add the copied properties
* @param propertiesToCopyList the properties to be copied
* @return the updated component with the copied properties.
* @throws ToscaOperationException when a problem happens during the copy operation
*/
- public Component copyPropertyToComponent(final Component component,
- final List<PropertyDefinition> propertiesToCopyList) throws ToscaOperationException {
+ public Component copyPropertyToComponent(final Component component, final List<PropertyDefinition> propertiesToCopyList)
+ throws ToscaOperationException {
return copyPropertyToComponent(component, propertiesToCopyList, true);
}
/**
* Copies a list of properties to a component.
*
- * @param component the component to add the copied properties
+ * @param component the component to add the copied properties
* @param propertiesToCopyList the properties to be copied
- * @param refreshComponent refresh the component from database after update
- * @return the component refreshed from database if refreshComponent is {@code true}, the same component reference
- * otherwise
+ * @param refreshComponent refresh the component from database after update
+ * @return the component refreshed from database if refreshComponent is {@code true}, the same component reference otherwise
* @throws ToscaOperationException when a problem happens during the copy operation
*/
- public Component copyPropertyToComponent(final Component component,
- final List<PropertyDefinition> propertiesToCopyList,
+ public Component copyPropertyToComponent(final Component component, final List<PropertyDefinition> propertiesToCopyList,
final boolean refreshComponent) throws ToscaOperationException {
if (CollectionUtils.isEmpty(propertiesToCopyList)) {
return component;
}
-
for (final PropertyDefinition propertyDefinition : propertiesToCopyList) {
copyPropertyToComponent(component, propertyDefinition);
}
-
if (refreshComponent) {
return toscaOperationFacade.getToscaElement(component.getUniqueId()).left().value();
}
-
return component;
}
/**
* Copies one property to a component.
*
- * @param component the component to add the copied property
+ * @param component the component to add the copied property
* @param propertyDefinition the property to be copied
* @throws ToscaOperationException when a problem happens during the copy operation
*/
- private void copyPropertyToComponent(final Component component,
- final PropertyDefinition propertyDefinition) throws ToscaOperationException {
+ private void copyPropertyToComponent(final Component component, final PropertyDefinition propertyDefinition) throws ToscaOperationException {
final PropertyDefinition copiedPropertyDefinition = new PropertyDefinition(propertyDefinition);
final String componentId = component.getUniqueId();
final String propertyName = copiedPropertyDefinition.getName();
- copiedPropertyDefinition.setUniqueId(
- UniqueIdBuilder.buildPropertyUniqueId(componentId, propertyName)
- );
+ copiedPropertyDefinition.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(componentId, propertyName));
copiedPropertyDefinition.setParentUniqueId(componentId);
final Either<PropertyDefinition, StorageOperationStatus> operationResult = toscaOperationFacade
.addPropertyToComponent(propertyName, copiedPropertyDefinition, component);
if (operationResult.isRight()) {
- final String error = String.format(
- "Failed to add copied property '%s' to component '%s'. Operation status: '%s'",
- propertyDefinition.getUniqueId(), componentId, operationResult.right().value()
- );
+ final String error = String
+ .format("Failed to add copied property '%s' to component '%s'. Operation status: '%s'", propertyDefinition.getUniqueId(), componentId,
+ operationResult.right().value());
log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, PropertyBusinessLogic.class.getName(), "catalog-be", error);
throw new ToscaOperationException(error, operationResult.right().value());
}
@@ -274,50 +236,40 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
* @param userId
* @return either properties or response format
*/
-
public Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> getComponentProperty(String componentId, String propertyId, String userId) {
-
validateUserExists(userId);
// Get the resource from DB
- Either<Component, StorageOperationStatus> status =
- toscaOperationFacade.getToscaElement(componentId);
+ Either<Component, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(componentId);
if (status.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
}
Component component = status.left().value();
List<PropertyDefinition> properties = component.getProperties();
- if(CollectionUtils.isEmpty(properties)) {
+ if (CollectionUtils.isEmpty(properties)) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, ""));
}
-
- for(PropertyDefinition property : properties) {
- if(property.getUniqueId().equals(propertyId)) {
+ for (PropertyDefinition property : properties) {
+ if (property.getUniqueId().equals(propertyId)) {
return Either.left(new EntryData<>(property.getName(), property));
}
}
return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, ""));
}
-
- public Either<List<PropertyDefinition>, ResponseFormat> getPropertiesList(String componentId,
- String userId) {
+ public Either<List<PropertyDefinition>, ResponseFormat> getPropertiesList(String componentId, String userId) {
validateUserExists(userId);
-
// Get the resource from DB
ComponentParametersView filter = new ComponentParametersView(true);
filter.setIgnoreProperties(false);
- Either<Component, StorageOperationStatus> status =
- toscaOperationFacade.getToscaElement(componentId);
+ Either<Component, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(componentId);
if (status.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
}
Component component = status.left().value();
List<PropertyDefinition> properties = component.getProperties();
-
return Either.left(properties);
}
-
/**
* delete property of component from graph
*
@@ -326,13 +278,10 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
* @param userId
* @return either properties or response format
*/
-
- public Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> deletePropertyFromComponent(String componentId, String propertyId, String userId) {
-
+ public Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> deletePropertyFromComponent(String componentId, String propertyId,
+ String userId) {
Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> result = null;
-
validateUserExists(userId);
-
// Get the resource from DB
Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaElement(componentId);
if (getComponentRes.isRight()) {
@@ -343,46 +292,36 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
NodeTypeEnum nodeType = component.getComponentType().getNodeType();
StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, nodeType);
if (!lockResult.equals(StorageOperationStatus.OK)) {
- BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, nodeType.name().toLowerCase(),
- componentId);
+ BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, nodeType.name().toLowerCase(), componentId);
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
return result;
}
-
try {
// verify that resource is checked-out and the user is the last
+
// updater
if (!ComponentValidationUtils.canWorkOnComponent(component, userId)) {
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
return result;
}
-
// verify property exist in resource
- Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> statusGetProperty =
- getComponentProperty(componentId, propertyId, userId);
+ Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> statusGetProperty = getComponentProperty(componentId, propertyId, userId);
if (statusGetProperty.isRight()) {
result = Either.right(statusGetProperty.right().value());
return result;
}
-
Map.Entry<String, PropertyDefinition> propertyDefinitionEntry = statusGetProperty.left().value();
-
// verify that the property is not used by operation
if (isPropertyUsedByOperation(component, propertyDefinitionEntry.getValue())) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus
- .PROPERTY_USED_BY_OPERATION));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_USED_BY_OPERATION));
}
-
- StorageOperationStatus status =
- toscaOperationFacade.deletePropertyOfComponent(component, propertyDefinitionEntry.getKey());
+ StorageOperationStatus status = toscaOperationFacade.deletePropertyOfComponent(component, propertyDefinitionEntry.getKey());
if (status != StorageOperationStatus.OK) {
- result = Either.right(componentsUtils.getResponseFormat(componentsUtils
- .convertFromStorageResponse(status), component.getName()));
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
return result;
}
result = Either.left(propertyDefinitionEntry);
return result;
-
} finally {
commitOrRollback(result);
// unlock component
@@ -390,58 +329,48 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
}
}
- public boolean isPropertyUsedByOperation(Component component,
- PropertyDefinition propertyDefinitionEntry) {
-
+ public boolean isPropertyUsedByOperation(Component component, PropertyDefinition propertyDefinitionEntry) {
// Component's own interfaces
Map<String, InterfaceDefinition> interfaces = component.getInterfaces();
- if(MapUtils.isNotEmpty(interfaces)){
- for(Map.Entry<String, InterfaceDefinition> interfaceEntry : interfaces.entrySet()) {
- if (isPropertyExistInOperationInterface(propertyDefinitionEntry, interfaceEntry.getValue())) {
- return true;
+ if (MapUtils.isNotEmpty(interfaces)) {
+ for (Map.Entry<String, InterfaceDefinition> interfaceEntry : interfaces.entrySet()) {
+ if (isPropertyExistInOperationInterface(propertyDefinitionEntry, interfaceEntry.getValue())) {
+ return true;
+ }
}
- }
}
-
// Component's child's component interfaces
- if(isPropertyUsedInCIInterfaces(component.getComponentInstancesInterfaces(), propertyDefinitionEntry)){
+ if (isPropertyUsedInCIInterfaces(component.getComponentInstancesInterfaces(), propertyDefinitionEntry)) {
return true;
}
-
// Component's parent's component interfaces
Either<List<Component>, StorageOperationStatus> componentList = toscaOperationFacade.getParentComponents(component.getUniqueId());
- if(componentList.isLeft()){
+ if (componentList.isLeft()) {
for (Component parentComponent : componentList.left().value()) {
- if(isPropertyUsedInCIInterfaces(parentComponent.getComponentInstancesInterfaces(), propertyDefinitionEntry)){
+ if (isPropertyUsedInCIInterfaces(parentComponent.getComponentInstancesInterfaces(), propertyDefinitionEntry)) {
return true;
}
}
}
-
return false;
}
- private boolean isPropertyUsedInCIInterfaces(Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces, PropertyDefinition propertyDefinitionEntry){
+ private boolean isPropertyUsedInCIInterfaces(Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
+ PropertyDefinition propertyDefinitionEntry) {
Optional<ComponentInstanceInterface> isPropertyExistInOperationInterface = Optional.empty();
- if(MapUtils.isNotEmpty(componentInstanceInterfaces)){
+ if (MapUtils.isNotEmpty(componentInstanceInterfaces)) {
isPropertyExistInOperationInterface = componentInstanceInterfaces.entrySet().stream()
- .flatMap(interfaceEntry -> interfaceEntry.getValue().stream())
- .filter(instanceInterface -> isPropertyExistInOperationInterface(propertyDefinitionEntry, instanceInterface))
- .findAny();
+ .flatMap(interfaceEntry -> interfaceEntry.getValue().stream())
+ .filter(instanceInterface -> isPropertyExistInOperationInterface(propertyDefinitionEntry, instanceInterface)).findAny();
}
return isPropertyExistInOperationInterface.isPresent();
}
- private boolean isPropertyExistInOperationInterface(PropertyDefinition propertyDefinition,
- InterfaceDefinition interfaceDefinition) {
- Map<String, OperationDataDefinition> operations =
- interfaceDefinition.getOperations();
- for(Map.Entry<String, OperationDataDefinition> operationEntry : operations
- .entrySet()) {
- Optional<OperationInputDefinition> inputWithDeletedPropertyCandidate =
- getInputWithDeclaredProperty(propertyDefinition, operationEntry);
-
- if(inputWithDeletedPropertyCandidate.isPresent()) {
+ private boolean isPropertyExistInOperationInterface(PropertyDefinition propertyDefinition, InterfaceDefinition interfaceDefinition) {
+ Map<String, OperationDataDefinition> operations = interfaceDefinition.getOperations();
+ for (Map.Entry<String, OperationDataDefinition> operationEntry : operations.entrySet()) {
+ Optional<OperationInputDefinition> inputWithDeletedPropertyCandidate = getInputWithDeclaredProperty(propertyDefinition, operationEntry);
+ if (inputWithDeletedPropertyCandidate.isPresent()) {
return true;
}
}
@@ -450,17 +379,14 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
private Optional<OperationInputDefinition> getInputWithDeclaredProperty(PropertyDefinition propertyDefinition,
Map.Entry<String, OperationDataDefinition> operationEntry) {
- ListDataDefinition<OperationInputDefinition> inputs =
- operationEntry.getValue().getInputs();
- List<OperationInputDefinition> operationInputsList =
- Objects.isNull(inputs) ? null : inputs.getListToscaDataDefinition();
-
- if(CollectionUtils.isEmpty(operationInputsList)) {
+ ListDataDefinition<OperationInputDefinition> inputs = operationEntry.getValue().getInputs();
+ List<OperationInputDefinition> operationInputsList = Objects.isNull(inputs) ? null : inputs.getListToscaDataDefinition();
+ if (CollectionUtils.isEmpty(operationInputsList)) {
return Optional.empty();
}
-
- return operationInputsList.stream().filter(input -> input.getInputId().equals(propertyDefinition.getUniqueId())
- || (input.getSourceProperty() != null && input.getSourceProperty().equals(propertyDefinition.getUniqueId()))).findAny();
+ return operationInputsList.stream().filter(
+ input -> input.getInputId().equals(propertyDefinition.getUniqueId()) || (input.getSourceProperty() != null && input.getSourceProperty()
+ .equals(propertyDefinition.getUniqueId()))).findAny();
}
/**
@@ -472,59 +398,46 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
* @param userId
* @return either properties or response format
*/
-
- public Either<EntryData<String, PropertyDefinition>, ResponseFormat> updateComponentProperty(String componentId,
- String propertyId,
- PropertyDefinition newPropertyDefinition,
- String userId) {
-
+ public Either<EntryData<String, PropertyDefinition>, ResponseFormat> updateComponentProperty(String componentId, String propertyId,
+ PropertyDefinition newPropertyDefinition,
+ String userId) {
Either<EntryData<String, PropertyDefinition>, ResponseFormat> result = null;
-
- Either<Component, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(
- componentId);
+ Either<Component, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(componentId);
if (status.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
}
Component component = status.left().value();
NodeTypeEnum nodeType = component.getComponentType().getNodeType();
-
if (!ComponentValidationUtils.canWorkOnComponent(component, userId)) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
-
StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, nodeType);
if (!lockResult.equals(StorageOperationStatus.OK)) {
- BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, nodeType.name().toLowerCase(),
- componentId);
+ BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, nodeType.name().toLowerCase(), componentId);
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
return result;
}
-
try {
- Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> statusGetProperty =
- getComponentProperty(componentId, propertyId, userId);
+ Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> statusGetProperty = getComponentProperty(componentId, propertyId, userId);
if (statusGetProperty.isRight()) {
result = Either.right(statusGetProperty.right().value());
return result;
}
String propertyName = statusGetProperty.left().value().getKey();
-
- Either<PropertyDefinition, StorageOperationStatus> either =
- toscaOperationFacade.updatePropertyOfComponent(component, newPropertyDefinition);
+ Either<PropertyDefinition, StorageOperationStatus> either = toscaOperationFacade
+ .updatePropertyOfComponent(component, newPropertyDefinition);
if (either.isRight()) {
- result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), component.getName()));
+ result = Either.right(componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), component.getName()));
return result;
}
-
EntryData<String, PropertyDefinition> property = new EntryData<>(propertyName, either.left().value());
result = Either.left(property);
return result;
-
} finally {
commitOrRollback(result);
graphLockOperation.unlockComponent(componentId, nodeType);
}
-
}
/**
@@ -550,41 +463,32 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
/**
* Updates a component property.
*
- * @param componentId the component id that owns the property
+ * @param componentId the component id that owns the property
* @param propertyDefinition the existing property to update
* @return the updated property
- * @throws BusinessLogicException if the component was not found or if there was a problem during the update
- * operation.
+ * @throws BusinessLogicException if the component was not found or if there was a problem during the update operation.
*/
- public PropertyDefinition updateComponentProperty(final String componentId,
- final PropertyDefinition propertyDefinition)
- throws BusinessLogicException {
+ public PropertyDefinition updateComponentProperty(final String componentId, final PropertyDefinition propertyDefinition)
+ throws BusinessLogicException {
final Component component = findComponentById(componentId).orElse(null);
if (component == null) {
- throw new BusinessLogicException(
- componentsUtils.getResponseFormatByResource(ActionStatus.RESOURCE_NOT_FOUND, componentId));
+ throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(ActionStatus.RESOURCE_NOT_FOUND, componentId));
}
- final Either<PropertyDefinition, StorageOperationStatus> updateResultEither =
- toscaOperationFacade.updatePropertyOfComponent(component, propertyDefinition);
+ final Either<PropertyDefinition, StorageOperationStatus> updateResultEither = toscaOperationFacade
+ .updatePropertyOfComponent(component, propertyDefinition);
if (updateResultEither.isRight()) {
- final ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(updateResultEither.right().value()), component.getName()
- );
+ final ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updateResultEither.right().value()), component.getName());
throw new BusinessLogicException(responseFormat);
}
-
return updateResultEither.left().value();
}
private boolean isPropertyExistInComponent(List<PropertyDefinition> properties, String propertyName) {
- if(CollectionUtils.isEmpty(properties)) {
+ if (CollectionUtils.isEmpty(properties)) {
return false;
}
-
- Optional<PropertyDefinition> propertyCandidate =
- properties.stream().filter(property -> property.getName().equals(propertyName))
- .findAny();
-
+ Optional<PropertyDefinition> propertyCandidate = properties.stream().filter(property -> property.getName().equals(propertyName)).findAny();
return propertyCandidate.isPresent();
}
@@ -593,7 +497,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
if (jsonElement == null || jsonElement.isJsonNull()) {
return EMPTY_VALUE;
}
- if(jsonElement.toString().isEmpty()){
+ if (jsonElement.toString().isEmpty()) {
return "";
}
return jsonElement.toString();
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeBusinessLogic.java
index e231ed7ffe..9a83566166 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeBusinessLogic.java
@@ -13,10 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
+import java.util.Map;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
@@ -27,40 +27,33 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import java.util.Map;
-
@Component("relationshipTypeBusinessLogic")
public class RelationshipTypeBusinessLogic {
- private final RelationshipTypeOperation relationshipTypeOperation;
protected final ComponentsUtils componentsUtils;
+ private final RelationshipTypeOperation relationshipTypeOperation;
@Autowired
- public RelationshipTypeBusinessLogic(RelationshipTypeOperation relationshipTypeOperation,
- ComponentsUtils componentsUtils) {
+ public RelationshipTypeBusinessLogic(RelationshipTypeOperation relationshipTypeOperation, ComponentsUtils componentsUtils) {
this.relationshipTypeOperation = relationshipTypeOperation;
this.componentsUtils = componentsUtils;
}
public Either<Map<String, RelationshipTypeDefinition>, ResponseFormat> getAllRelationshipTypes() {
- Either<Map<String, RelationshipTypeDefinition>, JanusGraphOperationStatus> allRelationshipTypes =
- relationshipTypeOperation.getAllRelationshipTypes();
+ Either<Map<String, RelationshipTypeDefinition>, JanusGraphOperationStatus> allRelationshipTypes = relationshipTypeOperation
+ .getAllRelationshipTypes();
if (allRelationshipTypes.isRight()) {
JanusGraphOperationStatus operationStatus = allRelationshipTypes.right().value();
if (JanusGraphOperationStatus.NOT_FOUND == operationStatus) {
- BeEcompErrorManager.getInstance().logInternalDataError("FetchRelationshipTypes", "Relationship types "
- + "are "
- + "not loaded",
- BeEcompErrorManager.ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance().logInternalDataError("FetchRelationshipTypes", "Relationship types " + "are " + "not loaded",
+ BeEcompErrorManager.ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY));
} else {
- BeEcompErrorManager.getInstance().logInternalFlowError("FetchRelationshipTypes", "Failed to fetch "
- + "relationship types",
- BeEcompErrorManager.ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance().logInternalFlowError("FetchRelationshipTypes", "Failed to fetch " + "relationship types",
+ BeEcompErrorManager.ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
}
return Either.left(allRelationshipTypes.left().value());
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeImportManager.java
index 993d0136f6..6e4d554d98 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeImportManager.java
@@ -13,10 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
+import java.util.List;
+import java.util.Map;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -29,9 +30,6 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import java.util.List;
-import java.util.Map;
-
@Component("relationshipTypeImportManager")
public class RelationshipTypeImportManager {
@@ -40,73 +38,62 @@ public class RelationshipTypeImportManager {
private final ComponentsUtils componentsUtils;
@Autowired
- public RelationshipTypeImportManager(RelationshipTypeOperation relationshipTypeOperation,
- CommonImportManager commonImportManager, ComponentsUtils componentsUtils) {
+ public RelationshipTypeImportManager(RelationshipTypeOperation relationshipTypeOperation, CommonImportManager commonImportManager,
+ ComponentsUtils componentsUtils) {
this.relationshipTypeOperation = relationshipTypeOperation;
this.commonImportManager = commonImportManager;
this.componentsUtils = componentsUtils;
}
- public Either<List<ImmutablePair<RelationshipTypeDefinition, Boolean>>, ResponseFormat> createRelationshipTypes(
- String relationshipYml) {
+ public Either<List<ImmutablePair<RelationshipTypeDefinition, Boolean>>, ResponseFormat> createRelationshipTypes(String relationshipYml) {
return createRelationshipTypes(relationshipYml, false);
}
- private Either<List<ImmutablePair<RelationshipTypeDefinition, Boolean>>, ResponseFormat> createRelationshipTypes(
- String relationshipTypeYml, boolean inTransaction) {
- return commonImportManager.createElementTypes(relationshipTypeYml,
- relationshipTypesFromYml -> createRelationshipTypesFromYml(relationshipTypeYml),
- relationshipTypesToCreate -> createRelationshipTypesByDao(relationshipTypesToCreate,
- inTransaction), ElementTypeEnum.RELATIONSHIP_TYPE);
+ private Either<List<ImmutablePair<RelationshipTypeDefinition, Boolean>>, ResponseFormat> createRelationshipTypes(String relationshipTypeYml,
+ boolean inTransaction) {
+ return commonImportManager
+ .createElementTypes(relationshipTypeYml, relationshipTypesFromYml -> createRelationshipTypesFromYml(relationshipTypeYml),
+ relationshipTypesToCreate -> createRelationshipTypesByDao(relationshipTypesToCreate, inTransaction),
+ ElementTypeEnum.RELATIONSHIP_TYPE);
}
- private Either<List<RelationshipTypeDefinition>, ActionStatus> createRelationshipTypesFromYml(
- String relationshipTypeYml) {
- return commonImportManager.createElementTypesFromYml(relationshipTypeYml,
- this::createRelationshipType);
+ private Either<List<RelationshipTypeDefinition>, ActionStatus> createRelationshipTypesFromYml(String relationshipTypeYml) {
+ return commonImportManager.createElementTypesFromYml(relationshipTypeYml, this::createRelationshipType);
}
private Either<List<ImmutablePair<RelationshipTypeDefinition, Boolean>>, ResponseFormat> createRelationshipTypesByDao(
- List<RelationshipTypeDefinition> relationshipTypesToCreate, boolean inTransaction) {
+ List<RelationshipTypeDefinition> relationshipTypesToCreate, boolean inTransaction) {
return commonImportManager.createElementTypesByDao(relationshipTypesToCreate, this::validateRelationshipType,
- relationshipType -> new ImmutablePair<>(ElementTypeEnum.RELATIONSHIP_TYPE, relationshipType.getType()),
- relationshipTypeName -> relationshipTypeOperation.getRelationshipTypeByName(relationshipTypeName)
- .right().map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus),
- relationshipType -> relationshipTypeOperation.addRelationshipType(relationshipType, inTransaction),
- (newRelationshipType, oldRelationshipType) -> relationshipTypeOperation
- .updateRelationshipType(newRelationshipType, oldRelationshipType, inTransaction));
+ relationshipType -> new ImmutablePair<>(ElementTypeEnum.RELATIONSHIP_TYPE, relationshipType.getType()),
+ relationshipTypeName -> relationshipTypeOperation.getRelationshipTypeByName(relationshipTypeName).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus),
+ relationshipType -> relationshipTypeOperation.addRelationshipType(relationshipType, inTransaction),
+ (newRelationshipType, oldRelationshipType) -> relationshipTypeOperation
+ .updateRelationshipType(newRelationshipType, oldRelationshipType, inTransaction));
}
-
private Either<ActionStatus, ResponseFormat> validateRelationshipType(RelationshipTypeDefinition relationshipType) {
Either<ActionStatus, ResponseFormat> result = Either.left(ActionStatus.OK);
if (relationshipType.getType() == null) {
- ResponseFormat responseFormat =
- componentsUtils.getResponseFormat(ActionStatus.MISSING_RELATIONSHIP_TYPE, relationshipType.getType());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_RELATIONSHIP_TYPE, relationshipType.getType());
result = Either.right(responseFormat);
}
return result;
}
- private RelationshipTypeDefinition createRelationshipType(String relationshipTypeName,
- Map<String, Object> toscaJson) {
+ private RelationshipTypeDefinition createRelationshipType(String relationshipTypeName, Map<String, Object> toscaJson) {
RelationshipTypeDefinition relationshipType = new RelationshipTypeDefinition();
-
relationshipType.setType(relationshipTypeName);
-
// Description
- commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName(),
- relationshipType::setDescription);
+ commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName(), relationshipType::setDescription);
// Derived From
- commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM.getElementName(),
- relationshipType::setDerivedFrom);
+ commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM.getElementName(), relationshipType::setDerivedFrom);
// Properties
commonImportManager.setPropertiesMap(toscaJson, relationshipType::setProperties);
//valid-target-types
- if(toscaJson.get("valid_target_types") instanceof List)
+ if (toscaJson.get("valid_target_types") instanceof List) {
relationshipType.setValidTargetTypes((List<String>) toscaJson.get("valid_target_types"));
-
+ }
return relationshipType;
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementBusinessLogic.java
index f3aca5696a..e5d704709d 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementBusinessLogic.java
@@ -13,10 +13,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
@@ -41,39 +49,23 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.UUID;
-import java.util.stream.Collectors;
-
@Component("requirementBusinessLogic")
public class RequirementBusinessLogic extends BaseBusinessLogic {
+
private static final Logger LOGGER = LoggerFactory.getLogger(RequirementBusinessLogic.class);
- private static final String FAILED_TO_LOCK_COMPONENT_RESPONSE_IS
- = "Failed to lock component {}. Response is {}";
+ private static final String FAILED_TO_LOCK_COMPONENT_RESPONSE_IS = "Failed to lock component {}. Response is {}";
private static final String DELETE_REQUIREMENTS = "deleteRequirement";
private static final String GET_REQUIREMENTS = "getRequirements";
- private static final String EXCEPTION_OCCURRED_DURING_REQUIREMENTS
- = "Exception occurred during {}. Response is {}";
-
+ private static final String EXCEPTION_OCCURRED_DURING_REQUIREMENTS = "Exception occurred during {}. Response is {}";
private RequirementOperation requirementOperation;
private RequirementValidation requirementValidation;
@Autowired
- public RequirementBusinessLogic(IElementOperation elementDao,
- IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation,
- IGroupTypeOperation groupTypeOperation,
- InterfaceOperation interfaceOperation,
- InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
- ArtifactsOperations artifactToscaOperation) {
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
- interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+ public RequirementBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+ IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
+ InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+ artifactToscaOperation);
}
@Autowired
@@ -86,63 +78,52 @@ public class RequirementBusinessLogic extends BaseBusinessLogic {
this.requirementValidation = requirementValidation;
}
- public Either<List<RequirementDefinition>, ResponseFormat> createRequirements(
- String componentId, List<RequirementDefinition> requirementDefinitions,
- User user, String errorContext, boolean lock) {
+ public Either<List<RequirementDefinition>, ResponseFormat> createRequirements(String componentId,
+ List<RequirementDefinition> requirementDefinitions, User user,
+ String errorContext, boolean lock) {
validateUserExists(user.getUserId());
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither
- = getComponentDetails(componentId);
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId);
if (componentEither.isRight()) {
return Either.right(componentEither.right().value());
}
org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value();
-
Either<Boolean, ResponseFormat> requirementsValidationEither = requirementValidation
- .validateRequirements(requirementDefinitions, storedComponent, false);
+ .validateRequirements(requirementDefinitions, storedComponent, false);
if (requirementsValidationEither.isRight()) {
return Either.right(requirementsValidationEither.right().value());
}
-
- Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock,
- storedComponent, errorContext);
+ Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock, storedComponent, errorContext);
if (lockResult.isRight()) {
return Either.right(lockResult.right().value());
}
-
try {
Either<List<RequirementDefinition>, StorageOperationStatus> result;
List<RequirementDefinition> requirementsListStoredInComponent = null;
- Map<String, List<RequirementDefinition>> storedComponentRequirements
- = storedComponent.getRequirements();
+ Map<String, List<RequirementDefinition>> storedComponentRequirements = storedComponent.getRequirements();
if (org.apache.commons.collections.MapUtils.isNotEmpty(storedComponentRequirements)) {
RequirementDefinition requirementDefinitionToGetType = requirementDefinitions.get(0);
- if(Objects.isNull(requirementDefinitionToGetType)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ if (Objects.isNull(requirementDefinitionToGetType)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
- requirementsListStoredInComponent
- = getRequirementStoredInComponentByType(requirementDefinitionToGetType
- .getCapability(), storedComponentRequirements);
+ requirementsListStoredInComponent = getRequirementStoredInComponentByType(requirementDefinitionToGetType.getCapability(),
+ storedComponentRequirements);
}
List<RequirementDefinition> requirementsToReturn;
- if (org.apache.commons.collections.CollectionUtils
- .isNotEmpty(requirementsListStoredInComponent)) {
+ if (org.apache.commons.collections.CollectionUtils.isNotEmpty(requirementsListStoredInComponent)) {
List<RequirementDefinition> requirementDefToCreate = requirementDefinitions.stream()
- .map(requirementDefinition -> initiateNewRequirement(storedComponent, requirementDefinition))
- .collect(Collectors.toList());
+ .map(requirementDefinition -> initiateNewRequirement(storedComponent, requirementDefinition)).collect(Collectors.toList());
requirementsToReturn = requirementDefToCreate;
requirementDefToCreate.addAll(requirementsListStoredInComponent);
result = requirementOperation.updateRequirement(componentId, requirementDefToCreate);
} else {
- requirementsToReturn = requirementDefinitions.stream().map(requirementDefinition ->
- initiateNewRequirement(storedComponent, requirementDefinition))
- .collect(Collectors.toList());
+ requirementsToReturn = requirementDefinitions.stream()
+ .map(requirementDefinition -> initiateNewRequirement(storedComponent, requirementDefinition)).collect(Collectors.toList());
result = requirementOperation.addRequirement(componentId, requirementsToReturn);
}
if (result.isRight()) {
janusGraphDao.rollback();
- return Either.right(componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(result.right().value(),
- storedComponent.getComponentType()), ""));
+ return Either.right(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value(), storedComponent.getComponentType()), ""));
}
janusGraphDao.commit();
return Either.left(requirementsToReturn);
@@ -152,75 +133,63 @@ public class RequirementBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
} finally {
if (lockResult.isLeft() && lockResult.left().value()) {
- graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
- NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+ graphLockOperation
+ .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
}
}
}
- public Either<List<RequirementDefinition>, ResponseFormat> updateRequirements(
- String componentId, List<RequirementDefinition> requirementDefinitions,
- User user, String errorContext, boolean lock) {
+ public Either<List<RequirementDefinition>, ResponseFormat> updateRequirements(String componentId,
+ List<RequirementDefinition> requirementDefinitions, User user,
+ String errorContext, boolean lock) {
validateUserExists(user.getUserId());
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither
- = getComponentDetails(componentId);
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId);
if (componentEither.isRight()) {
return Either.right(componentEither.right().value());
}
org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value();
-
Either<Boolean, ResponseFormat> requirementsValidationEither = requirementValidation
- .validateRequirements(requirementDefinitions, storedComponent, true);
+ .validateRequirements(requirementDefinitions, storedComponent, true);
if (requirementsValidationEither.isRight()) {
return Either.right(requirementsValidationEither.right().value());
}
-
- Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock,
- storedComponent, errorContext);
+ Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock, storedComponent, errorContext);
if (lockResult.isRight()) {
return Either.right(lockResult.right().value());
}
try {
Either<List<RequirementDefinition>, StorageOperationStatus> result;
List<RequirementDefinition> requirementsListStoredInComponent = null;
- Map<String, List<RequirementDefinition>> storedComponentRequirements
- = storedComponent.getRequirements();
+ Map<String, List<RequirementDefinition>> storedComponentRequirements = storedComponent.getRequirements();
if (org.apache.commons.collections.MapUtils.isNotEmpty(storedComponentRequirements)) {
RequirementDefinition requirementDefinitionToGetType = requirementDefinitions.get(0);
- if(Objects.isNull(requirementDefinitionToGetType)) {
+ if (Objects.isNull(requirementDefinitionToGetType)) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
- requirementsListStoredInComponent
- = getRequirementStoredInComponentByType(requirementDefinitionToGetType
- .getCapability(), storedComponentRequirements);
+ requirementsListStoredInComponent = getRequirementStoredInComponentByType(requirementDefinitionToGetType.getCapability(),
+ storedComponentRequirements);
}
List<RequirementDefinition> requirementsToReturn = null;
- if (org.apache.commons.collections.CollectionUtils
- .isNotEmpty(requirementsListStoredInComponent)) {
+ if (org.apache.commons.collections.CollectionUtils.isNotEmpty(requirementsListStoredInComponent)) {
List<RequirementDefinition> requirementDefToUpdate = new ArrayList<>();
- if (requirementDefinitions.stream().anyMatch(requirementDefinition ->
- isRequirementUsedInServiceComposition(requirementDefinition, storedComponent))) {
+ if (requirementDefinitions.stream()
+ .anyMatch(requirementDefinition -> isRequirementUsedInServiceComposition(requirementDefinition, storedComponent))) {
LOGGER.error("Requirement can't be edited, since it is used in service composition");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus
- .REQUIREMENT_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION));
}
for (RequirementDefinition requirementDefinitionToUpdate : requirementDefinitions) {
requirementsToReturn = requirementsListStoredInComponent.stream()
- .filter(reqToUpdate -> reqToUpdate.getUniqueId()
- .equals(requirementDefinitionToUpdate.getUniqueId()))
- .map(requirementDefinition -> updateRequirement(requirementDefinition,
- requirementDefinitionToUpdate)).collect(Collectors.toList());
- requirementsListStoredInComponent.removeIf(reqToUpdate ->
- reqToUpdate.getUniqueId().equals(requirementDefinitionToUpdate.getUniqueId()));
-
+ .filter(reqToUpdate -> reqToUpdate.getUniqueId().equals(requirementDefinitionToUpdate.getUniqueId()))
+ .map(requirementDefinition -> updateRequirement(requirementDefinition, requirementDefinitionToUpdate))
+ .collect(Collectors.toList());
+ requirementsListStoredInComponent
+ .removeIf(reqToUpdate -> reqToUpdate.getUniqueId().equals(requirementDefinitionToUpdate.getUniqueId()));
if (CollectionUtils.isNotEmpty(requirementsToReturn)) {
requirementsListStoredInComponent.addAll(requirementsToReturn);
requirementDefToUpdate.addAll(requirementsListStoredInComponent);
} else {
- Either<List<RequirementDefinition>, ResponseFormat> updateCapTypeEither
- = handleUpdateRequirementCapabilityWhenNewCapabilityExist(storedComponent,
- storedComponentRequirements,
- requirementsToReturn, requirementDefinitionToUpdate);
+ Either<List<RequirementDefinition>, ResponseFormat> updateCapTypeEither = handleUpdateRequirementCapabilityWhenNewCapabilityExist(
+ storedComponent, storedComponentRequirements, requirementsToReturn, requirementDefinitionToUpdate);
if (updateCapTypeEither.isRight()) {
return Either.right(updateCapTypeEither.right().value());
}
@@ -229,22 +198,19 @@ public class RequirementBusinessLogic extends BaseBusinessLogic {
}
result = requirementOperation.updateRequirement(componentId, requirementDefToUpdate);
} else {
- Either<List<RequirementDefinition>, ResponseFormat> requirementDefinitionToDelete
- = handleRequirementCapabilityUpdateWhenNewCapabilityNotExist(requirementDefinitions,
- storedComponent, storedComponentRequirements);
+ Either<List<RequirementDefinition>, ResponseFormat> requirementDefinitionToDelete = handleRequirementCapabilityUpdateWhenNewCapabilityNotExist(
+ requirementDefinitions, storedComponent, storedComponentRequirements);
if (requirementDefinitionToDelete != null) {
return requirementDefinitionToDelete;
}
- requirementsToReturn = requirementDefinitions.stream().map(requirementDefinition ->
- initiateNewRequirement(storedComponent, requirementDefinition))
- .collect(Collectors.toList());
+ requirementsToReturn = requirementDefinitions.stream()
+ .map(requirementDefinition -> initiateNewRequirement(storedComponent, requirementDefinition)).collect(Collectors.toList());
result = requirementOperation.addRequirement(componentId, requirementsToReturn);
}
if (result.isRight()) {
janusGraphDao.rollback();
- return Either.right(componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(result.right().value(),
- storedComponent.getComponentType()), ""));
+ return Either.right(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value(), storedComponent.getComponentType()), ""));
}
janusGraphDao.commit();
return Either.left(requirementsToReturn);
@@ -254,70 +220,55 @@ public class RequirementBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
} finally {
if (lockResult.isLeft() && lockResult.left().value()) {
- graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
- NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+ graphLockOperation
+ .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
}
}
}
private Either<List<RequirementDefinition>, ResponseFormat> handleUpdateRequirementCapabilityWhenNewCapabilityExist(
- org.openecomp.sdc.be.model.Component storedComponent,
- Map<String, List<RequirementDefinition>> storedComponentRequirements,
- List<RequirementDefinition> requirementsToReturn,
- RequirementDefinition requirementDefinitionToUpdate) {
+ org.openecomp.sdc.be.model.Component storedComponent, Map<String, List<RequirementDefinition>> storedComponentRequirements,
+ List<RequirementDefinition> requirementsToReturn, RequirementDefinition requirementDefinitionToUpdate) {
List<RequirementDefinition> requirementsListStoredInComponent;
List<RequirementDefinition> requirementDefsToCreateOrUpdate = new ArrayList<>();
- Optional<RequirementDefinition> definitionOptional = storedComponentRequirements
- .values().stream().flatMap(Collection::stream)
- .filter(requirementDefinition -> requirementDefinition.getUniqueId()
- .equals(requirementDefinitionToUpdate.getUniqueId())).findAny();
+ Optional<RequirementDefinition> definitionOptional = storedComponentRequirements.values().stream().flatMap(Collection::stream)
+ .filter(requirementDefinition -> requirementDefinition.getUniqueId().equals(requirementDefinitionToUpdate.getUniqueId())).findAny();
if (!definitionOptional.isPresent()) {
- return Either.right(componentsUtils.getResponseFormat(
- ActionStatus.REQUIREMENT_NOT_FOUND, storedComponent.getUniqueId()));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, storedComponent.getUniqueId()));
}
RequirementDefinition requirementDefinitionToDelete = definitionOptional.get();
-
- requirementsListStoredInComponent = getRequirementStoredInComponentByType(
- requirementDefinitionToUpdate.getCapability(), storedComponentRequirements);
- Either<List<RequirementDefinition>, StorageOperationStatus> deleteRequirementEither
- = deleteRequirement(storedComponent, storedComponentRequirements, requirementDefinitionToDelete);
+ requirementsListStoredInComponent = getRequirementStoredInComponentByType(requirementDefinitionToUpdate.getCapability(),
+ storedComponentRequirements);
+ Either<List<RequirementDefinition>, StorageOperationStatus> deleteRequirementEither = deleteRequirement(storedComponent,
+ storedComponentRequirements, requirementDefinitionToDelete);
if (deleteRequirementEither.isRight()) {
janusGraphDao.rollback();
return Either.right(componentsUtils.getResponseFormat(deleteRequirementEither.right().value()));
}
requirementsToReturn.add(initiateNewRequirement(storedComponent, requirementDefinitionToUpdate));
-
requirementDefsToCreateOrUpdate.addAll(requirementsToReturn);
requirementDefsToCreateOrUpdate.addAll(requirementsListStoredInComponent);
return Either.left(requirementDefsToCreateOrUpdate);
}
private Either<List<RequirementDefinition>, ResponseFormat> handleRequirementCapabilityUpdateWhenNewCapabilityNotExist(
- List<RequirementDefinition> requirementDefinitions,
- org.openecomp.sdc.be.model.Component storedComponent,
- Map<String, List<RequirementDefinition>> storedComponentRequirements) {
+ List<RequirementDefinition> requirementDefinitions, org.openecomp.sdc.be.model.Component storedComponent,
+ Map<String, List<RequirementDefinition>> storedComponentRequirements) {
for (RequirementDefinition requirementDefinitionToUpdate : requirementDefinitions) {
-
- Optional<RequirementDefinition> definitionOptional = storedComponentRequirements
- .values().stream().flatMap(Collection::stream)
- .filter(requirementDefinition -> requirementDefinition.getUniqueId()
- .equals(requirementDefinitionToUpdate.getUniqueId())).findAny();
+ Optional<RequirementDefinition> definitionOptional = storedComponentRequirements.values().stream().flatMap(Collection::stream)
+ .filter(requirementDefinition -> requirementDefinition.getUniqueId().equals(requirementDefinitionToUpdate.getUniqueId())).findAny();
if (!definitionOptional.isPresent()) {
- return Either.right(componentsUtils.getResponseFormat(
- ActionStatus.REQUIREMENT_NOT_FOUND, storedComponent.getUniqueId()));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, storedComponent.getUniqueId()));
}
RequirementDefinition requirementDefinitionToDelete = definitionOptional.get();
- Boolean isRequirementUsedInServiceComposition
- = isRequirementUsedInServiceComposition(requirementDefinitionToDelete, storedComponent);
+ Boolean isRequirementUsedInServiceComposition = isRequirementUsedInServiceComposition(requirementDefinitionToDelete, storedComponent);
if (isRequirementUsedInServiceComposition) {
- LOGGER.error("Requirement {} can't be edited, since it is used in service composition",
- requirementDefinitionToDelete.getUniqueId());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus
- .REQUIREMENT_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION,
- requirementDefinitionToDelete.getName()));
+ LOGGER.error("Requirement {} can't be edited, since it is used in service composition", requirementDefinitionToDelete.getUniqueId());
+ return Either.right(componentsUtils
+ .getResponseFormat(ActionStatus.REQUIREMENT_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION, requirementDefinitionToDelete.getName()));
}
- Either<List<RequirementDefinition>, StorageOperationStatus> deleteRequirementEither
- = deleteRequirement(storedComponent, storedComponentRequirements, requirementDefinitionToDelete);
+ Either<List<RequirementDefinition>, StorageOperationStatus> deleteRequirementEither = deleteRequirement(storedComponent,
+ storedComponentRequirements, requirementDefinitionToDelete);
if (deleteRequirementEither.isRight()) {
janusGraphDao.rollback();
return Either.right(componentsUtils.getResponseFormat(deleteRequirementEither.right().value()));
@@ -326,30 +277,26 @@ public class RequirementBusinessLogic extends BaseBusinessLogic {
return null;
}
- public Either<RequirementDefinition, ResponseFormat> getRequirement(String componentId,
- String requirementIdToGet, User user, boolean lock) {
+ public Either<RequirementDefinition, ResponseFormat> getRequirement(String componentId, String requirementIdToGet, User user, boolean lock) {
validateUserExists(user.getUserId());
Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId);
if (componentEither.isRight()) {
return Either.right(componentEither.right().value());
}
org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value();
-
Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock, storedComponent, GET_REQUIREMENTS);
if (lockResult.isRight()) {
return Either.right(lockResult.right().value());
}
try {
-
- List<RequirementDefinition> requirementDefinitions = storedComponent.getRequirements().values().stream()
- .flatMap(Collection::stream).collect(Collectors.toList());
+ List<RequirementDefinition> requirementDefinitions = storedComponent.getRequirements().values().stream().flatMap(Collection::stream)
+ .collect(Collectors.toList());
if (requirementDefinitions.isEmpty()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, componentId));
}
-
RequirementDefinition requirementDefinitionToReturn;
Optional<RequirementDefinition> requirementDefinitionOptional = requirementDefinitions.stream()
- .filter(requirementDefinition -> requirementDefinition.getUniqueId().equals(requirementIdToGet)).findAny();
+ .filter(requirementDefinition -> requirementDefinition.getUniqueId().equals(requirementIdToGet)).findAny();
if (requirementDefinitionOptional.isPresent()) {
requirementDefinitionToReturn = requirementDefinitionOptional.get();
} else {
@@ -361,61 +308,48 @@ public class RequirementBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, componentId));
} finally {
if (lockResult.isLeft() && lockResult.left().value()) {
- graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
- NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+ graphLockOperation
+ .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
}
}
}
- public Either<RequirementDefinition, ResponseFormat> deleteRequirement(String componentId,
- String requirementIdToDelete,
- User user, boolean lock) {
+ public Either<RequirementDefinition, ResponseFormat> deleteRequirement(String componentId, String requirementIdToDelete, User user,
+ boolean lock) {
validateUserExists(user.getUserId());
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither
- = getComponentDetails(componentId);
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId);
if (componentEither.isRight()) {
return Either.right(componentEither.right().value());
}
org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value();
-
Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock, storedComponent, DELETE_REQUIREMENTS);
if (lockResult.isRight()) {
return Either.right(lockResult.right().value());
}
-
try {
Map<String, List<RequirementDefinition>> storedComponentRequirements = storedComponent.getRequirements();
if (storedComponentRequirements.isEmpty()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, componentId));
}
-
- Optional<RequirementDefinition> definitionOptional = storedComponentRequirements
- .values().stream().flatMap(Collection::stream)
- .filter(requirementDefinition -> requirementDefinition.getUniqueId()
- .equals(requirementIdToDelete)).findAny();
+ Optional<RequirementDefinition> definitionOptional = storedComponentRequirements.values().stream().flatMap(Collection::stream)
+ .filter(requirementDefinition -> requirementDefinition.getUniqueId().equals(requirementIdToDelete)).findAny();
if (!definitionOptional.isPresent()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, componentId));
}
RequirementDefinition requirementDefinitionToDelete = definitionOptional.get();
-
- Boolean isRequirementUsedInServiceComposition
- = isRequirementUsedInServiceComposition(requirementDefinitionToDelete, storedComponent);
+ Boolean isRequirementUsedInServiceComposition = isRequirementUsedInServiceComposition(requirementDefinitionToDelete, storedComponent);
if (isRequirementUsedInServiceComposition) {
- LOGGER.error("Requirement {} can't be deleted, since it is used in service composition",
- requirementDefinitionToDelete.getUniqueId());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus
- .CAPABILITY_DELETION_NOT_ALLOWED_USED_IN_COMPOSITION,
- requirementDefinitionToDelete.getName()));
+ LOGGER.error("Requirement {} can't be deleted, since it is used in service composition", requirementDefinitionToDelete.getUniqueId());
+ return Either.right(componentsUtils
+ .getResponseFormat(ActionStatus.CAPABILITY_DELETION_NOT_ALLOWED_USED_IN_COMPOSITION, requirementDefinitionToDelete.getName()));
}
-
- Either<List<RequirementDefinition>, StorageOperationStatus> result
- = deleteRequirement(storedComponent, storedComponentRequirements, requirementDefinitionToDelete);
+ Either<List<RequirementDefinition>, StorageOperationStatus> result = deleteRequirement(storedComponent, storedComponentRequirements,
+ requirementDefinitionToDelete);
if (result.isRight()) {
janusGraphDao.rollback();
- LOGGER.error("Failed to delete requirement from component {}. Response is {}",
- storedComponent.getName(), result.right().value());
- return Either.right(componentsUtils.getResponseFormat(componentsUtils
- .convertFromStorageResponse(result.right().value(), storedComponent.getComponentType())));
+ LOGGER.error("Failed to delete requirement from component {}. Response is {}", storedComponent.getName(), result.right().value());
+ return Either.right(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value(), storedComponent.getComponentType())));
}
janusGraphDao.commit();
return Either.left(requirementDefinitionToDelete);
@@ -425,37 +359,33 @@ public class RequirementBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND));
} finally {
if (lockResult.isLeft() && lockResult.left().value()) {
- graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
- NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+ graphLockOperation
+ .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
}
}
}
- private Either<List<RequirementDefinition>, StorageOperationStatus> deleteRequirement(
- org.openecomp.sdc.be.model.Component storedComponent, Map<String,
- List<RequirementDefinition>> storedComponentRequirements,
- RequirementDefinition requirementDefinitionToDelete) {
- List<RequirementDefinition> requirementStoredInComponentByType =
- getRequirementStoredInComponentByType(requirementDefinitionToDelete.getCapability(),
- storedComponentRequirements);
- if(requirementStoredInComponentByType == null) {
+ private Either<List<RequirementDefinition>, StorageOperationStatus> deleteRequirement(org.openecomp.sdc.be.model.Component storedComponent,
+ Map<String, List<RequirementDefinition>> storedComponentRequirements,
+ RequirementDefinition requirementDefinitionToDelete) {
+ List<RequirementDefinition> requirementStoredInComponentByType = getRequirementStoredInComponentByType(
+ requirementDefinitionToDelete.getCapability(), storedComponentRequirements);
+ if (requirementStoredInComponentByType == null) {
return Either.right(StorageOperationStatus.BAD_REQUEST);
}
- requirementStoredInComponentByType.removeIf(requirementDefinition ->
- requirementDefinition.getUniqueId().equals(requirementDefinitionToDelete.getUniqueId()));
+ requirementStoredInComponentByType
+ .removeIf(requirementDefinition -> requirementDefinition.getUniqueId().equals(requirementDefinitionToDelete.getUniqueId()));
Either<List<RequirementDefinition>, StorageOperationStatus> result;
if (requirementStoredInComponentByType.isEmpty()) {
-
- StorageOperationStatus operationStatus = requirementOperation.deleteRequirements(storedComponent,
- requirementDefinitionToDelete.getCapability());
+ StorageOperationStatus operationStatus = requirementOperation
+ .deleteRequirements(storedComponent, requirementDefinitionToDelete.getCapability());
if (operationStatus.equals(StorageOperationStatus.OK)) {
result = Either.left(Collections.singletonList(requirementDefinitionToDelete));
} else {
result = Either.right(operationStatus);
}
} else {
- result = requirementOperation.updateRequirement(storedComponent.getUniqueId(),
- requirementStoredInComponentByType);
+ result = requirementOperation.updateRequirement(storedComponent.getUniqueId(), requirementStoredInComponentByType);
}
return result;
}
@@ -463,8 +393,8 @@ public class RequirementBusinessLogic extends BaseBusinessLogic {
private Either<org.openecomp.sdc.be.model.Component, ResponseFormat> getComponentDetails(String componentId) {
ComponentParametersView filter = new ComponentParametersView(true);
filter.setIgnoreRequirements(false);
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentStorageOperationStatusEither
- = toscaOperationFacade.getToscaElement(componentId, filter);
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade
+ .getToscaElement(componentId, filter);
if (componentStorageOperationStatusEither.isRight()) {
StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
LOGGER.error("Failed to fetch component information by component id {}, Response is {}", componentId, errorStatus);
@@ -473,15 +403,12 @@ public class RequirementBusinessLogic extends BaseBusinessLogic {
return Either.left(componentStorageOperationStatusEither.left().value());
}
- private Either<Boolean, ResponseFormat> lockComponentResult(boolean lock,
- org.openecomp.sdc.be.model.Component component,
- String action) {
+ private Either<Boolean, ResponseFormat> lockComponentResult(boolean lock, org.openecomp.sdc.be.model.Component component, String action) {
if (lock) {
- try{
- lockComponent(component.getUniqueId(), component, action);
- } catch (ComponentException e){
- LOGGER.debug(FAILED_TO_LOCK_COMPONENT_RESPONSE_IS, component.getName(),
- e.getMessage());
+ try {
+ lockComponent(component.getUniqueId(), component, action);
+ } catch (ComponentException e) {
+ LOGGER.debug(FAILED_TO_LOCK_COMPONENT_RESPONSE_IS, component.getName(), e.getMessage());
janusGraphDao.rollback();
throw e;
}
@@ -489,30 +416,29 @@ public class RequirementBusinessLogic extends BaseBusinessLogic {
return Either.left(true);
}
- private List<RequirementDefinition> getRequirementStoredInComponentByType(
- String capabilityType, Map<String,
- List<RequirementDefinition>> requirements) {
-
- Optional<Map.Entry<String, List<RequirementDefinition>>> entryOptional
- = requirements.entrySet().stream().filter(map -> map.getKey().equals(capabilityType)).findFirst();
+ private List<RequirementDefinition> getRequirementStoredInComponentByType(String capabilityType,
+ Map<String, List<RequirementDefinition>> requirements) {
+ Optional<Map.Entry<String, List<RequirementDefinition>>> entryOptional = requirements.entrySet().stream()
+ .filter(map -> map.getKey().equals(capabilityType)).findFirst();
return entryOptional.map(Map.Entry::getValue).orElse(null);
-
}
private RequirementDefinition initiateNewRequirement(org.openecomp.sdc.be.model.Component component,
RequirementDefinition requirementDefinition) {
- if (StringUtils.isEmpty(requirementDefinition.getUniqueId()))
+ if (StringUtils.isEmpty(requirementDefinition.getUniqueId())) {
requirementDefinition.setUniqueId(UUID.randomUUID().toString());
- if (StringUtils.isEmpty(requirementDefinition.getOwnerId()))
+ }
+ if (StringUtils.isEmpty(requirementDefinition.getOwnerId())) {
requirementDefinition.setOwnerId(component.getUniqueId());
- if (StringUtils.isEmpty(requirementDefinition.getOwnerName()))
+ }
+ if (StringUtils.isEmpty(requirementDefinition.getOwnerName())) {
requirementDefinition.setOwnerName(component.getName());
+ }
requirementDefinition.setLeftOccurrences(requirementDefinition.getMaxOccurrences());
return requirementDefinition;
}
- private RequirementDefinition updateRequirement(RequirementDefinition storedRequirement,
- RequirementDefinition requirementToUpdate) {
+ private RequirementDefinition updateRequirement(RequirementDefinition storedRequirement, RequirementDefinition requirementToUpdate) {
storedRequirement.setName(requirementToUpdate.getName());
storedRequirement.setCapability(requirementToUpdate.getCapability());
storedRequirement.setNode(requirementToUpdate.getNode());
@@ -524,15 +450,14 @@ public class RequirementBusinessLogic extends BaseBusinessLogic {
private Boolean isRequirementUsedInServiceComposition(RequirementDefinition requirementDefinition,
org.openecomp.sdc.be.model.Component component) {
- Either<List<org.openecomp.sdc.be.model.Component>, StorageOperationStatus> componentList
- = toscaOperationFacade.getParentComponents(component.getUniqueId());
+ Either<List<org.openecomp.sdc.be.model.Component>, StorageOperationStatus> componentList = toscaOperationFacade
+ .getParentComponents(component.getUniqueId());
if (componentList.isRight()) {
return Boolean.FALSE;
}
- return componentList.left().value().stream()
- .flatMap(parentComponent -> parentComponent.getComponentInstancesRelations()
- .stream()).flatMap(requirementCapabilityRelDef -> requirementCapabilityRelDef.getRelationships().stream())
- .anyMatch(capabilityRequirementRelationship -> capabilityRequirementRelationship.getRelation()
- .getRequirementUid().equals(requirementDefinition.getUniqueId()));
+ return componentList.left().value().stream().flatMap(parentComponent -> parentComponent.getComponentInstancesRelations().stream())
+ .flatMap(requirementCapabilityRelDef -> requirementCapabilityRelDef.getRelationships().stream()).anyMatch(
+ capabilityRequirementRelationship -> capabilityRequirementRelationship.getRelation().getRequirementUid()
+ .equals(requirementDefinition.getUniqueId()));
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java
index eb4bb33d70..cc10da0a6e 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import org.openecomp.sdc.be.impl.ComponentsUtils;
@@ -26,13 +25,10 @@ import org.springframework.stereotype.Component;
@Component("requirementsBusinessLogic")
public class RequirementsBusinessLogic {
- private static final Logger log = Logger.getLogger(RequirementsBusinessLogic.class);
+ private static final Logger log = Logger.getLogger(RequirementsBusinessLogic.class);
@javax.annotation.Resource
private ComponentsUtils componentsUtils;
-
@javax.annotation.Resource
private ResourceBusinessLogic resourceBusinessLogic;
-
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java
index a3d746da89..22fdc3b6e5 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import static java.util.stream.Collectors.joining;
@@ -190,154 +189,143 @@ import org.yaml.snakeyaml.Yaml;
@org.springframework.stereotype.Component("resourceBusinessLogic")
public class ResourceBusinessLogic extends ComponentBusinessLogic {
- private static final String DELETE_RESOURCE = "Delete Resource";
- private static final String IN_RESOURCE = " in resource {} ";
- private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
- private static final String INITIAL_VERSION = "0.1";
- private static final Logger log = Logger.getLogger(ResourceBusinessLogic.class);
- private static final String CERTIFICATION_ON_IMPORT = "certification on import";
- private static final String CREATE_RESOURCE = "Create Resource";
- private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
- private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
- private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
- private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
- private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {} in resource {} ";
- private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ResourceBusinessLogic.class.getName());
-
- private IInterfaceLifecycleOperation interfaceTypeOperation;
- private LifecycleBusinessLogic lifecycleBusinessLogic;
-
- private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
- private final ResourceImportManager resourceImportManager;
- private final InputsBusinessLogic inputsBusinessLogic;
- private final OutputsBusinessLogic outputsBusinessLogic;
- private final CompositionBusinessLogic compositionBusinessLogic;
- private final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic;
- private final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
- private final MergeInstanceUtils mergeInstanceUtils;
- private final UiComponentDataConverter uiComponentDataConverter;
- private final CsarBusinessLogic csarBusinessLogic;
- private final PropertyBusinessLogic propertyBusinessLogic;
- private final PolicyBusinessLogic policyBusinessLogic;
-
- @Autowired
- public ResourceBusinessLogic(final IElementOperation elementDao,
- final IGroupOperation groupOperation,
- final IGroupInstanceOperation groupInstanceOperation,
- final IGroupTypeOperation groupTypeOperation,
- final GroupBusinessLogic groupBusinessLogic,
- final InterfaceOperation interfaceOperation,
- final InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
- final ArtifactsBusinessLogic artifactsBusinessLogic,
- final ComponentInstanceBusinessLogic componentInstanceBusinessLogic,
- final @Lazy ResourceImportManager resourceImportManager,
- final InputsBusinessLogic inputsBusinessLogic,
- final OutputsBusinessLogic outputsBusinessLogic,
- final CompositionBusinessLogic compositionBusinessLogic,
- final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic,
- final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic,
- final MergeInstanceUtils mergeInstanceUtils,
- final UiComponentDataConverter uiComponentDataConverter,
- final CsarBusinessLogic csarBusinessLogic,
- final ArtifactsOperations artifactToscaOperation,
- final PropertyBusinessLogic propertyBusinessLogic,
- final ComponentContactIdValidator componentContactIdValidator,
- final ComponentNameValidator componentNameValidator,
- final ComponentTagsValidator componentTagsValidator,
- final ComponentValidator componentValidator,
- final ComponentIconValidator componentIconValidator,
- final ComponentProjectCodeValidator componentProjectCodeValidator,
- final ComponentDescriptionValidator componentDescriptionValidator,
- final PolicyBusinessLogic policyBusinessLogic) {
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic, interfaceOperation,
- interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, componentContactIdValidator,
- componentNameValidator, componentTagsValidator, componentValidator, componentIconValidator, componentProjectCodeValidator,
- componentDescriptionValidator);
- this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
- this.resourceImportManager = resourceImportManager;
- this.inputsBusinessLogic = inputsBusinessLogic;
- this.outputsBusinessLogic = outputsBusinessLogic;
- this.compositionBusinessLogic = compositionBusinessLogic;
- this.resourceDataMergeBusinessLogic = resourceDataMergeBusinessLogic;
- this.csarArtifactsAndGroupsBusinessLogic = csarArtifactsAndGroupsBusinessLogic;
- this.mergeInstanceUtils = mergeInstanceUtils;
- this.uiComponentDataConverter = uiComponentDataConverter;
- this.csarBusinessLogic = csarBusinessLogic;
- this.propertyBusinessLogic = propertyBusinessLogic;
- this.policyBusinessLogic = policyBusinessLogic;
- }
-
- @Autowired
- private ICapabilityTypeOperation capabilityTypeOperation;
-
- @Autowired
- private TopologyComparator topologyComparator;
-
- @Autowired
- private ComponentValidator componentValidator;
-
- @Autowired
- private PropertyDataValueMergeBusinessLogic propertyDataValueMergeBusinessLogic;
-
- @Autowired
- private SoftwareInformationBusinessLogic softwareInformationBusinessLogic;
-
- public LifecycleBusinessLogic getLifecycleBusinessLogic() {
- return lifecycleBusinessLogic;
- }
+ private static final String DELETE_RESOURCE = "Delete Resource";
+ private static final String IN_RESOURCE = " in resource {} ";
+ private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
+ private static final String INITIAL_VERSION = "0.1";
+ private static final Logger log = Logger.getLogger(ResourceBusinessLogic.class);
+ private static final String CERTIFICATION_ON_IMPORT = "certification on import";
+ private static final String CREATE_RESOURCE = "Create Resource";
+ private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
+ private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
+ private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
+ private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
+ private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {} in resource {} ";
+ private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ResourceBusinessLogic.class.getName());
+ private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
+ private final ResourceImportManager resourceImportManager;
+ private final InputsBusinessLogic inputsBusinessLogic;
+ private final OutputsBusinessLogic outputsBusinessLogic;
+ private final CompositionBusinessLogic compositionBusinessLogic;
+ private final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic;
+ private final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
+ private final MergeInstanceUtils mergeInstanceUtils;
+ private final UiComponentDataConverter uiComponentDataConverter;
+ private final CsarBusinessLogic csarBusinessLogic;
+ private final PropertyBusinessLogic propertyBusinessLogic;
+ private final PolicyBusinessLogic policyBusinessLogic;
+ private IInterfaceLifecycleOperation interfaceTypeOperation;
+ private LifecycleBusinessLogic lifecycleBusinessLogic;
+ @Autowired
+ private ICapabilityTypeOperation capabilityTypeOperation;
+ @Autowired
+ private TopologyComparator topologyComparator;
+ @Autowired
+ private ComponentValidator componentValidator;
+ @Autowired
+ private PropertyDataValueMergeBusinessLogic propertyDataValueMergeBusinessLogic;
+ @Autowired
+ private SoftwareInformationBusinessLogic softwareInformationBusinessLogic;
+
+ @Autowired
+ public ResourceBusinessLogic(final IElementOperation elementDao, final IGroupOperation groupOperation,
+ final IGroupInstanceOperation groupInstanceOperation, final IGroupTypeOperation groupTypeOperation,
+ final GroupBusinessLogic groupBusinessLogic, final InterfaceOperation interfaceOperation,
+ final InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+ final ArtifactsBusinessLogic artifactsBusinessLogic,
+ final ComponentInstanceBusinessLogic componentInstanceBusinessLogic,
+ final @Lazy ResourceImportManager resourceImportManager, final InputsBusinessLogic inputsBusinessLogic,
+ final OutputsBusinessLogic outputsBusinessLogic, final CompositionBusinessLogic compositionBusinessLogic,
+ final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic,
+ final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic,
+ final MergeInstanceUtils mergeInstanceUtils, final UiComponentDataConverter uiComponentDataConverter,
+ final CsarBusinessLogic csarBusinessLogic, final ArtifactsOperations artifactToscaOperation,
+ final PropertyBusinessLogic propertyBusinessLogic, final ComponentContactIdValidator componentContactIdValidator,
+ final ComponentNameValidator componentNameValidator, final ComponentTagsValidator componentTagsValidator,
+ final ComponentValidator componentValidator, final ComponentIconValidator componentIconValidator,
+ final ComponentProjectCodeValidator componentProjectCodeValidator,
+ final ComponentDescriptionValidator componentDescriptionValidator, final PolicyBusinessLogic policyBusinessLogic) {
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic, interfaceOperation,
+ interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, componentContactIdValidator, componentNameValidator,
+ componentTagsValidator, componentValidator, componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator);
+ this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
+ this.resourceImportManager = resourceImportManager;
+ this.inputsBusinessLogic = inputsBusinessLogic;
+ this.outputsBusinessLogic = outputsBusinessLogic;
+ this.compositionBusinessLogic = compositionBusinessLogic;
+ this.resourceDataMergeBusinessLogic = resourceDataMergeBusinessLogic;
+ this.csarArtifactsAndGroupsBusinessLogic = csarArtifactsAndGroupsBusinessLogic;
+ this.mergeInstanceUtils = mergeInstanceUtils;
+ this.uiComponentDataConverter = uiComponentDataConverter;
+ this.csarBusinessLogic = csarBusinessLogic;
+ this.propertyBusinessLogic = propertyBusinessLogic;
+ this.policyBusinessLogic = policyBusinessLogic;
+ }
+
+ static <T> Either<T, RuntimeException> rollbackWithEither(final JanusGraphDao janusGraphDao, final ActionStatus actionStatus,
+ final String... params) {
+ if (janusGraphDao != null) {
+ janusGraphDao.rollback();
+ }
+ return Either.right(new ByActionStatusComponentException(actionStatus, params));
+ }
+
+ public LifecycleBusinessLogic getLifecycleBusinessLogic() {
+ return lifecycleBusinessLogic;
+ }
@Autowired
public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) {
this.lifecycleBusinessLogic = lifecycleBusinessLogic;
}
- @VisibleForTesting
- protected void setComponentValidator(ComponentValidator componentValidator) {
- this.componentValidator = componentValidator;
- }
+ @VisibleForTesting
+ protected void setComponentValidator(ComponentValidator componentValidator) {
+ this.componentValidator = componentValidator;
+ }
- public IElementOperation getElementDao() {
- return elementDao;
- }
+ public IElementOperation getElementDao() {
+ return elementDao;
+ }
- public void setElementDao(IElementOperation elementDao) {
- this.elementDao = elementDao;
- }
+ public void setElementDao(IElementOperation elementDao) {
+ this.elementDao = elementDao;
+ }
- public UserBusinessLogic getUserAdmin() {
- return this.userAdmin;
- }
+ public UserBusinessLogic getUserAdmin() {
+ return this.userAdmin;
+ }
- @Autowired
- @Override
- public void setUserAdmin(UserBusinessLogic userAdmin) {
- this.userAdmin = userAdmin;
- }
+ @Autowired
+ @Override
+ public void setUserAdmin(UserBusinessLogic userAdmin) {
+ this.userAdmin = userAdmin;
+ }
- public ComponentsUtils getComponentsUtils() {
- return this.componentsUtils;
- }
+ public ComponentsUtils getComponentsUtils() {
+ return this.componentsUtils;
+ }
- @Autowired
- @Override
- public void setComponentsUtils(ComponentsUtils componentsUtils) {
- this.componentsUtils = componentsUtils;
- }
+ @Autowired
+ @Override
+ public void setComponentsUtils(ComponentsUtils componentsUtils) {
+ this.componentsUtils = componentsUtils;
+ }
- public ArtifactsBusinessLogic getArtifactsManager() {
- return artifactsBusinessLogic;
- }
+ public ArtifactsBusinessLogic getArtifactsManager() {
+ return artifactsBusinessLogic;
+ }
- public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
- this.artifactsBusinessLogic = artifactsManager;
- }
+ public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
+ this.artifactsBusinessLogic = artifactsManager;
+ }
- public ApplicationDataTypeCache getApplicationDataTypeCache() {
- return applicationDataTypeCache;
- }
+ public ApplicationDataTypeCache getApplicationDataTypeCache() {
+ return applicationDataTypeCache;
+ }
@Autowired
- @Override
+ @Override
public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
this.applicationDataTypeCache = applicationDataTypeCache;
}
@@ -347,1289 +335,1058 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
this.interfaceTypeOperation = interfaceTypeOperation;
}
- /**
- * the method returns a list of all the resources that are certified, the
- * returned resources are only abstract or only none abstract according to
- * the given param
- *
- * @param getAbstract
- * @param userId
- * TODO
- * @return
- */
- public List<Resource> getAllCertifiedResources(boolean getAbstract, HighestFilterEnum highestFilter,
- String userId) {
- User user = validateUserExists(userId);
- Boolean isHighest = null;
- switch (highestFilter) {
- case ALL:
- break;
- case HIGHEST_ONLY:
- isHighest = true;
- break;
- case NON_HIGHEST_ONLY:
- isHighest = false;
- break;
- default:
- break;
- }
- Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade
- .getAllCertifiedResources(getAbstract, isHighest);
-
- if (getResponse.isRight()) {
- throw new StorageException(getResponse.right()
- .value());
- }
-
- return getResponse.left()
- .value();
- }
-
- public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName,
- ResourceTypeEnum resourceTypeEnum, String userId) {
-
- validateUserExists(userId);
-
- Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
- .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
- // DE242223
+ /**
+ * the method returns a list of all the resources that are certified, the returned resources are only abstract or only none abstract according to
+ * the given param
+ *
+ * @param getAbstract
+ * @param userId TODO
+ * @return
+ */
+ public List<Resource> getAllCertifiedResources(boolean getAbstract, HighestFilterEnum highestFilter, String userId) {
+ User user = validateUserExists(userId);
+ Boolean isHighest = null;
+ switch (highestFilter) {
+ case ALL:
+ break;
+ case HIGHEST_ONLY:
+ isHighest = true;
+ break;
+ case NON_HIGHEST_ONLY:
+ isHighest = false;
+ break;
+ default:
+ break;
+ }
+ Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade.getAllCertifiedResources(getAbstract, isHighest);
+ if (getResponse.isRight()) {
+ throw new StorageException(getResponse.right().value());
+ }
+ return getResponse.left().value();
+ }
+
+ public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName, ResourceTypeEnum resourceTypeEnum,
+ String userId) {
+ validateUserExists(userId);
+ Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
+ .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
+ // DE242223
janusGraphDao.commit();
+ if (dataModelResponse.isLeft()) {
+ Map<String, Boolean> result = new HashMap<>();
+ result.put("isValid", dataModelResponse.left().value());
+ log.debug("validation was successfully performed.");
+ return Either.left(result);
+ }
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
+ return Either.right(responseFormat);
+ }
+
+ public Resource createResource(Resource resource, AuditingActionEnum auditingAction, User user, Map<String, byte[]> csarUIPayload,
+ String payloadName) {
+ validateResourceBeforeCreate(resource, user, false);
+ String csarUUID = payloadName == null ? resource.getCsarUUID() : payloadName;
+ loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
+ "Starting to create resource from CSAR by user {} ", user.getUserId());
+ if (StringUtils.isNotEmpty(csarUUID)) {
+ csarBusinessLogic.validateCsarBeforeCreate(resource, auditingAction, user, csarUUID);
+ log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
+ Resource createResourceFromCsar = createResourceFromCsar(resource, user, csarUIPayload, csarUUID);
+ return updateCatalog(createResourceFromCsar, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Resource) r).left().value();
+ }
+ final Resource createResourceByDao = createResourceByDao(resource, user, auditingAction, false, false);
+ return updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Resource) r).left().value();
+ }
+
+ public Resource validateAndUpdateResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload, String payloadName,
+ String resourceUniqueId) {
+ String csarUUID = payloadName;
+ String csarVersion = null;
+ Resource updatedResource = null;
+ if (payloadName == null) {
+ csarUUID = resource.getCsarUUID();
+ csarVersion = resource.getCsarVersion();
+ }
+ if (csarUUID != null && !csarUUID.isEmpty()) {
+ Resource oldResource = getResourceByUniqueId(resourceUniqueId);
+ validateCsarUuidMatching(oldResource, resource, csarUUID, resourceUniqueId, user);
+ validateCsarIsNotAlreadyUsed(oldResource, resource, csarUUID, user);
+ if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
+ overrideImmutableMetadata(oldResource, resource);
+ }
+ validateResourceBeforeCreate(resource, user, false);
+ String oldCsarVersion = oldResource != null ? oldResource.getCsarVersion() : null;
+ log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID, resourceUniqueId);
+ // (on boarding flow): If the update includes same csarUUID and
+
+ // same csarVersion as already in the VF - no need to import the
+
+ // csar (do only metadata changes if there are).
+ if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
+ updatedResource = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, false);
+ } else {
+ updatedResource = updateResourceFromCsar(oldResource, resource, user, AuditingActionEnum.UPDATE_RESOURCE_METADATA, false,
+ csarUIPayload, csarUUID);
+ }
+ } else {
+ log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID, resource.getName());
+ componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE);
+ throw new ByActionStatusComponentException(ActionStatus.MISSING_CSAR_UUID, resource.getName());
+ }
+ return updatedResource;
+ }
+
+ private void validateCsarIsNotAlreadyUsed(Resource oldResource, Resource resource, String csarUUID, User user) {
+ // (on boarding flow): If the update includes a csarUUID: verify this
+
+ // csarUUID is not in use by another VF, If it is - use same error as
+
+ // above:
+
+ // "Error: The VSP with UUID %1 was already imported for VF %2. Please
+
+ // select another or update the existing VF." %1 - csarUUID, %2 - VF
+
+ // name
+ Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade
+ .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
+ if (resourceLinkedToCsarRes.isRight()) {
+ if (StorageOperationStatus.NOT_FOUND != resourceLinkedToCsarRes.right().value()) {
+ log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID, resource.getSystemName());
+ throw new StorageException(resourceLinkedToCsarRes.right().value());
+ }
+ } else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId()) && !resourceLinkedToCsarRes.left().value()
+ .getName().equals(oldResource.getName())) {
+ ResponseFormat errorResponse = componentsUtils
+ .getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left().value().getName());
+ componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
+ throw new ByActionStatusComponentException(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left().value().getName());
+ }
+ }
+
+ private void validateCsarUuidMatching(Resource resource, Resource oldResource, String csarUUID, String resourceUniqueId, User user) {
+ // (on boarding flow): If the update includes csarUUID which is
+
+ // different from the csarUUID of the VF - fail with
+
+ // error: "Error: Resource %1 cannot be updated using since it is linked
+
+ // to a different VSP" %1 - VF name
+ String oldCsarUUID = oldResource.getCsarUUID();
+ if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
+ log.debug("Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}",
+ resourceUniqueId, csarUUID, oldCsarUUID);
+ ResponseFormat errorResponse = componentsUtils
+ .getResponseFormat(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
+ componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
+ throw new ByActionStatusComponentException(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
+ }
+ }
+
+ private Resource getResourceByUniqueId(String resourceUniqueId) {
+ Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade.getToscaFullElement(resourceUniqueId);
+ if (oldResourceRes.isRight()) {
+ log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId, oldResourceRes.right().value());
+ throw new StorageException(oldResourceRes.right().value());
+ }
+ return oldResourceRes.left().value();
+ }
+
+ private void overrideImmutableMetadata(Resource oldResource, Resource resource) {
+ resource.setName(oldResource.getName());
+ resource.setIcon(oldResource.getIcon());
+ resource.setTags(oldResource.getTags());
+ resource.setCategories(oldResource.getCategories());
+ resource.setDerivedFrom(oldResource.getDerivedFrom());
+ }
- if (dataModelResponse.isLeft()) {
- Map<String, Boolean> result = new HashMap<>();
- result.put("isValid", dataModelResponse.left()
- .value());
- log.debug("validation was successfully performed.");
- return Either.left(result);
- }
-
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right()
- .value()));
-
- return Either.right(responseFormat);
- }
-
- public Resource createResource(Resource resource, AuditingActionEnum auditingAction, User user,
- Map<String, byte[]> csarUIPayload, String payloadName) {
- validateResourceBeforeCreate(resource, user, false);
- String csarUUID = payloadName == null ? resource.getCsarUUID() : payloadName;
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Starting to create resource from CSAR by user {} ", user.getUserId());
- if (StringUtils.isNotEmpty(csarUUID)) {
- csarBusinessLogic.validateCsarBeforeCreate(resource, auditingAction, user, csarUUID);
- log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
-
- Resource createResourceFromCsar = createResourceFromCsar(resource, user, csarUIPayload, csarUUID);
- return updateCatalog(createResourceFromCsar, ChangeTypeEnum.LIFECYCLE).left()
- .map(r -> (Resource) r)
- .left()
- .value();
- }
-
- final Resource createResourceByDao = createResourceByDao(resource, user, auditingAction, false, false);
- return updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left()
- .map(r -> (Resource) r)
- .left()
- .value();
- }
-
- public Resource validateAndUpdateResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload,
- String payloadName, String resourceUniqueId) {
- String csarUUID = payloadName;
- String csarVersion = null;
- Resource updatedResource = null;
- if (payloadName == null) {
- csarUUID = resource.getCsarUUID();
- csarVersion = resource.getCsarVersion();
- }
- if (csarUUID != null && !csarUUID.isEmpty()) {
- Resource oldResource = getResourceByUniqueId(resourceUniqueId);
- validateCsarUuidMatching(oldResource, resource, csarUUID, resourceUniqueId, user);
- validateCsarIsNotAlreadyUsed(oldResource, resource, csarUUID, user);
- if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
- overrideImmutableMetadata(oldResource, resource);
- }
- validateResourceBeforeCreate(resource, user, false);
- String oldCsarVersion = oldResource != null ? oldResource.getCsarVersion() : null;
- log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID,
- resourceUniqueId);
- // (on boarding flow): If the update includes same csarUUID and
- // same csarVersion as already in the VF - no need to import the
- // csar (do only metadata changes if there are).
- if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
- updatedResource = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, false);
- } else {
- updatedResource = updateResourceFromCsar(oldResource, resource, user,
- AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, csarUIPayload, csarUUID);
- }
- } else {
- log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID,
- resource.getName());
- componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE);
- throw new ByActionStatusComponentException(ActionStatus.MISSING_CSAR_UUID, resource.getName());
- }
- return updatedResource;
- }
-
- private void validateCsarIsNotAlreadyUsed(Resource oldResource, Resource resource, String csarUUID, User user) {
- // (on boarding flow): If the update includes a csarUUID: verify this
- // csarUUID is not in use by another VF, If it is - use same error as
- // above:
- // "Error: The VSP with UUID %1 was already imported for VF %2. Please
- // select another or update the existing VF." %1 - csarUUID, %2 - VF
- // name
- Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade
- .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
- if (resourceLinkedToCsarRes.isRight()) {
- if (StorageOperationStatus.NOT_FOUND != resourceLinkedToCsarRes.right().value()) {
- log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID,
- resource.getSystemName());
- throw new StorageException(resourceLinkedToCsarRes.right()
- .value());
- }
- } else if (!resourceLinkedToCsarRes.left()
- .value()
- .getUniqueId()
- .equals(oldResource.getUniqueId())
- && !resourceLinkedToCsarRes.left()
- .value()
- .getName()
- .equals(oldResource.getName())) {
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
- resourceLinkedToCsarRes.left()
- .value()
- .getName());
- componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
- throw new ByActionStatusComponentException(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left()
- .value()
- .getName());
- }
- }
-
- private void validateCsarUuidMatching(Resource resource, Resource oldResource, String csarUUID,
- String resourceUniqueId, User user) {
- // (on boarding flow): If the update includes csarUUID which is
- // different from the csarUUID of the VF - fail with
- // error: "Error: Resource %1 cannot be updated using since it is linked
- // to a different VSP" %1 - VF name
- String oldCsarUUID = oldResource.getCsarUUID();
- if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
- log.debug(
- "Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}",
- resourceUniqueId, csarUUID, oldCsarUUID);
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(
- ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
- componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
- throw new ByActionStatusComponentException(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID,
- oldCsarUUID);
- }
- }
-
- private Resource getResourceByUniqueId(String resourceUniqueId) {
- Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade
- .getToscaFullElement(resourceUniqueId);
- if (oldResourceRes.isRight()) {
- log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId,
- oldResourceRes.right()
- .value());
- throw new StorageException(oldResourceRes.right()
- .value());
- }
- return oldResourceRes.left()
- .value();
- }
-
- private void overrideImmutableMetadata(Resource oldResource, Resource resource) {
- resource.setName(oldResource.getName());
- resource.setIcon(oldResource.getIcon());
- resource.setTags(oldResource.getTags());
- resource.setCategories(oldResource.getCategories());
- resource.setDerivedFrom(oldResource.getDerivedFrom());
- }
-
- private Resource updateResourceFromCsar(Resource oldResource, Resource newResource, User user,
- AuditingActionEnum updateResource, boolean inTransaction, Map<String, byte[]> csarUIPayload,
- String csarUUID) {
- Resource updatedResource = null;
- validateLifecycleState(oldResource, user);
- String lockedResourceId = oldResource.getUniqueId();
- List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
- CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(newResource, oldResource, user, csarUIPayload, csarUUID);
- lockComponent(lockedResourceId, oldResource, "update Resource From Csar");
-
- Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
-
- Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
- nodeTypesInfo, csarInfo, oldResource);
- if (findNodeTypesArtifactsToHandleRes.isRight()) {
- log.debug("failed to find node types for update with artifacts during import csar {}. ",
- csarInfo.getCsarUUID());
- throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right()
- .value());
- }
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes
- .left()
- .value();
- try {
- updatedResource = updateResourceFromYaml(oldResource, newResource, updateResource, createdArtifacts,
- csarInfo.getMainTemplateName(), csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo,
- nodeTypesArtifactsToHandle, null, false);
-
- } catch (ComponentException | StorageException e) {
- rollback(inTransaction, newResource, createdArtifacts, null);
- throw e;
- }
- finally {
+ private Resource updateResourceFromCsar(Resource oldResource, Resource newResource, User user, AuditingActionEnum updateResource,
+ boolean inTransaction, Map<String, byte[]> csarUIPayload, String csarUUID) {
+ Resource updatedResource = null;
+ validateLifecycleState(oldResource, user);
+ String lockedResourceId = oldResource.getUniqueId();
+ List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
+ CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(newResource, oldResource, user, csarUIPayload, csarUUID);
+ lockComponent(lockedResourceId, oldResource, "update Resource From Csar");
+ Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
+ Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
+ nodeTypesInfo, csarInfo, oldResource);
+ if (findNodeTypesArtifactsToHandleRes.isRight()) {
+ log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID());
+ throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value());
+ }
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes.left()
+ .value();
+ try {
+ updatedResource = updateResourceFromYaml(oldResource, newResource, updateResource, createdArtifacts, csarInfo.getMainTemplateName(),
+ csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false);
+ } catch (ComponentException | StorageException e) {
+ rollback(inTransaction, newResource, createdArtifacts, null);
+ throw e;
+ } finally {
janusGraphDao.commit();
- log.debug("unlock resource {}", lockedResourceId);
- graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
- }
- return updatedResource;
-
- }
-
- private void validateLifecycleState(Resource oldResource, User user) {
- if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT == oldResource.getLifecycleState()
- && !oldResource.getLastUpdaterUserId()
- .equals(user.getUserId())) {
- log.debug(
- "#validateLifecycleState - Current user is not last updater, last updater userId: {}, current user userId: {}",
- oldResource.getLastUpdaterUserId(), user.getUserId());
- throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION);
- }
- }
-
- private Resource updateResourceFromYaml(Resource oldResource, Resource newResource, AuditingActionEnum actionEnum,
- List<ArtifactDefinition> createdArtifacts, String yamlFileName, String yamlFileContent, CsarInfo csarInfo,
- Map<String, NodeTypeInfo> nodeTypesInfo,
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
- String nodeName, boolean isNested) {
- boolean inTransaction = true;
- boolean shouldLock = false;
- Resource preparedResource = null;
- ParsedToscaYamlInfo uploadComponentInstanceInfoMap;
- try {
- uploadComponentInstanceInfoMap = csarBusinessLogic.getParsedToscaYamlInfo(yamlFileContent, yamlFileName,
- nodeTypesInfo, csarInfo, nodeName, oldResource);
- Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
+ log.debug("unlock resource {}", lockedResourceId);
+ graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
+ }
+ return updatedResource;
+ }
+
+ private void validateLifecycleState(Resource oldResource, User user) {
+ if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT == oldResource.getLifecycleState() && !oldResource.getLastUpdaterUserId()
+ .equals(user.getUserId())) {
+ log.debug("#validateLifecycleState - Current user is not last updater, last updater userId: {}, current user userId: {}",
+ oldResource.getLastUpdaterUserId(), user.getUserId());
+ throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION);
+ }
+ }
+
+ private Resource updateResourceFromYaml(Resource oldResource, Resource newResource, AuditingActionEnum actionEnum,
+ List<ArtifactDefinition> createdArtifacts, String yamlFileName, String yamlFileContent, CsarInfo csarInfo,
+ Map<String, NodeTypeInfo> nodeTypesInfo,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
+ String nodeName, boolean isNested) {
+ boolean inTransaction = true;
+ boolean shouldLock = false;
+ Resource preparedResource = null;
+ ParsedToscaYamlInfo uploadComponentInstanceInfoMap;
+ try {
+ uploadComponentInstanceInfoMap = csarBusinessLogic
+ .getParsedToscaYamlInfo(yamlFileContent, yamlFileName, nodeTypesInfo, csarInfo, nodeName, oldResource);
+ Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
if (MapUtils.isEmpty(instances) && newResource.getResourceType() != ResourceTypeEnum.PNF) {
throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
}
- preparedResource = updateExistingResourceByImport(newResource, oldResource, csarInfo.getModifier(),
- inTransaction, shouldLock, isNested).left;
- log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
- handleResourceGenericType(preparedResource);
- handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle,
- createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
- preparedResource = createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
- Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>();
- preparedResource = createResourceInstances(yamlFileName, preparedResource, oldResource, instances, csarInfo.getCreatedNodes(), existingNodeTypesByResourceNames);
- preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, oldResource, instances, existingNodeTypesByResourceNames);
- } catch (ComponentException e) {
- ResponseFormat responseFormat = e.getResponseFormat() == null
- ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
- log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName,
- responseFormat);
- componentsUtils.auditResource(responseFormat, csarInfo.getModifier(),
- preparedResource == null ? oldResource : preparedResource, actionEnum);
- throw e;
- } catch (StorageException e) {
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
- log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName,
- responseFormat);
- componentsUtils.auditResource(responseFormat, csarInfo.getModifier(),
- preparedResource == null ? oldResource : preparedResource, actionEnum);
- throw e;
- }
- Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
- .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(),
- preparedResource.getSystemName());
- if (validateUpdateVfGroupNamesRes.isRight()) {
-
- throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right()
- .value());
- }
- // add groups to newResource
- Map<String, GroupDefinition> groups;
-
- if (!validateUpdateVfGroupNamesRes.left()
- .value()
- .isEmpty()) {
- groups = validateUpdateVfGroupNamesRes.left()
- .value();
- } else {
- groups = uploadComponentInstanceInfoMap.getGroups();
- }
- handleGroupsProperties(preparedResource, groups);
- Either<Boolean, ActionStatus> isTopologyChanged = topologyComparator.isTopologyChanged(oldResource, preparedResource);
-
- preparedResource = updateGroupsOnResource(preparedResource, groups);
-
- NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
- nodeTypesArtifactsToHandle);
-
- Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE,
- createdArtifacts, yamlFileName, csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts,
- inTransaction, shouldLock);
- if (updateArtifactsEither.isRight()) {
- log.debug("failed to update artifacts {}", updateArtifactsEither.right()
- .value());
- throw new ByResponseFormatComponentException(updateArtifactsEither.right()
- .value());
- }
- preparedResource = getResourceWithGroups(updateArtifactsEither.left()
- .value()
- .getUniqueId());
-
- updateGroupsName(oldResource, preparedResource, isTopologyChanged.left().value());
- updateResourceInstancesNames(oldResource, csarInfo, preparedResource, isTopologyChanged.left().value());
-
- final String preparedResourceId = preparedResource != null ? preparedResource.getUniqueId() : "";
- preparedResource = getResourceWithGroups(preparedResourceId);
-
- updateVolumeGroup(preparedResource);
-
- ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldResource, preparedResource);
- if (mergingPropsAndInputsStatus != ActionStatus.OK) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus,
- preparedResource);
- throw new ByResponseFormatComponentException(responseFormat);
- }
- compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier()
- .getUserId());
- return preparedResource;
- }
-
- protected void updateVolumeGroup(Resource preparedResource) {
- List<GroupDefinition> groups = preparedResource.safeGetGroups();
- for (GroupDefinition group : groups) {
- Map<String, ArtifactDefinition> createdNewArtifacts = preparedResource.getDeploymentArtifacts();
- if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
- List<PropertyDataDefinition> volumePropList = group.getProperties().stream().filter(p -> "volume_group".equals(p.getName())).collect(Collectors.toList());
- if (!volumePropList.isEmpty()) {
- PropertyDataDefinition volumeProp = volumePropList.get(0);
- if (volumeProp != null) {
- boolean isVolumeGroup = isVolumeGroup(group.getArtifacts(), new ArrayList<>(createdNewArtifacts.values()));
-
- if (!volumePropList.get(0).getValue().equals(String.valueOf(isVolumeGroup))) {
- volumeProp.setValue(String.valueOf(isVolumeGroup));
- volumeProp.setDefaultValue(String.valueOf(isVolumeGroup));
- }
- }
- }
- }
- }
- }
-
- private void updateGroupsName(Resource oldResource, Resource preparedResource, boolean isTopologyChanged) {
- if (oldResource == null || preparedResource == null) {
- log.debug("Failed to update groups name : oldResource or preparedResource is null");
- } else if (CollectionUtils.isNotEmpty(oldResource.getGroups())
- && CollectionUtils.isNotEmpty(preparedResource.getGroups())) {
- Map<String, String> oldGroups = oldResource.getGroups()
- .stream()
- .collect(toMap(GroupDataDefinition::getInvariantName, GroupDataDefinition::getName));
-
- List<GroupDefinition> updatedGroups = preparedResource.getGroups()
- .stream()
- .filter(group -> oldGroups.containsKey(group.getInvariantName()) && !group.getName()
- .equals(oldGroups.get(group.getInvariantName())))
- .collect(toList());
-
- if (CollectionUtils.isNotEmpty(updatedGroups)) {
- if (isTopologyChanged) {
- updatedGroups.stream().filter(group -> !group.isVspOriginated())
- .forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
- } else {
- updatedGroups.forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
- }
- groupBusinessLogic.updateGroups(preparedResource, updatedGroups, false);
- }
- }
- }
-
- private void updateResourceInstancesNames(Resource oldResource, CsarInfo csarInfo, Resource preparedResource,
- boolean isTopologyChanged) {
- if (oldResource == null || preparedResource == null) {
- log.debug("Failed to update resource instances names : oldResource or preparedResource is null");
- } else {
- if (CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) {
- Map<String, String> oldInstances = oldResource.getComponentInstances()
- .stream()
- .collect(toMap(ComponentInstance::getInvariantName, ComponentInstance::getName));
- List<ComponentInstance> updatedInstances = preparedResource.getComponentInstances()
- .stream()
- .filter(i -> oldInstances.containsKey(i.getInvariantName()) && !i.getName()
- .equals(oldInstances.get(i.getInvariantName())))
- .collect(toList());
- if (CollectionUtils.isNotEmpty(updatedInstances)) {
- if (isTopologyChanged) {
- updatedInstances.stream().filter(i -> !i.isCreatedFromCsar())
- .forEach(i -> i.setName(oldInstances.get(i.getInvariantName())));
- } else {
- updatedInstances.forEach(i -> i.setName(oldInstances.get(i.getInvariantName())));
- }
- }
- }
-
- componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME,
- null, preparedResource.getUniqueId(), csarInfo.getModifier()
- .getUserId(),
- preparedResource.getComponentInstances(), false);
- }
- }
-
- private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation,
- List<ArtifactDefinition> createdArtifacts, String yamlFileName, CsarInfo csarInfo,
- Resource preparedResource, NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts,
- boolean inTransaction, boolean shouldLock) {
-
- String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
- Resource resource = preparedResource;
-
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
- .getNodeTypesArtifactsToHandle();
- if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) {
- if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null
- && !nodeTypesArtifactsToHandle.get(nodeName)
- .isEmpty()) {
- Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = handleNodeTypeArtifacts(
- preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts,
- csarInfo.getModifier(), inTransaction, true);
- if (handleNodeTypeArtifactsRes.isRight()) {
- return Either.right(handleNodeTypeArtifactsRes.right()
- .value());
- }
- }
- } else {
- Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource,
- csarInfo, createdArtifacts,
- new ArtifactOperationInfo(false, false, operation), shouldLock,
- inTransaction);
- log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
- if (createdCsarArtifactsEither.isRight()) {
- return createdCsarArtifactsEither;
-
- }
- resource = createdCsarArtifactsEither.left()
- .value();
- }
- return Either.left(resource);
- }
-
- private Resource handleResourceGenericType(Resource resource) {
- Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
- if (resource.shouldGenerateInputs()) {
- generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
- }
- return genericResource;
- }
-
- private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
- final Map<String, NodeTypeInfo> nodeTypesInfo, final CsarInfo csarInfo, final Resource oldResource) {
-
- final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
- Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat>
- nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle);
-
- try {
- final Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils
- .extractVfcsArtifactsFromCsar(csarInfo.getCsar());
- final Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(
- nodeTypesInfo, oldResource.getName(), csarInfo);
- log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ",
- oldResource.getName(), csarInfo.getCsarUUID());
- extractedVfcToscaNames.forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo,
- nodeTypesArtifactsToHandle, oldResource, extractedVfcsArtifacts, namespace, vfcToscaNames));
- } catch (Exception e) {
- final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
- log.debug("Exception occurred when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
- }
- return nodeTypesArtifactsToHandleRes;
- }
-
- private void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo,
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
- Resource resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace,
- ImmutablePair<String, String> vfcToscaNames) {
-
- EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
- log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
- Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(),
- null);
- if (!isEmpty(extractedVfcsArtifacts)) {
- List<ArtifactDefinition> currArtifacts = new ArrayList<>();
- if (extractedVfcsArtifacts.containsKey(namespace)) {
- handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
- }
- curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
- } else if (curNodeType != null) {
- // delete all artifacts if have not received artifacts from
- // csar
- curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
- List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
- // delete all informational artifacts
- artifactsToDelete.addAll(curNodeType.getArtifacts()
- .values()
- .stream()
- .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
- .collect(toList()));
- // delete all deployment artifacts
- artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts()
- .values());
- if (!artifactsToDelete.isEmpty()) {
- curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
- }
- }
- if (isNotEmpty(curNodeTypeArtifactsToHandle)) {
- nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
- }
- }
-
- private Resource findVfcResource(CsarInfo csarInfo, Resource resource, String currVfcToscaName,
- String previousVfcToscaName, StorageOperationStatus status) {
- if (status != null && status != StorageOperationStatus.NOT_FOUND) {
- log.debug("Error occurred during fetching node type with tosca name {}, error: {}", currVfcToscaName,
- status);
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
- componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
- AuditingActionEnum.CREATE_RESOURCE);
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
- } else if (StringUtils.isNotEmpty(currVfcToscaName)) {
- return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName)
- .left()
- .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
- }
- return null;
- }
-
- private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(Resource curNodeType,
- List<ArtifactDefinition> extractedArtifacts) {
-
- try {
- List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
- List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
- List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
- processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate,
- artifactsToDelete, collectExistingArtifacts(curNodeType));
- return putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
- } catch (Exception e) {
- log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
- throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
- }
- }
-
- private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(
- List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
- List<ArtifactDefinition> artifactsToDelete) {
- EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
- if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
- nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
- if (!artifactsToUpload.isEmpty()) {
- nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
- }
- if (!artifactsToUpdate.isEmpty()) {
- nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
- }
- if (!artifactsToDelete.isEmpty()) {
- nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
- }
- }
- return nodeTypeArtifactsToHandle;
- }
-
- private void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts,
- List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
- List<ArtifactDefinition> artifactsToDelete, Map<String, ArtifactDefinition> existingArtifacts) {
- if (!existingArtifacts.isEmpty()) {
- extractedArtifacts.stream()
- .forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
- artifactsToDelete.addAll(existingArtifacts.values());
- }
- }
-
- private void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload,
- List<ArtifactDefinition> artifactsToUpdate, Map<String, ArtifactDefinition> existingArtifacts,
- ArtifactDefinition currNewArtifact) {
- Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values()
- .stream()
- .filter(a -> a.getArtifactName()
- .equals(currNewArtifact.getArtifactName()))
- .findFirst();
- if (foundArtifact.isPresent()) {
- if (foundArtifact.get()
- .getArtifactType()
- .equals(currNewArtifact.getArtifactType())) {
- updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
- existingArtifacts.remove(foundArtifact.get()
- .getArtifactLabel());
- artifactsToUpload.remove(currNewArtifact);
- } else {
- log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
- throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
- currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), foundArtifact.get()
- .getArtifactType());
- }
- }
- }
-
- private void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact,
- ArtifactDefinition foundArtifact) {
- if (!foundArtifact.getArtifactChecksum()
- .equals(currNewArtifact.getArtifactChecksum())) {
- foundArtifact.setPayload(currNewArtifact.getPayloadData());
- foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
- foundArtifact.setArtifactChecksum(
- GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
- artifactsToUpdate.add(foundArtifact);
- }
- }
-
- private Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
- Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
- if (curNodeType == null) {
- return existingArtifacts;
- }
- if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
- existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
- }
- if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
- existingArtifacts.putAll(curNodeType.getArtifacts()
- .entrySet()
- .stream()
- .filter(e -> e.getValue()
- .getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
- .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
- }
- return existingArtifacts;
- }
-
- /**
- * Changes resource life cycle state to checked out
- *
- * @param resource
- * @param user
- * @param inTransaction
- * @return
- */
- private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
- Either<Resource, ResponseFormat> checkoutResourceRes;
- try {
- if (!resource.getComponentMetadataDefinition()
- .getMetadataDataDefinition()
- .getState()
- .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
- log.debug(
- "************* Going to change life cycle state of resource {} to not certified checked out. ",
- resource.getName());
- Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(
- resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
- new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
- LifecycleChanceActionEnum.CREATE_FROM_CSAR),
- inTransaction, true);
- if (checkoutRes.isRight()) {
- log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ",
- resource.getComponentType()
- .getNodeType(),
- resource.getUniqueId(), checkoutRes.right()
- .value()
- .getStatus());
- checkoutResourceRes = Either.right(checkoutRes.right()
- .value());
- } else {
- checkoutResourceRes = Either.left((Resource) checkoutRes.left()
- .value());
- }
- } else {
- checkoutResourceRes = Either.left(resource);
- }
- } catch (Exception e) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- checkoutResourceRes = Either.right(responseFormat);
- log.debug("Exception occurred when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(),
- e);
- }
- return checkoutResourceRes;
- }
-
- /**
- * Handles Artifacts of NodeType
- *
- * @param nodeTypeResource
- * @param nodeTypeArtifactsToHandle
- * @param user
- * @param inTransaction
- * @return
- */
- public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
- Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
- List<ArtifactDefinition> createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) {
- List<ArtifactDefinition> handleNodeTypeArtifactsRequestRes;
- Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
- Either<Resource, ResponseFormat> changeStateResponse;
- try {
- changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
- if (changeStateResponse.isRight()) {
- return Either.right(changeStateResponse.right()
- .value());
- }
- nodeTypeResource = changeStateResponse.left()
- .value();
-
- List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
- log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
- for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
- .entrySet()) {
- ArtifactOperationEnum curOperation = curOperationEntry.getKey();
- List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
- if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
- log.debug("************* Going to {} artifact to vfc {}", curOperation.name(),
- nodeTypeResource.getName());
- handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
- .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user,
- createdArtifacts, new ArtifactOperationInfo(false,
- ignoreLifecycleState, curOperation),
- false, inTransaction);
- if (ArtifactOperationEnum.isCreateOrLink(curOperation)) {
- createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
- }
- handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
- }
- }
- if (handleNodeTypeArtifactsRes == null) {
- handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
- }
- } catch (Exception e) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- handleNodeTypeArtifactsRes = Either.right(responseFormat);
- log.debug("Exception occurred when handleVfcArtifacts, error is:{}", e.getMessage(), e);
- }
- return handleNodeTypeArtifactsRes;
- }
-
- private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(final Map<String, NodeTypeInfo> nodeTypesInfo,
- final String vfResourceName,
- final CsarInfo csarInfo) {
- final Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
-
- final Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
- if (!nodes.isEmpty()) {
- final Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
- while (nodesNameEntry.hasNext()) {
- final Entry<String, Object> nodeType = nodesNameEntry.next();
- final ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(
- ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
- vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
- }
- }
- for (final NodeTypeInfo cvfc : nodeTypesInfo.values()) {
- vfcToscaNames.put(cvfc.getType(), buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(),
- vfResourceName, cvfc.getType()));
- }
- return vfcToscaNames;
- }
-
- private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
- Map<String, Object> nodes = new HashMap<>();
- for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
- extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
- }
- extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
- return nodes;
- }
-
- private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
- Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
- .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
- if (eitherNodeTypes.isLeft()) {
- nodes.putAll(eitherNodeTypes.left()
- .value());
- }
- }
-
- public Resource createResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload,
- String csarUUID) {
- log.trace("************* created successfully from YAML, resource TOSCA ");
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,StatusCode.STARTED,"Starting to create Resource From Csar by user {}", user.getUserId() );
- CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID);
- Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
- Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
- nodeTypesInfo, csarInfo, resource);
- if (findNodeTypesArtifactsToHandleRes.isRight()) {
- log.debug("failed to find node types for update with artifacts during import csar {}. ",
- csarInfo.getCsarUUID());
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
- StatusCode.ERROR,"error: {}",findNodeTypesArtifactsToHandleRes.right().value());
- throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value());
- }
- Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(),
- csarInfo.getMainTemplateName(), nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left()
- .value(),
- true, false, null);
- log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}",
- vfResource.getToscaResourceName());
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,StatusCode.COMPLETE,"Ended create Resource From Csar by user {}", user.getUserId() );
- return vfResource;
- }
-
- private Resource validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
- log.trace("validating resource before create");
- user.copyData(validateUser(user, CREATE_RESOURCE, resource, AuditingActionEnum.CREATE_RESOURCE, false));
- // validate user role
- validateUserRole(user, resource, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null);
- // VF / PNF "derivedFrom" should be null (or ignored)
- if (ModelConverter.isAtomicComponent(resource)) {
- validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
- }
- return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
-
- }
-
- // resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo,
- // nodeTypesArtifactsToCreate, true, false, null
- private Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName,
- Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
- boolean shouldLock, boolean inTransaction, String nodeName) {
-
- List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
- Resource createdResource;
- try {
- ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, resource);
+ preparedResource = updateExistingResourceByImport(newResource, oldResource, csarInfo.getModifier(), inTransaction, shouldLock,
+ isNested).left;
+ log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
+ handleResourceGenericType(preparedResource);
+ handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo,
+ csarInfo, nodeName);
+ preparedResource = createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
+ Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>();
+ preparedResource = createResourceInstances(yamlFileName, preparedResource, oldResource, instances, csarInfo.getCreatedNodes(),
+ existingNodeTypesByResourceNames);
+ preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, oldResource, instances,
+ existingNodeTypesByResourceNames);
+ } catch (ComponentException e) {
+ ResponseFormat responseFormat =
+ e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
+ log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName, responseFormat);
+ componentsUtils
+ .auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldResource : preparedResource, actionEnum);
+ throw e;
+ } catch (StorageException e) {
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
+ log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName, responseFormat);
+ componentsUtils
+ .auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldResource : preparedResource, actionEnum);
+ throw e;
+ }
+ Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
+ .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(), preparedResource.getSystemName());
+ if (validateUpdateVfGroupNamesRes.isRight()) {
+ throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right().value());
+ }
+ // add groups to newResource
+ Map<String, GroupDefinition> groups;
+ if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
+ groups = validateUpdateVfGroupNamesRes.left().value();
+ } else {
+ groups = uploadComponentInstanceInfoMap.getGroups();
+ }
+ handleGroupsProperties(preparedResource, groups);
+ Either<Boolean, ActionStatus> isTopologyChanged = topologyComparator.isTopologyChanged(oldResource, preparedResource);
+ preparedResource = updateGroupsOnResource(preparedResource, groups);
+ NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToHandle);
+ Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE, createdArtifacts, yamlFileName,
+ csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
+ if (updateArtifactsEither.isRight()) {
+ log.debug("failed to update artifacts {}", updateArtifactsEither.right().value());
+ throw new ByResponseFormatComponentException(updateArtifactsEither.right().value());
+ }
+ preparedResource = getResourceWithGroups(updateArtifactsEither.left().value().getUniqueId());
+ updateGroupsName(oldResource, preparedResource, isTopologyChanged.left().value());
+ updateResourceInstancesNames(oldResource, csarInfo, preparedResource, isTopologyChanged.left().value());
+ final String preparedResourceId = preparedResource != null ? preparedResource.getUniqueId() : "";
+ preparedResource = getResourceWithGroups(preparedResourceId);
+ updateVolumeGroup(preparedResource);
+ ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldResource, preparedResource);
+ if (mergingPropsAndInputsStatus != ActionStatus.OK) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus, preparedResource);
+ throw new ByResponseFormatComponentException(responseFormat);
+ }
+ compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
+ return preparedResource;
+ }
+
+ protected void updateVolumeGroup(Resource preparedResource) {
+ List<GroupDefinition> groups = preparedResource.safeGetGroups();
+ for (GroupDefinition group : groups) {
+ Map<String, ArtifactDefinition> createdNewArtifacts = preparedResource.getDeploymentArtifacts();
+ if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
+ List<PropertyDataDefinition> volumePropList = group.getProperties().stream().filter(p -> "volume_group".equals(p.getName()))
+ .collect(Collectors.toList());
+ if (!volumePropList.isEmpty()) {
+ PropertyDataDefinition volumeProp = volumePropList.get(0);
+ if (volumeProp != null) {
+ boolean isVolumeGroup = isVolumeGroup(group.getArtifacts(), new ArrayList<>(createdNewArtifacts.values()));
+ if (!volumePropList.get(0).getValue().equals(String.valueOf(isVolumeGroup))) {
+ volumeProp.setValue(String.valueOf(isVolumeGroup));
+ volumeProp.setDefaultValue(String.valueOf(isVolumeGroup));
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private void updateGroupsName(Resource oldResource, Resource preparedResource, boolean isTopologyChanged) {
+ if (oldResource == null || preparedResource == null) {
+ log.debug("Failed to update groups name : oldResource or preparedResource is null");
+ } else if (CollectionUtils.isNotEmpty(oldResource.getGroups()) && CollectionUtils.isNotEmpty(preparedResource.getGroups())) {
+ Map<String, String> oldGroups = oldResource.getGroups().stream()
+ .collect(toMap(GroupDataDefinition::getInvariantName, GroupDataDefinition::getName));
+ List<GroupDefinition> updatedGroups = preparedResource.getGroups().stream()
+ .filter(group -> oldGroups.containsKey(group.getInvariantName()) && !group.getName().equals(oldGroups.get(group.getInvariantName())))
+ .collect(toList());
+ if (CollectionUtils.isNotEmpty(updatedGroups)) {
+ if (isTopologyChanged) {
+ updatedGroups.stream().filter(group -> !group.isVspOriginated())
+ .forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
+ } else {
+ updatedGroups.forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
+ }
+ groupBusinessLogic.updateGroups(preparedResource, updatedGroups, false);
+ }
+ }
+ }
+
+ private void updateResourceInstancesNames(Resource oldResource, CsarInfo csarInfo, Resource preparedResource, boolean isTopologyChanged) {
+ if (oldResource == null || preparedResource == null) {
+ log.debug("Failed to update resource instances names : oldResource or preparedResource is null");
+ } else {
+ if (CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) {
+ Map<String, String> oldInstances = oldResource.getComponentInstances().stream()
+ .collect(toMap(ComponentInstance::getInvariantName, ComponentInstance::getName));
+ List<ComponentInstance> updatedInstances = preparedResource.getComponentInstances().stream()
+ .filter(i -> oldInstances.containsKey(i.getInvariantName()) && !i.getName().equals(oldInstances.get(i.getInvariantName())))
+ .collect(toList());
+ if (CollectionUtils.isNotEmpty(updatedInstances)) {
+ if (isTopologyChanged) {
+ updatedInstances.stream().filter(i -> !i.isCreatedFromCsar()).forEach(i -> i.setName(oldInstances.get(i.getInvariantName())));
+ } else {
+ updatedInstances.forEach(i -> i.setName(oldInstances.get(i.getInvariantName())));
+ }
+ }
+ }
+ componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME, null, preparedResource.getUniqueId(),
+ csarInfo.getModifier().getUserId(), preparedResource.getComponentInstances(), false);
+ }
+ }
+
+ private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
+ String yamlFileName, CsarInfo csarInfo, Resource preparedResource,
+ NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts,
+ boolean inTransaction, boolean shouldLock) {
+ String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
+ Resource resource = preparedResource;
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
+ .getNodeTypesArtifactsToHandle();
+ if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) {
+ if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) {
+ Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = handleNodeTypeArtifacts(preparedResource,
+ nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
+ if (handleNodeTypeArtifactsRes.isRight()) {
+ return Either.right(handleNodeTypeArtifactsRes.right().value());
+ }
+ }
+ } else {
+ Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts,
+ new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
+ log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
+ if (createdCsarArtifactsEither.isRight()) {
+ return createdCsarArtifactsEither;
+ }
+ resource = createdCsarArtifactsEither.left().value();
+ }
+ return Either.left(resource);
+ }
+
+ private Resource handleResourceGenericType(Resource resource) {
+ Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
+ if (resource.shouldGenerateInputs()) {
+ generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
+ }
+ return genericResource;
+ }
+
+ private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
+ final Map<String, NodeTypeInfo> nodeTypesInfo, final CsarInfo csarInfo, final Resource oldResource) {
+ final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
+ Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes = Either
+ .left(nodeTypesArtifactsToHandle);
+ try {
+ final Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
+ final Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, oldResource.getName(),
+ csarInfo);
+ log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(),
+ csarInfo.getCsarUUID());
+ extractedVfcToscaNames.forEach(
+ (namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
+ extractedVfcsArtifacts, namespace, vfcToscaNames));
+ } catch (Exception e) {
+ final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
+ log.debug("Exception occurred when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
+ }
+ return nodeTypesArtifactsToHandleRes;
+ }
+
+ private void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
+ Resource resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace,
+ ImmutablePair<String, String> vfcToscaNames) {
+ EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
+ log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
+ Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), null);
+ if (!isEmpty(extractedVfcsArtifacts)) {
+ List<ArtifactDefinition> currArtifacts = new ArrayList<>();
+ if (extractedVfcsArtifacts.containsKey(namespace)) {
+ handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
+ }
+ curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
+ } else if (curNodeType != null) {
+ // delete all artifacts if have not received artifacts from
+
+ // csar
+ curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
+ List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
+ // delete all informational artifacts
+ artifactsToDelete.addAll(
+ curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
+ .collect(toList()));
+ // delete all deployment artifacts
+ artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
+ if (!artifactsToDelete.isEmpty()) {
+ curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
+ }
+ }
+ if (isNotEmpty(curNodeTypeArtifactsToHandle)) {
+ nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
+ }
+ }
+
+ private Resource findVfcResource(CsarInfo csarInfo, Resource resource, String currVfcToscaName, String previousVfcToscaName,
+ StorageOperationStatus status) {
+ if (status != null && status != StorageOperationStatus.NOT_FOUND) {
+ log.debug("Error occurred during fetching node type with tosca name {}, error: {}", currVfcToscaName, status);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
+ componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.CREATE_RESOURCE);
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
+ } else if (StringUtils.isNotEmpty(currVfcToscaName)) {
+ return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName).left()
+ .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
+ }
+ return null;
+ }
+
+ private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(Resource curNodeType,
+ List<ArtifactDefinition> extractedArtifacts) {
+ try {
+ List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
+ List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
+ List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
+ processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, artifactsToDelete,
+ collectExistingArtifacts(curNodeType));
+ return putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
+ } catch (Exception e) {
+ log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
+ throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
+ }
+ }
+
+ private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(List<ArtifactDefinition> artifactsToUpload,
+ List<ArtifactDefinition> artifactsToUpdate,
+ List<ArtifactDefinition> artifactsToDelete) {
+ EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
+ if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
+ nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
+ if (!artifactsToUpload.isEmpty()) {
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
+ }
+ if (!artifactsToUpdate.isEmpty()) {
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
+ }
+ if (!artifactsToDelete.isEmpty()) {
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
+ }
+ }
+ return nodeTypeArtifactsToHandle;
+ }
+
+ private void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts, List<ArtifactDefinition> artifactsToUpload,
+ List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete,
+ Map<String, ArtifactDefinition> existingArtifacts) {
+ if (!existingArtifacts.isEmpty()) {
+ extractedArtifacts.stream().forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
+ artifactsToDelete.addAll(existingArtifacts.values());
+ }
+ }
+
+ private void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
+ Map<String, ArtifactDefinition> existingArtifacts, ArtifactDefinition currNewArtifact) {
+ Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values().stream()
+ .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst();
+ if (foundArtifact.isPresent()) {
+ if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) {
+ updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
+ existingArtifacts.remove(foundArtifact.get().getArtifactLabel());
+ artifactsToUpload.remove(currNewArtifact);
+ } else {
+ log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
+ throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
+ currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), foundArtifact.get().getArtifactType());
+ }
+ }
+ }
+
+ private void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact,
+ ArtifactDefinition foundArtifact) {
+ if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
+ foundArtifact.setPayload(currNewArtifact.getPayloadData());
+ foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
+ foundArtifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
+ artifactsToUpdate.add(foundArtifact);
+ }
+ }
+
+ private Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
+ Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
+ if (curNodeType == null) {
+ return existingArtifacts;
+ }
+ if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
+ existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
+ }
+ if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
+ existingArtifacts.putAll(
+ curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
+ .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
+ }
+ return existingArtifacts;
+ }
+
+ /**
+ * Changes resource life cycle state to checked out
+ *
+ * @param resource
+ * @param user
+ * @param inTransaction
+ * @return
+ */
+ private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
+ Either<Resource, ResponseFormat> checkoutResourceRes;
+ try {
+ if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState()
+ .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ log.debug("************* Going to change life cycle state of resource {} to not certified checked out. ", resource.getName());
+ Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic
+ .changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
+ new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT, LifecycleChanceActionEnum.CREATE_FROM_CSAR), inTransaction, true);
+ if (checkoutRes.isRight()) {
+ log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ",
+ resource.getComponentType().getNodeType(), resource.getUniqueId(), checkoutRes.right().value().getStatus());
+ checkoutResourceRes = Either.right(checkoutRes.right().value());
+ } else {
+ checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
+ }
+ } else {
+ checkoutResourceRes = Either.left(resource);
+ }
+ } catch (Exception e) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ checkoutResourceRes = Either.right(responseFormat);
+ log.debug("Exception occurred when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), e);
+ }
+ return checkoutResourceRes;
+ }
+
+ /**
+ * Handles Artifacts of NodeType
+ *
+ * @param nodeTypeResource
+ * @param nodeTypeArtifactsToHandle
+ * @param user
+ * @param inTransaction
+ * @return
+ */
+ public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
+ Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
+ List<ArtifactDefinition> createdArtifacts, User user,
+ boolean inTransaction, boolean ignoreLifecycleState) {
+ List<ArtifactDefinition> handleNodeTypeArtifactsRequestRes;
+ Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
+ Either<Resource, ResponseFormat> changeStateResponse;
+ try {
+ changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
+ if (changeStateResponse.isRight()) {
+ return Either.right(changeStateResponse.right().value());
+ }
+ nodeTypeResource = changeStateResponse.left().value();
+ List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
+ log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
+ for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle.entrySet()) {
+ ArtifactOperationEnum curOperation = curOperationEntry.getKey();
+ List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
+ if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
+ log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), nodeTypeResource.getName());
+ handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
+ .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, createdArtifacts,
+ new ArtifactOperationInfo(false, ignoreLifecycleState, curOperation), false, inTransaction);
+ if (ArtifactOperationEnum.isCreateOrLink(curOperation)) {
+ createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
+ }
+ handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
+ }
+ }
+ if (handleNodeTypeArtifactsRes == null) {
+ handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
+ }
+ } catch (Exception e) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ handleNodeTypeArtifactsRes = Either.right(responseFormat);
+ log.debug("Exception occurred when handleVfcArtifacts, error is:{}", e.getMessage(), e);
+ }
+ return handleNodeTypeArtifactsRes;
+ }
+
+ private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(final Map<String, NodeTypeInfo> nodeTypesInfo,
+ final String vfResourceName, final CsarInfo csarInfo) {
+ final Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
+ final Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
+ if (!nodes.isEmpty()) {
+ final Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
+ while (nodesNameEntry.hasNext()) {
+ final Entry<String, Object> nodeType = nodesNameEntry.next();
+ final ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), vfResourceName,
+ nodeType.getKey());
+ vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
+ }
+ }
+ for (final NodeTypeInfo cvfc : nodeTypesInfo.values()) {
+ vfcToscaNames.put(cvfc.getType(), buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), vfResourceName, cvfc.getType()));
+ }
+ return vfcToscaNames;
+ }
+
+ private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
+ Map<String, Object> nodes = new HashMap<>();
+ for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
+ extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
+ }
+ extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
+ return nodes;
+ }
+
+ private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
+ Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
+ .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
+ if (eitherNodeTypes.isLeft()) {
+ nodes.putAll(eitherNodeTypes.left().value());
+ }
+ }
+
+ public Resource createResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload, String csarUUID) {
+ log.trace("************* created successfully from YAML, resource TOSCA ");
+ loggerSupportability
+ .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, StatusCode.STARTED, "Starting to create Resource From Csar by user {}",
+ user.getUserId());
+ CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID);
+ Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
+ Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
+ nodeTypesInfo, csarInfo, resource);
+ if (findNodeTypesArtifactsToHandleRes.isRight()) {
+ log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID());
+ loggerSupportability
+ .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "error: {}", findNodeTypesArtifactsToHandleRes.right().value());
+ throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value());
+ }
+ Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(), nodeTypesInfo,
+ csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false, null);
+ log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}", vfResource.getToscaResourceName());
+ loggerSupportability
+ .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, StatusCode.COMPLETE, "Ended create Resource From Csar by user {}",
+ user.getUserId());
+ return vfResource;
+ }
+
+ private Resource validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
+ log.trace("validating resource before create");
+ user.copyData(validateUser(user, CREATE_RESOURCE, resource, AuditingActionEnum.CREATE_RESOURCE, false));
+ // validate user role
+ validateUserRole(user, resource, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null);
+ // VF / PNF "derivedFrom" should be null (or ignored)
+ if (ModelConverter.isAtomicComponent(resource)) {
+ validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
+ }
+ return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
+ }
+
+ private Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo,
+ CsarInfo csarInfo,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
+ boolean shouldLock, boolean inTransaction, String nodeName) {
+ List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
+ Resource createdResource;
+ try {
+ ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic
+ .getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, resource);
if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances()) && resource.getResourceType() != ResourceTypeEnum.PNF) {
throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
}
- log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
- StatusCode.STARTED,"");
- createdResource = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo,
- AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml, nodeTypesInfo,
- csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
- log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
- StatusCode.COMPLETE,"The resource has been created: {}",resource.getName());
- } catch (ComponentException e) {
- ResponseFormat responseFormat = e.getResponseFormat() == null
- ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
- componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
- AuditingActionEnum.IMPORT_RESOURCE);
- throw e;
- } catch (StorageException e) {
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
- componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
- AuditingActionEnum.IMPORT_RESOURCE);
- throw e;
- }
- return createdResource;
-
- }
-
- public Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource,
- Map<String, Object> mappedToscaTemplate, boolean needLock,
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
- List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
- CsarInfo csarInfo) {
-
- Either<String, ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
- TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
- if (toscaVersion.isRight()) {
- throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
- }
- Map<String, Object> mapToConvert = new HashMap<>();
- mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left()
- .value());
- Map<String, Object> nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate);
- createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
- nodeTypesInfo, csarInfo, mapToConvert, nodeTypes);
- return csarInfo.getCreatedNodes();
- }
-
- private Map<String, Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
- return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES)
- .left()
- .orValue(HashMap::new);
- }
-
- private void createNodeTypes(String yamlName, Resource resource, boolean needLock,
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
- List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
- CsarInfo csarInfo, Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
- Iterator<Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet()
- .iterator();
- Resource vfcCreated = null;
- while (nodesNameValueIter.hasNext()) {
- Entry<String, Object> nodeType = nodesNameValueIter.next();
- Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
- || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
-
- if (nodeTypesInfo.containsKey(nodeType.getKey())) {
- log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
- vfcCreated = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
- nodeTypesInfo, csarInfo, nodeType.getKey());
- log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
- } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
- && !csarInfo.getCreatedNodesToscaResourceNames()
- .containsKey(nodeType.getKey())) {
- log.trace("************* Going to create node {}", nodeType.getKey());
- ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName,
- nodeType, csarInfo.getModifier(), mapToConvert, resource, needLock, nodeTypeArtifactsToHandle,
- nodeTypesNewCreatedArtifacts, true, csarInfo, true);
- log.debug("************* Finished to create node {}", nodeType.getKey());
-
- vfcCreated = resourceCreated.getLeft();
- csarInfo.getCreatedNodesToscaResourceNames()
- .put(nodeType.getKey(), vfcCreated.getToscaResourceName());
- }
- if (vfcCreated != null) {
- csarInfo.getCreatedNodes()
- .put(nodeType.getKey(), vfcCreated);
- }
- mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
- }
- }
-
- private Resource handleNestedVfc(Resource resource,
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
- List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
- String nodeName) {
-
- String yamlName = nodesInfo.get(nodeName)
- .getTemplateFileName();
- Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName)
- .getMappedToscaTemplate();
-
- log.debug("************* Going to create node types from yaml {}", yamlName);
- createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle,
- createdArtifacts, Collections.emptyMap(), csarInfo);
- log.debug("************* Finished to create node types from yaml {}", yamlName);
-
- if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
- log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
- resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo,
- nodeName, yamlName);
- }
- return resource;
- }
-
- private Resource handleComplexVfc(final Resource resource,
- final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>
- nodesArtifactsToHandle,
- final List<ArtifactDefinition>
- createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
- final String nodeName, final String yamlName) {
-
- Resource oldComplexVfc = null;
- Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
- Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
- .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
- if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
- oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
- buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getRight());
- }
- if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
- log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ",
- newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
- throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
- } else if (oldComplexVfcRes.isLeft()) {
- log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
- final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(
- oldComplexVfcRes.left().value(),
- newComplexVfc, ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
- if (eitherValidation.isLeft()) {
- oldComplexVfc = oldComplexVfcRes.left().value();
- }
- }
- newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName,
- yamlName, oldComplexVfc, newComplexVfc);
- csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
- final LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
- LifecycleChanceActionEnum.CREATE_FROM_CSAR);
- log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
- final Resource result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc,
- lifecycleChangeInfo, true, false, true);
- csarInfo.getCreatedNodes().put(nodeName, result);
- csarInfo.removeNodeFromQueue();
- return result;
- }
-
- private Resource handleComplexVfc(
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
- List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
- String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
-
- Resource handleComplexVfcRes;
- Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName)
- .getMappedToscaTemplate();
- String yamlContent = new String(csarInfo.getCsar()
- .get(yamlName));
- Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet()
- .stream()
- .collect(toMap(Entry::getKey, e -> e.getValue()
- .getUnmarkedCopy()));
- CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
- if (oldComplexVfc == null) {
- handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo,
- csarInfo, nodesArtifactsToHandle, false, true, nodeName);
- } else {
- handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc,
- AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo,
- newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
- }
- return handleComplexVfcRes;
- }
-
- private Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName,
- Map<String, NodeTypeInfo> nodesInfo) {
-
- Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
- log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
- csarInfo.addNodeToQueue(nodeName);
- return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE,
- true, csarInfo);
- }
-
- private String getNodeTypeActualName(final String nodeTypefullName, final String nodeTypeNamePrefix) {
-
- final String nameWithouNamespacePrefix = nodeTypefullName.substring(nodeTypeNamePrefix.length());
- final String[] findTypes = nameWithouNamespacePrefix.split("\\.");
-
- if(findTypes.length > 1){
- final String resourceType = findTypes[0];
- return nameWithouNamespacePrefix.substring(resourceType.length());
- }
- return nameWithouNamespacePrefix;
- }
-
- private ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(final String yamlName,
- final Entry<String, Object> nodeNameValue,
- User user,
- final Map<String, Object> mapToConvert,
- final Resource resourceVf,
- final boolean needLock,
- final Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
- final List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
- final boolean forceCertificationAllowed,
- final CsarInfo csarInfo,
- final boolean isNested) {
-
- final UploadResourceInfo resourceMetaData = fillResourceMetadata(
- yamlName, resourceVf, nodeNameValue.getKey(), user);
-
- final String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
- user = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
- return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock,
- nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
- nodeNameValue.getKey(), isNested);
- }
-
- private String buildNodeTypeYaml(final Entry<String, Object> nodeNameValue,
- final Map<String, Object> mapToConvert,
- final String nodeResourceType,
- final CsarInfo csarInfo) {
- // We need to create a Yaml from each node_types in order to create
- // resource from each node type using import normative flow.
- final DumperOptions options = new DumperOptions();
- options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
- final Yaml yaml = new Yaml(options);
-
- final Map<String, Object> node = new HashMap<>();
- node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey())
- .getLeft(), nodeNameValue.getValue());
- mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
-
- return yaml.dumpAsMap(mapToConvert);
- }
-
- public Boolean validateResourceCreationFromNodeType(Resource resource, User creator) {
- validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
- return true;
- }
-
- public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml,
- UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
- Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
- List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
- String nodeName, boolean isNested) {
-
- LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
- LifecycleChanceActionEnum.CREATE_FROM_CSAR);
- Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(
- resource, creator);
- return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
- lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle,
- nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
- }
-
- /**
- * Validates if a given node type name has a valid prefix.
- *
- * @param nodeName node name from definition file
- * @param definedResourceNamespaceList is a list of all node type name prefix allowed
- * @return a valid node type name prefix if it`s found
- */
- public Optional<String> validateNodeTypeNamePrefix(final String nodeName,
- final List<String> definedResourceNamespaceList) {
- for (final String validNamespace : definedResourceNamespaceList) {
- if (nodeName.startsWith(validNamespace)) {
- return Optional.of(validNamespace);
- }
- }
- return Optional.empty();
- }
-
- private List<String> getDefinedNodeTypeNamespaceList() {
- return ConfigurationManager.getConfigurationManager().getConfiguration().getDefinedResourceNamespace();
- }
-
- private UploadResourceInfo fillResourceMetadata(final String yamlName, final Resource resourceVf,
- final String nodeName, final User user) {
-
- final UploadResourceInfo resourceMetaData = new UploadResourceInfo();
-
- final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeName);
- log.debug("Node type Name prefix {}", nodeTypeNamePrefix);
-
- if (!nodeName.startsWith(nodeTypeNamePrefix)) {
- log.debug("invalid nodeName:{} does not start with {}.", nodeName, getDefinedNodeTypeNamespaceList());
- throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName,
- resourceMetaData.getName(), nodeName);
- }
-
- final String actualName = this.getNodeTypeActualName(nodeName, nodeTypeNamePrefix);
- final String namePrefix = nodeName.replace(actualName, "");
- String resourceType = namePrefix.substring(nodeTypeNamePrefix.length());
- log.debug("initial namePrefix:{} resourceType {}. nodeName {} , actualName {} prefix {}", namePrefix,
- resourceType, nodeName, actualName, nodeTypeNamePrefix);
-
- // if we import from csar, the node_type name can be
- // org.openecomp.resource.abstract.node_name - in this case we always
- // create a vfc
- if (resourceType.equals(Constants.ABSTRACT)) {
- resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
- }
-
- if (!ResourceTypeEnum.containsIgnoreCase(resourceType)) {
- resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
- }
-
- // validating type
- if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
- log.debug("invalid resourceType:{} the type is not one of the valide types:{}.",
- resourceType.toUpperCase(), ResourceTypeEnum.values());
- throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName,
- resourceMetaData.getName(), nodeName);
- }
-
- // Setting name
- resourceMetaData.setName(new StringBuilder(resourceVf.getSystemName()).append(actualName).toString());
-
- // Setting type from name
- final String type = resourceType.toUpperCase();
- resourceMetaData.setResourceType(type);
-
- resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
- resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
- resourceMetaData.setContactId(user.getUserId());
- resourceMetaData.setVendorName(resourceVf.getVendorName());
- resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
-
- // Setting tag
- final List<String> tags = new ArrayList<>();
- tags.add(resourceMetaData.getName());
- resourceMetaData.setTags(tags);
-
- // Setting category
- final CategoryDefinition category = new CategoryDefinition();
- category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
- final SubCategoryDefinition subCategory = new SubCategoryDefinition();
- subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
- category.addSubCategory(subCategory);
- final List<CategoryDefinition> categories = new ArrayList<>();
- categories.add(category);
- resourceMetaData.setCategories(categories);
-
- return resourceMetaData;
- }
-
- private Resource buildComplexVfcMetadata(final Resource resourceVf,
- final CsarInfo csarInfo,
- final String nodeName,
- final Map<String, NodeTypeInfo> nodesInfo) {
- final Resource cvfc = new Resource();
- final NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
- cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
- cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
- cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
- cvfc.setResourceType(ResourceTypeEnum.CVFC);
- cvfc.setAbstract(true);
- cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
- cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
- cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
- cvfc.setContactId(csarInfo.getModifier()
- .getUserId());
- cvfc.setCreatorUserId(csarInfo.getModifier()
- .getUserId());
- cvfc.setVendorName(resourceVf.getVendorName());
- cvfc.setVendorRelease(resourceVf.getVendorRelease());
- cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
- cvfc.setToscaResourceName(buildNestedToscaResourceName(
- ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
- cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
-
- final List<String> tags = new ArrayList<>();
- tags.add(cvfc.getName());
- cvfc.setTags(tags);
-
- final CategoryDefinition category = new CategoryDefinition();
- category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
- SubCategoryDefinition subCategory = new SubCategoryDefinition();
- subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
- category.addSubCategory(subCategory);
- final List<CategoryDefinition> categories = new ArrayList<>();
- categories.add(category);
- cvfc.setCategories(categories);
-
- cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
- cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
- cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
-
- return cvfc;
- }
-
- private String buildCvfcName(final String resourceVfName, final String nodeName) {
-
- String nameWithouNamespacePrefix =
- nodeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
- String[] findTypes = nameWithouNamespacePrefix.split("\\.");
- String resourceType = findTypes[0];
- String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
- return addCvfcSuffixToResourceName(resourceName);
- }
-
- private Resource createResourceAndRIsFromYaml(final String yamlName,
- Resource resource,
- final ParsedToscaYamlInfo parsedToscaYamlInfo,
- final AuditingActionEnum actionEnum,
- final boolean isNormative,
- final List<ArtifactDefinition> createdArtifacts,
- final String topologyTemplateYaml,
- final Map<String, NodeTypeInfo> nodeTypesInfo,
- final CsarInfo csarInfo,
- final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
- final boolean shouldLock,
- final boolean inTransaction,
- final String nodeName) {
-
- final List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
+ log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
+ loggerSupportability
+ .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED, "");
+ createdResource = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false,
+ createdArtifacts, topologyTemplateYaml, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
+ log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
+ loggerSupportability
+ .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
+ "The resource has been created: {}", resource.getName());
+ } catch (ComponentException e) {
+ ResponseFormat responseFormat =
+ e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
+ componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
+ throw e;
+ } catch (StorageException e) {
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
+ componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
+ throw e;
+ }
+ return createdResource;
+ }
+
+ public Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map<String, Object> mappedToscaTemplate,
+ boolean needLock,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
+ Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
+ Either<String, ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
+ if (toscaVersion.isRight()) {
+ throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
+ }
+ Map<String, Object> mapToConvert = new HashMap<>();
+ mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value());
+ Map<String, Object> nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate);
+ createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, mapToConvert,
+ nodeTypes);
+ return csarInfo.getCreatedNodes();
+ }
+
+ private Map<String, Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
+ return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES).left().orValue(HashMap::new);
+ }
+
+ private void createNodeTypes(String yamlName, Resource resource, boolean needLock,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
+ Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
+ Iterator<Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet().iterator();
+ Resource vfcCreated = null;
+ while (nodesNameValueIter.hasNext()) {
+ Entry<String, Object> nodeType = nodesNameValueIter.next();
+ Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle =
+ nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
+ if (nodeTypesInfo.containsKey(nodeType.getKey())) {
+ log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
+ vfcCreated = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
+ nodeType.getKey());
+ log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
+ } else if (csarInfo.getCreatedNodesToscaResourceNames() != null && !csarInfo.getCreatedNodesToscaResourceNames()
+ .containsKey(nodeType.getKey())) {
+ log.trace("************* Going to create node {}", nodeType.getKey());
+ ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(),
+ mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true);
+ log.debug("************* Finished to create node {}", nodeType.getKey());
+ vfcCreated = resourceCreated.getLeft();
+ csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(), vfcCreated.getToscaResourceName());
+ }
+ if (vfcCreated != null) {
+ csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
+ }
+ mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
+ }
+ }
+
+ private Resource handleNestedVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
+ List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
+ String nodeName) {
+ String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
+ Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
+ log.debug("************* Going to create node types from yaml {}", yamlName);
+ createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts,
+ Collections.emptyMap(), csarInfo);
+ log.debug("************* Finished to create node types from yaml {}", yamlName);
+ if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
+ log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
+ resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
+ }
+ return resource;
+ }
+ private Resource handleComplexVfc(final Resource resource,
+ final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
+ final List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
+ final String nodeName, final String yamlName) {
+ Resource oldComplexVfc = null;
+ Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
+ Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
+ .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
+ if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
+ oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
+ buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getRight());
+ }
+ if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
+ log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", newComplexVfc.getToscaResourceName(),
+ oldComplexVfcRes.right().value());
+ throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
+ } else if (oldComplexVfcRes.isLeft()) {
+ log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
+ final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(),
+ newComplexVfc, ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
+ if (eitherValidation.isLeft()) {
+ oldComplexVfc = oldComplexVfcRes.left().value();
+ }
+ }
+ newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc,
+ newComplexVfc);
+ csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
+ final LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
+ LifecycleChanceActionEnum.CREATE_FROM_CSAR);
+ log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
+ final Resource result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true);
+ csarInfo.getCreatedNodes().put(nodeName, result);
+ csarInfo.removeNodeFromQueue();
+ return result;
+ }
+
+ private Resource handleComplexVfc(Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
+ List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
+ String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
+ Resource handleComplexVfcRes;
+ Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
+ String yamlContent = new String(csarInfo.getCsar().get(yamlName));
+ Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream().collect(toMap(Entry::getKey, e -> e.getValue().getUnmarkedCopy()));
+ CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
+ if (oldComplexVfc == null) {
+ handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, csarInfo, nodesArtifactsToHandle,
+ false, true, nodeName);
+ } else {
+ handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts,
+ yamlContent, yamlName, csarInfo, newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
+ }
+ return handleComplexVfcRes;
+ }
+
+ private Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
+ Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
+ log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
+ csarInfo.addNodeToQueue(nodeName);
+ return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
+ }
+
+ private String getNodeTypeActualName(final String nodeTypefullName, final String nodeTypeNamePrefix) {
+ final String nameWithouNamespacePrefix = nodeTypefullName.substring(nodeTypeNamePrefix.length());
+ final String[] findTypes = nameWithouNamespacePrefix.split("\\.");
+ if (findTypes.length > 1) {
+ final String resourceType = findTypes[0];
+ return nameWithouNamespacePrefix.substring(resourceType.length());
+ }
+ return nameWithouNamespacePrefix;
+ }
+
+ private ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(final String yamlName, final Entry<String, Object> nodeNameValue,
+ User user, final Map<String, Object> mapToConvert,
+ final Resource resourceVf, final boolean needLock,
+ final Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
+ final List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
+ final boolean forceCertificationAllowed, final CsarInfo csarInfo,
+ final boolean isNested) {
+ final UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
+ final String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
+ user = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
+ return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, nodeTypeArtifactsToHandle,
+ nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested);
+ }
+
+ private String buildNodeTypeYaml(final Entry<String, Object> nodeNameValue, final Map<String, Object> mapToConvert, final String nodeResourceType,
+ final CsarInfo csarInfo) {
+ // We need to create a Yaml from each node_types in order to create
+
+ // resource from each node type using import normative flow.
+ final DumperOptions options = new DumperOptions();
+ options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
+ final Yaml yaml = new Yaml(options);
+ final Map<String, Object> node = new HashMap<>();
+ node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey()).getLeft(),
+ nodeNameValue.getValue());
+ mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
+ return yaml.dumpAsMap(mapToConvert);
+ }
+
+ public Boolean validateResourceCreationFromNodeType(Resource resource, User creator) {
+ validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
+ return true;
+ }
+
+ public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator,
+ boolean isInTransaction, boolean needLock,
+ Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
+ boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName,
+ boolean isNested) {
+ LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
+ LifecycleChanceActionEnum.CREATE_FROM_CSAR);
+ Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(resource, creator);
+ return resourceImportManager
+ .importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock,
+ nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
+ }
+
+ /**
+ * Validates if a given node type name has a valid prefix.
+ *
+ * @param nodeName node name from definition file
+ * @param definedResourceNamespaceList is a list of all node type name prefix allowed
+ * @return a valid node type name prefix if it`s found
+ */
+ public Optional<String> validateNodeTypeNamePrefix(final String nodeName, final List<String> definedResourceNamespaceList) {
+ for (final String validNamespace : definedResourceNamespaceList) {
+ if (nodeName.startsWith(validNamespace)) {
+ return Optional.of(validNamespace);
+ }
+ }
+ return Optional.empty();
+ }
+
+ private List<String> getDefinedNodeTypeNamespaceList() {
+ return ConfigurationManager.getConfigurationManager().getConfiguration().getDefinedResourceNamespace();
+ }
+
+ private UploadResourceInfo fillResourceMetadata(final String yamlName, final Resource resourceVf, final String nodeName, final User user) {
+ final UploadResourceInfo resourceMetaData = new UploadResourceInfo();
+ final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeName);
+ log.debug("Node type Name prefix {}", nodeTypeNamePrefix);
+ if (!nodeName.startsWith(nodeTypeNamePrefix)) {
+ log.debug("invalid nodeName:{} does not start with {}.", nodeName, getDefinedNodeTypeNamespaceList());
+ throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
+ }
+ final String actualName = this.getNodeTypeActualName(nodeName, nodeTypeNamePrefix);
+ final String namePrefix = nodeName.replace(actualName, "");
+ String resourceType = namePrefix.substring(nodeTypeNamePrefix.length());
+ log.debug("initial namePrefix:{} resourceType {}. nodeName {} , actualName {} prefix {}", namePrefix, resourceType, nodeName, actualName,
+ nodeTypeNamePrefix);
+ // if we import from csar, the node_type name can be
+
+ // org.openecomp.resource.abstract.node_name - in this case we always
+
+ // create a vfc
+ if (resourceType.equals(Constants.ABSTRACT)) {
+ resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
+ }
+ if (!ResourceTypeEnum.containsIgnoreCase(resourceType)) {
+ resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
+ }
+ // validating type
+ if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
+ log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values());
+ throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
+ }
+ // Setting name
+ resourceMetaData.setName(new StringBuilder(resourceVf.getSystemName()).append(actualName).toString());
+ // Setting type from name
+ final String type = resourceType.toUpperCase();
+ resourceMetaData.setResourceType(type);
+ resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
+ resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
+ resourceMetaData.setContactId(user.getUserId());
+ resourceMetaData.setVendorName(resourceVf.getVendorName());
+ resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
+ // Setting tag
+ final List<String> tags = new ArrayList<>();
+ tags.add(resourceMetaData.getName());
+ resourceMetaData.setTags(tags);
+ // Setting category
+ final CategoryDefinition category = new CategoryDefinition();
+ category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
+ final SubCategoryDefinition subCategory = new SubCategoryDefinition();
+ subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
+ category.addSubCategory(subCategory);
+ final List<CategoryDefinition> categories = new ArrayList<>();
+ categories.add(category);
+ resourceMetaData.setCategories(categories);
+ return resourceMetaData;
+ }
+
+ private Resource buildComplexVfcMetadata(final Resource resourceVf, final CsarInfo csarInfo, final String nodeName,
+ final Map<String, NodeTypeInfo> nodesInfo) {
+ final Resource cvfc = new Resource();
+ final NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
+ cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
+ cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
+ cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
+ cvfc.setResourceType(ResourceTypeEnum.CVFC);
+ cvfc.setAbstract(true);
+ cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
+ cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
+ cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
+ cvfc.setContactId(csarInfo.getModifier().getUserId());
+ cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
+ cvfc.setVendorName(resourceVf.getVendorName());
+ cvfc.setVendorRelease(resourceVf.getVendorRelease());
+ cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
+ cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
+ cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
+ final List<String> tags = new ArrayList<>();
+ tags.add(cvfc.getName());
+ cvfc.setTags(tags);
+ final CategoryDefinition category = new CategoryDefinition();
+ category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
+ SubCategoryDefinition subCategory = new SubCategoryDefinition();
+ subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
+ category.addSubCategory(subCategory);
+ final List<CategoryDefinition> categories = new ArrayList<>();
+ categories.add(category);
+ cvfc.setCategories(categories);
+ cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
+ cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
+ cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
+ return cvfc;
+ }
+
+ private String buildCvfcName(final String resourceVfName, final String nodeName) {
+ String nameWithouNamespacePrefix = nodeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
+ String[] findTypes = nameWithouNamespacePrefix.split("\\.");
+ String resourceType = findTypes[0];
+ String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
+ return addCvfcSuffixToResourceName(resourceName);
+ }
+
+ private Resource createResourceAndRIsFromYaml(final String yamlName, Resource resource, final ParsedToscaYamlInfo parsedToscaYamlInfo,
+ final AuditingActionEnum actionEnum, final boolean isNormative,
+ final List<ArtifactDefinition> createdArtifacts, final String topologyTemplateYaml,
+ final Map<String, NodeTypeInfo> nodeTypesInfo, final CsarInfo csarInfo,
+ final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
+ final boolean shouldLock, final boolean inTransaction, final String nodeName) {
+ final List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
if (shouldLock) {
- final Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
- CREATE_RESOURCE);
+ final Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, CREATE_RESOURCE);
if (lockResult.isRight()) {
rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
throw new ByResponseFormatComponentException(lockResult.right().value());
@@ -1638,48 +1395,44 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
try {
log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Starting to add inputs from yaml: {}",yamlName);
+ loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
+ "Starting to add inputs from yaml: {}", yamlName);
final Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
resource = createResourceTransaction(resource, csarInfo.getModifier(), isNormative);
log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
log.trace("************* Going to add inputs from yaml {}", yamlName);
- if (resource.shouldGenerateInputs())
+ if (resource.shouldGenerateInputs()) {
generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
-
+ }
final Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
resource = createInputsOnResource(resource, inputs);
log.trace("************* Finish to add inputs from yaml {}", yamlName);
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,
- resource.getComponentMetadataForSupportLog(),
- StatusCode.COMPLETE,"Finish to add inputs from yaml: {}",yamlName);
+ loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
+ "Finish to add inputs from yaml: {}", yamlName);
if (resource.getResourceType() == ResourceTypeEnum.PNF) {
log.trace("************* Adding generic properties to PNF");
- resource = (Resource) propertyBusinessLogic.copyPropertyToComponent(resource,
- genericResource.getProperties());
+ resource = (Resource) propertyBusinessLogic.copyPropertyToComponent(resource, genericResource.getProperties());
log.trace("************* Adding software information to PNF");
softwareInformationBusinessLogic.setSoftwareInformation(resource, csarInfo);
log.trace("************* Removing non-mano software information file from PNF");
- if (csarInfo.getSoftwareInformationPath().isPresent() &&
- !softwareInformationBusinessLogic.removeSoftwareInformationFile(csarInfo)) {
- log.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR , ResourceBusinessLogic.class.getName(),
- "catalog-be", "Could not remove the software information file.");
+ if (csarInfo.getSoftwareInformationPath().isPresent() && !softwareInformationBusinessLogic.removeSoftwareInformationFile(csarInfo)) {
+ log.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(), "catalog-be",
+ "Could not remove the software information file.");
}
}
-
- final Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
- .getInstances();
+ final Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Start create nodes, RI and Relations from yaml: {}",yamlName);
- resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap,
- topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate,
- nodeName);
+ loggerSupportability
+ .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
+ "Start create nodes, RI and Relations from yaml: {}", yamlName);
+ resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, topologyTemplateYaml,
+ nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName);
log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,
- resource.getComponentMetadataForSupportLog(),
- StatusCode.COMPLETE,"Finished to create nodes, RI and Relation from yaml: {}",yamlName);
+ loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
+ "Finished to create nodes, RI and Relation from yaml: {}", yamlName);
// validate update vf module group names
final Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
- .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
+ .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
if (validateUpdateVfGroupNamesRes.isRight()) {
rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right().value());
@@ -1687,2061 +1440,1727 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// add groups to resource
final Map<String, GroupDefinition> groups;
log.trace("************* Going to add groups from yaml {}", yamlName);
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,resource.getComponentMetadataForSupportLog(),
- StatusCode.STARTED,"Start to add groups from yaml: {}",yamlName);
+ loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
+ "Start to add groups from yaml: {}", yamlName);
if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
groups = validateUpdateVfGroupNamesRes.left().value();
} else {
groups = parsedToscaYamlInfo.getGroups();
}
-
- final Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, groups);
- if (createGroupsOnResource.isRight()) {
- rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,
- resource.getComponentMetadataForSupportLog(),
- StatusCode.ERROR,"ERROR while adding groups from yaml: {}",yamlName);
- throw new ByResponseFormatComponentException(createGroupsOnResource.right().value());
- }
- resource = createGroupsOnResource.left().value();
- log.trace("************* Finished to add groups from yaml {}", yamlName);
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,
- resource.getComponentMetadataForSupportLog(),
- StatusCode.COMPLETE,"Finished to add groups from yaml: {}", yamlName);
- log.trace("************* Going to add artifacts from yaml {}", yamlName);
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
- resource.getComponentMetadataForSupportLog(),
- StatusCode.STARTED,"Started to add artifacts from yaml: {}",yamlName);
-
- log.trace("************* Starting to add policies from yaml {}", yamlName);
- Map<String, PolicyDefinition> policies = parsedToscaYamlInfo.getPolicies();
- if (MapUtils.isNotEmpty(policies)) {
- resource = createPoliciesOnResource(resource, policies);
- }
- log.trace("************* Finished to add policies from yaml {}", yamlName);
-
- final NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts =
- new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
-
- final Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(
- ArtifactOperationEnum.CREATE, createdArtifacts, yamlName, csarInfo, resource,
- nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
- if (createArtifactsEither.isRight()) {
- rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
- resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"error happened {}",
- createArtifactsEither.right().value());
- throw new ByResponseFormatComponentException(createArtifactsEither.right().value());
- }
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
- resource.getComponentMetadataForSupportLog(),
- StatusCode.COMPLETE,"Finished to add artifacts from yaml: "+resource.getToscaResourceName());
- final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
- componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
- ASDCKpiApi.countCreatedResourcesKPI();
- return resource;
-
+ final Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, groups);
+ if (createGroupsOnResource.isRight()) {
+ rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
+ loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "ERROR while adding groups from yaml: {}", yamlName);
+ throw new ByResponseFormatComponentException(createGroupsOnResource.right().value());
+ }
+ resource = createGroupsOnResource.left().value();
+ log.trace("************* Finished to add groups from yaml {}", yamlName);
+ loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
+ "Finished to add groups from yaml: {}", yamlName);
+ log.trace("************* Going to add artifacts from yaml {}", yamlName);
+ loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
+ "Started to add artifacts from yaml: {}", yamlName);
+ log.trace("************* Starting to add policies from yaml {}", yamlName);
+ Map<String, PolicyDefinition> policies = parsedToscaYamlInfo.getPolicies();
+ if (MapUtils.isNotEmpty(policies)) {
+ resource = createPoliciesOnResource(resource, policies);
+ }
+ log.trace("************* Finished to add policies from yaml {}", yamlName);
+ final NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
+ nodeTypesArtifactsToCreate);
+ final Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.CREATE, createdArtifacts,
+ yamlName, csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
+ if (createArtifactsEither.isRight()) {
+ rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
+ loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "error happened {}", createArtifactsEither.right().value());
+ throw new ByResponseFormatComponentException(createArtifactsEither.right().value());
+ }
+ loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
+ "Finished to add artifacts from yaml: " + resource.getToscaResourceName());
+ final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
+ componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
+ ASDCKpiApi.countCreatedResourcesKPI();
+ return resource;
} catch (final BusinessLogicException e) {
- log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(),
- "An error has occurred during resource and resource instance creation", e);
+ log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(),
+ "An error has occurred during resource and resource instance creation", e);
rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
throw new ByResponseFormatComponentException(e.getResponseFormat());
} catch (final Exception e) {
- log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(),
- "An error has occurred during resource and resource instance creation", e);
- rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
- throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
+ log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(),
+ "An error has occurred during resource and resource instance creation", e);
+ rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
+ throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
} finally {
if (!inTransaction) {
janusGraphDao.commit();
- }
- if (shouldLock) {
- graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
- NodeTypeEnum.Resource);
- }
- }
- }
-
- private void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts,
- List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
- if (!inTransaction) {
+ }
+ if (shouldLock) {
+ graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
+ }
+ }
+ }
+
+ private void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts,
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
+ if (!inTransaction) {
janusGraphDao.rollback();
- }
- if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
- createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
- log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(),
- resource.getName());
- }
- }
-
- private Resource getResourceWithGroups(String resourceId) {
-
- ComponentParametersView filter = new ComponentParametersView();
- filter.setIgnoreGroups(false);
- Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId,
- filter);
- if (updatedResource.isRight()) {
- rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right()
- .value()), resourceId);
- }
- return updatedResource.left()
- .value();
- }
-
- private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource,
- Map<String, GroupDefinition> groups) {
- if (groups != null && !groups.isEmpty()) {
- List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
- handleGroupsProperties(resource, groups);
- fillGroupsFinalFields(groupsAsList);
- Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource,
- groupsAsList, true);
- if (createGroups.isRight()) {
- return Either.right(createGroups.right()
- .value());
- }
- }
- return Either.left(resource);
- }
-
- private void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
- List<InputDefinition> inputs = resource.getInputs();
- if (MapUtils.isNotEmpty(groups)) {
- groups.values()
- .stream()
- .filter(g -> isNotEmpty(g.getProperties()))
- .flatMap(g -> g.getProperties()
- .stream())
- .forEach(p -> handleGetInputs(p, inputs));
- }
- }
+ }
+ if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
+ createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
+ log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(), resource.getName());
+ }
+ }
+
+ private Resource getResourceWithGroups(String resourceId) {
+ ComponentParametersView filter = new ComponentParametersView();
+ filter.setIgnoreGroups(false);
+ Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
+ if (updatedResource.isRight()) {
+ rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
+ }
+ return updatedResource.left().value();
+ }
+
+ private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
+ if (groups != null && !groups.isEmpty()) {
+ List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
+ handleGroupsProperties(resource, groups);
+ fillGroupsFinalFields(groupsAsList);
+ Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, groupsAsList, true);
+ if (createGroups.isRight()) {
+ return Either.right(createGroups.right().value());
+ }
+ }
+ return Either.left(resource);
+ }
+
+ private void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
+ List<InputDefinition> inputs = resource.getInputs();
+ if (MapUtils.isNotEmpty(groups)) {
+ groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream())
+ .forEach(p -> handleGetInputs(p, inputs));
+ }
+ }
private Resource createPoliciesOnResource(Resource resource, Map<String, PolicyDefinition> policies) {
- policyBusinessLogic.createPoliciesFromParsedCsar(resource, policies);
- return resource;
- }
-
- private void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
- if (isNotEmpty(property.getGetInputValues())) {
- if (inputs == null || inputs.isEmpty()) {
- log.debug("Failed to add property {} to group. Inputs list is empty ", property);
- rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
- .stream()
- .map(GetInputValueDataDefinition::getInputName)
- .collect(toList())
- .toString());
- }
- ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues()
- .listIterator();
- while (getInputValuesIter.hasNext()) {
- GetInputValueDataDefinition getInput = getInputValuesIter.next();
- Either<InputDefinition, RuntimeException> inputEither = findInputByName(inputs, getInput);
- if (inputEither.isRight()) {
- throw inputEither.right().value();
- } else {
- InputDefinition input = inputEither.left().value();
- getInput.setInputId(input.getUniqueId());
- if (getInput.getGetInputIndex() != null) {
- GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
- Either<InputDefinition, RuntimeException> newInputEither = findInputByName(inputs,
- getInputIndex);
- if (newInputEither.isRight()) {
- throw newInputEither.right().value();
- } else {
- InputDefinition newInput = newInputEither.left().value();
- getInputIndex.setInputId(newInput.getUniqueId());
- }
- getInputValuesIter.add(getInputIndex);
- }
- }
- }
- }
- }
-
- static <T> Either<T, RuntimeException> rollbackWithEither(
- final JanusGraphDao janusGraphDao,
- final ActionStatus actionStatus,
- final String... params) {
- if (janusGraphDao != null)
- janusGraphDao.rollback();
- return Either.right(new ByActionStatusComponentException(actionStatus, params));
- }
-
- <T> Either<T, RuntimeException> rollbackWithEither(
- final ActionStatus actionStatus,
- final String... params) {
- return rollbackWithEither(janusGraphDao, actionStatus, params);
- }
-
- private Either<InputDefinition, RuntimeException> findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
-
- final String inputName = getInput != null ? getInput.getInputName() : "";
-
- if(inputs == null || inputs.isEmpty()) {
- log.debug("#findInputByName - Inputs list is empty");
- return rollbackWithEither(ActionStatus.INPUTS_NOT_FOUND, inputName);
- } else {
- Optional<InputDefinition> inputOpt = inputs.stream()
- .filter(p -> p.getName().equals(inputName))
- .findFirst();
- if (!inputOpt.isPresent()) {
- log.debug("#findInputByName - Failed to find the input {} ", inputName);
- return rollbackWithEither(ActionStatus.INPUTS_NOT_FOUND, inputName);
- } else {
- return Either.left(inputOpt.get());
- }
- }
- }
-
- private void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
- groupsAsList.forEach(groupDefinition -> {
- groupDefinition.setInvariantName(groupDefinition.getName());
- groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
- });
- }
-
- private Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
- if (isEmpty(groups)) {
- return resource;
- }
- return updateOrCreateGroups(resource, groups);
- }
-
- private Resource updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
- List<GroupDefinition> groupsFromResource = resource.getGroups();
- List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
- List<GroupDefinition> groupsToUpdate = new ArrayList<>();
- List<GroupDefinition> groupsToDelete = new ArrayList<>();
- List<GroupDefinition> groupsToCreate = new ArrayList<>();
- if (isNotEmpty(groupsFromResource)) {
- addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
- addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
- } else {
- groupsToCreate.addAll(groupsAsList);
- }
- if (isNotEmpty(groupsToCreate)) {
- fillGroupsFinalFields(groupsToCreate);
- if (isNotEmpty(groupsFromResource)) {
- groupBusinessLogic.addGroups(resource, groupsToCreate, true)
- .left()
- .on(this::throwComponentException);
- } else {
- groupBusinessLogic.createGroups(resource, groupsToCreate, true)
- .left()
- .on(this::throwComponentException);
- }
- }
- if (isNotEmpty(groupsToDelete)) {
- groupBusinessLogic.deleteGroups(resource, groupsToDelete)
- .left()
- .on(this::throwComponentException);
- }
- if (isNotEmpty(groupsToUpdate)) {
- groupBusinessLogic.updateGroups(resource, groupsToUpdate, true)
- .left()
- .on(this::throwComponentException);
- }
- return resource;
-
- }
-
- private void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
- List<GroupDefinition> groupsToDelete) {
- for (GroupDefinition group : groupsFromResource) {
- Optional<GroupDefinition> op = groupsAsList.stream()
- .filter(p -> p.getInvariantName()
- .equalsIgnoreCase(group.getInvariantName()))
- .findAny();
- if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts()
- .isEmpty())) {
- groupsToDelete.add(group);
- }
- }
- }
-
- private void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
- List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
- for (GroupDefinition group : groupsAsList) {
- Optional<GroupDefinition> op = groupsFromResource.stream()
- .filter(p -> p.getInvariantName()
- .equalsIgnoreCase(group.getInvariantName()))
- .findAny();
- if (op.isPresent()) {
- GroupDefinition groupToUpdate = op.get();
- groupToUpdate.setMembers(group.getMembers());
- groupToUpdate.setCapabilities(group.getCapabilities());
- groupToUpdate.setProperties(group.getProperties());
- groupsToUpdate.add(groupToUpdate);
- } else {
- groupsToCreate.add(group);
- }
- }
- }
-
- private Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
- List<InputDefinition> resourceProperties = resource.getInputs();
- if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
-
- Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
- resource);
- if (createInputs.isRight()) {
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(),
- StatusCode.ERROR,"failed to add inputs from yaml: {}",createInputs.right()
- .value());
- throw new ByResponseFormatComponentException(createInputs.right()
- .value());
- }
- resource.setInputs(createInputs.left().value());
- }
- return resource;
- }
-
- private List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups,
- Resource component) {
-
- List<GroupDefinition> result = new ArrayList<>();
- List<ComponentInstance> componentInstances = component.getComponentInstances();
-
- if (groups != null) {
- Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
- if (validateCyclicGroupsDependencies.isRight()) {
- throw new ByResponseFormatComponentException(validateCyclicGroupsDependencies.right().value());
- }
- for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
- String groupName = entry.getKey();
- GroupDefinition groupDefinition = entry.getValue();
- GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
- updatedGroupDefinition.setMembers(null);
- Map<String, String> members = groupDefinition.getMembers();
- if (members != null) {
- updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName,
- members);
- }
- result.add(updatedGroupDefinition);
- }
- }
- return result;
- }
-
- private void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition,
- Resource component, List<ComponentInstance> componentInstances, String groupName,
- Map<String, String> members) {
- Set<String> compInstancesNames = members.keySet();
-
- if (CollectionUtils.isEmpty(componentInstances)) {
- String membersAstString = compInstancesNames.stream()
- .collect(joining(","));
- log.debug(
- "The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
- membersAstString, groupName, component.getNormalizedName());
- throw new ByActionStatusComponentException(
- ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString,
- groupName, component.getNormalizedName(), getComponentTypeForResponse(component));
- }
- // Find all component instances with the member names
- Map<String, String> memberNames = componentInstances.stream()
- .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
- memberNames.putAll(groups.keySet()
- .stream()
- .collect(toMap(g -> g, g -> "")));
- Map<String, String> relevantInstances = memberNames.entrySet()
- .stream()
- .filter(n -> compInstancesNames.contains(n.getKey()))
- .collect(toMap(Entry::getKey, Entry::getValue));
-
- if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
-
- List<String> foundMembers = new ArrayList<>();
- if (relevantInstances != null) {
- foundMembers = relevantInstances.keySet()
- .stream()
- .collect(toList());
- }
- compInstancesNames.removeAll(foundMembers);
- String membersAstString = compInstancesNames.stream()
- .collect(joining(","));
- log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName,
- component.getNormalizedName());
- throw new ByActionStatusComponentException(
- ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString,
- groupName, component.getNormalizedName(), getComponentTypeForResponse(component));
- }
- updatedGroupDefinition.setMembers(relevantInstances);
- }
-
- /**
- * This Method validates that there is no cyclic group dependencies. meaning
- * group A as member in group B which is member in group A
- *
- * @param allGroups
- * @return
- */
- private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
-
- Either<Boolean, ResponseFormat> result = Either.left(true);
- try {
- Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet()
- .iterator();
- while (allGroupsItr.hasNext() && result.isLeft()) {
- Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
- // Fetches a group member A
- String groupAName = groupAEntry.getKey();
- // Finds all group members in group A
- Set<String> allGroupAMembersNames = new HashSet<>();
- fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
- // If A is a group member of itself found cyclic dependency
- if (allGroupAMembersNames.contains(groupAName)) {
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
- result = Either.right(responseFormat);
- }
- }
- } catch (Exception e) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- result = Either.right(responseFormat);
- log.debug("Exception occurred when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
- }
- return result;
- }
-
- /**
- * This Method fills recursively the set groupMembers with all the members
- * of the given group which are also of type group.
- *
- * @param groupName
- * @param allGroups
- * @param allGroupMembers
- * @return
- */
- private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups,
- Set<String> allGroupMembers) {
-
- // Found Cyclic dependency
- if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
- return;
- }
- GroupDefinition groupDefinition = allGroups.get(groupName);
- // All Members Of Current Group Resource Instances & Other Groups
- Set<String> currGroupMembers = groupDefinition.getMembers()
- .keySet();
- // Filtered Members Of Current Group containing only members which
- // are groups
- List<String> currGroupFilteredMembers = currGroupMembers.stream()
- .
- // Keep Only Elements of type group and not Resource Instances
- filter(allGroups::containsKey)
- .
- // Add Filtered Elements to main Set
- peek(allGroupMembers::add)
- .
- // Collect results
- collect(toList());
-
- // Recursively call the method for all the filtered group members
- for (String innerGroupName : currGroupFilteredMembers) {
- fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
- }
-
- }
-
- private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
- Set<String> allGroupMembers) {
-
- boolean stop = false;
- // In Case Not Group Stop
- if (!allGroups.containsKey(groupName)) {
- stop = true;
- }
- // In Case Group Has no members stop
- if (!stop) {
- GroupDefinition groupDefinition = allGroups.get(groupName);
- stop = isEmpty(groupDefinition.getMembers());
-
- }
- // In Case all group members already contained stop
- if (!stop) {
- final Set<String> allMembers = allGroups.get(groupName)
- .getMembers()
- .keySet();
- Set<String> membersOfTypeGroup = allMembers.stream()
- .
- // Filter In Only Group members
- filter(allGroups::containsKey)
- .
- // Collect
- collect(toSet());
- stop = allGroupMembers.containsAll(membersOfTypeGroup);
- }
- return stop;
- }
-
- private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
- Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, String topologyTemplateYaml,
- List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
- CsarInfo csarInfo,
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
- String nodeName) {
-
- log.debug("************* Going to create all nodes {}", yamlName);
- handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate,
- nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeName);
- log.debug("************* Finished to create all nodes {}", yamlName);
- log.debug("************* Going to create all resource instances {}", yamlName);
- Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>();
- resource = createResourceInstances(yamlName, resource, null, uploadComponentInstanceInfoMap,
- csarInfo.getCreatedNodes(), existingNodeTypesByResourceNames);
- log.debug("************* Finished to create all resource instances {}", yamlName);
- log.debug("************* Going to create all relations {}", yamlName);
- resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, null, uploadComponentInstanceInfoMap, existingNodeTypesByResourceNames);
- log.debug("************* Finished to create all relations {}", yamlName);
- log.debug("************* Going to create positions {}", yamlName);
- compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier()
- .getUserId());
- log.debug("************* Finished to set positions {}", yamlName);
- return resource;
- }
-
- private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts,
- List<ArtifactDefinition> artifactsToAdd) {
- List<String> vfcArtifactNames = vfcArtifacts.stream()
- .map(ArtifactDataDefinition::getArtifactName)
- .collect(toList());
- artifactsToAdd.stream()
- .forEach(a -> {
- if (!vfcArtifactNames.contains(a.getArtifactName())) {
- vfcArtifacts.add(a);
- } else {
- log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
- }
- });
-
- }
-
- @SuppressWarnings("unchecked")
- private void handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
- List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
- CsarInfo csarInfo, String nodeName) {
- try {
- for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
- if (nodeTypeEntry.getValue()
- .isNested()) {
-
- handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo,
- csarInfo, nodeTypeEntry.getKey());
- log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
- }
- }
- Map<String, Object> mappedToscaTemplate = null;
- if (StringUtils.isNotEmpty(nodeName) && isNotEmpty(nodeTypesInfo) && nodeTypesInfo.containsKey(nodeName)) {
- mappedToscaTemplate = nodeTypesInfo.get(nodeName)
- .getMappedToscaTemplate();
- }
- if (isEmpty(mappedToscaTemplate)) {
- mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
- }
- createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock,
- nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
- } catch (ComponentException e) {
- ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
- : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
- componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
- AuditingActionEnum.IMPORT_RESOURCE);
- throw e;
- } catch (StorageException e) {
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
- componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
- AuditingActionEnum.IMPORT_RESOURCE);
- throw e;
- }
- }
-
- private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo,
- List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
- boolean inTransaction) {
-
- if (csarInfo.getCsar() != null) {
- String vendorLicenseModelId = null;
- String vfLicenseModelId = null;
-
- if (artifactOperation.isUpdate()) {
- Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
- if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
- for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
- if (artifactEntry.getValue()
- .getArtifactName()
- .equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
- vendorLicenseModelId = artifactEntry.getValue()
- .getUniqueId();
- }
- if (artifactEntry.getValue()
- .getArtifactName()
- .equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
- vfLicenseModelId = artifactEntry.getValue()
- .getUniqueId();
- }
- }
- }
-
- }
- // Specific Behavior for license artifacts
- createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
- CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
- ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
- Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
- Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true,
- shouldLock, inTransaction);
- createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
- CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
- ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
- Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
- artifactOperation, null, true, shouldLock, inTransaction);
-
- Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource,
- createdArtifacts, shouldLock, inTransaction, artifactOperation);
- if (eitherCreateResult.isRight()) {
- return Either.right(eitherCreateResult.right()
- .value());
- }
-
- Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
- .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
-
- if (artifacsMetaCsarStatus.isLeft()) {
- String artifactsFileName = artifacsMetaCsarStatus.left()
- .value()
- .getKey();
- String artifactsContents = artifacsMetaCsarStatus.left()
- .value()
- .getValue();
- Either<Resource, ResponseFormat> createArtifactsFromCsar;
- if (artifactOperation.isCreateOrLink()) {
- createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(
- csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts);
- } else {
- Either<Component, ResponseFormat> result = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(
- csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock,
- inTransaction);
- if ((result.left().value() instanceof Resource) && result.isLeft()) {
- Resource service1 = (Resource) result.left().value();
- createArtifactsFromCsar = Either.left(service1);
- } else {
- createArtifactsFromCsar = Either.right(result.right().value());
- }
- }
-
- if (createArtifactsFromCsar.isRight()) {
- log.debug("Couldn't create artifacts from artifacts.meta");
- return Either.right(createArtifactsFromCsar.right()
- .value());
- }
-
- return Either.left(createArtifactsFromCsar.left()
- .value());
- } else {
-
- return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock,
- inTransaction);
-
- }
- }
- return Either.left(resource);
- }
-
- private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo,
- String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType,
- String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId,
- ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean isFromCsar,
- boolean shouldLock, boolean inTransaction) {
- byte[] artifactFileBytes = null;
-
- if (csarInfo.getCsar()
- .containsKey(artifactPath)) {
- artifactFileBytes = csarInfo.getCsar()
- .get(artifactPath);
- }
- Either<Boolean, ResponseFormat> result = Either.left(true);
- if (operation.isUpdate() || operation.isDelete()) {
- if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
- Either<ArtifactDefinition, ResponseFormat> handleDelete = artifactsBusinessLogic
- .handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(),
- resource, shouldLock,
- inTransaction);
- if (handleDelete.isRight()) {
- result = Either.right(handleDelete.right()
- .value());
- } else {
- ArtifactDefinition value = handleDelete.left().value();
- String updatedArtifactId = value.getUniqueId();
- if (artifactGroupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
- resource.getDeploymentArtifacts().remove(updatedArtifactId);
- } else {
- resource.getArtifacts().remove(updatedArtifactId);
- }
- }
- return result;
- }
-
- if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
- operation = new ArtifactOperationInfo(false, false,
- ArtifactOperationEnum.CREATE);
- }
-
- }
- if (artifactFileBytes != null) {
- Map<String, Object> vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId,
- artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName,
- artifactDescription, artifactFileBytes, null, isFromCsar);
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic
- .createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), vendorLicenseModelJson,
- operation);
- addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
- if (eitherNonMetaArtifacts.isRight()) {
- BeEcompErrorManager.getInstance()
- .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: "
- + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
- ErrorSeverity.WARNING);
- return Either.right(eitherNonMetaArtifacts.right()
- .value());
- }
- ArtifactDefinition artifactDefinition = eitherNonMetaArtifacts.left().value().left().value();
- createOrUpdateResourceWithUpdatedArtifact(artifactDefinition,resource, artifactGroupType);
- }
-
- return result;
- }
-
- private void createOrUpdateResourceWithUpdatedArtifact(ArtifactDefinition artifact, Resource resource, ArtifactGroupTypeEnum groupTypeEnum) {
- if (groupTypeEnum == ArtifactGroupTypeEnum.DEPLOYMENT) {
- resource.getDeploymentArtifacts().put(artifact.getArtifactLabel(), artifact);
- } else {
- resource.getArtifacts().put(artifact.getArtifactLabel(), artifact);
- }
- }
-
- private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
- return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
- }
-
- private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation,
- List<ArtifactDefinition> createdArtifacts,
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
- if (operation.isCreateOrLink() && createdArtifacts != null
- && eitherNonMetaArtifacts.isLeft()) {
- Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left()
- .value();
- if (eitherResult.isLeft()) {
- createdArtifacts.add(eitherResult.left()
- .value());
- }
- }
- }
-
- private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
- List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
- ArtifactOperationInfo artifactOperation) {
-
- Either<Resource, ResponseFormat> resStatus = null;
- Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
-
- try {
- Either<List<NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo,
- collectedWarningMessages);
- if (artifactPathAndNameList.isRight()) {
- return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
- ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right()
- .value()));
- }
- EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
-
- if (artifactOperation.isCreateOrLink()) {
- vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
- vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left()
- .value());
- } else {
- Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
- resource, artifactPathAndNameList.left()
- .value(),
- csarInfo.getModifier());
-
- if (findVfCsarArtifactsToHandleRes.isRight()) {
- resStatus = Either.right(findVfCsarArtifactsToHandleRes.right()
- .value());
- }
- if (resStatus == null) {
- vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left()
- .value();
- }
- }
- if (resStatus == null && vfCsarArtifactsToHandle != null) {
- resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction,
- resStatus, vfCsarArtifactsToHandle);
- }
- if (resStatus == null) {
- resStatus = Either.left(resource);
- }
- } catch (Exception e) {
- resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- log.debug("Exception occurred in createNonMetaArtifacts, message:{}", e.getMessage(), e);
- } finally {
- CsarUtils.handleWarningMessages(collectedWarningMessages);
- }
- return resStatus;
- }
-
- private Either<Resource, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Resource resource,
- List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
- Either<Resource, ResponseFormat> resStatus,
- EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
- for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
- .entrySet()) {
-
- Optional<ResponseFormat> optionalCreateInDBError =
- // Stream of artifacts to be created
- currArtifactOperationPair.getValue()
- .stream()
- // create each artifact
- .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(),
- e.getArtifactName(), e.getArtifactType(),
- e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
- CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
- new ArtifactOperationInfo(false, false,
- currArtifactOperationPair.getKey()),
- createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
- // filter in only error
- .filter(Either::isRight)
- .
- // Convert the error from either to
- // ResponseFormat
- map(e -> e.right()
- .value())
- .
- // Check if an error occurred
- findAny();
- // Error found on artifact Creation
- if (optionalCreateInDBError.isPresent()) {
- resStatus = Either.right(optionalCreateInDBError.get());
- break;
- }
- }
- return resStatus;
- }
-
- private Either<List<NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo,
- Map<String, Set<List<String>>> collectedWarningMessages) {
- List<NonMetaArtifactInfo> artifactPathAndNameList =
- // Stream of file paths contained in csar
- csarInfo.getCsar()
- .entrySet()
- .stream()
- // Filter in only VF artifact path location
- .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN)
- .matcher(e.getKey())
- .matches())
- // Validate and add warnings
- .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages))
- // Filter in Non Warnings
- .filter(Either::isLeft)
- // Convert from Either to NonMetaArtifactInfo
- .map(e -> e.left()
- .value())
- // collect to List
- .collect(toList());
- Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
- for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
- if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName())
- .matches()) {
- return Either.right(nonMetaArtifactInfo.getArtifactName());
- }
- }
- return Either.left(artifactPathAndNameList);
- }
-
- private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
- Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
-
- List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
- // collect all Deployment and Informational artifacts of VF
- if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts()
- .isEmpty()) {
- existingArtifacts.addAll(resource.getDeploymentArtifacts()
- .values());
- }
- if (resource.getArtifacts() != null && !resource.getArtifacts()
- .isEmpty()) {
- existingArtifacts.addAll(resource.getArtifacts()
- .values());
- }
- existingArtifacts = existingArtifacts.stream()
- // filter MANDATORY artifacts, LICENSE artifacts and artifacts
- // was created from HEAT.meta
- .filter(this::isNonMetaArtifact)
- .collect(toList());
-
- List<String> artifactsToIgnore = new ArrayList<>();
- // collect IDs of Artifacts of VF which belongs to any group
- if (resource.getGroups() != null) {
- resource.getGroups()
- .stream()
- .forEach(g -> {
- if (g.getArtifacts() != null && !g.getArtifacts()
- .isEmpty()) {
- artifactsToIgnore.addAll(g.getArtifacts());
- }
- });
- }
- existingArtifacts = existingArtifacts.stream()
- // filter artifacts which belongs to any group
- .filter(a -> !artifactsToIgnore.contains(a.getUniqueId()))
- .collect(toList());
- return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
- }
-
- private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
- boolean result = true;
- if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
- result = false;
- }
- return result;
- }
-
- private boolean isValidArtifactType(ArtifactDefinition artifact) {
- boolean result = true;
- if (artifact.getArtifactType() == null
- || ArtifactTypeEnum.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE
- || ArtifactTypeEnum.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
- result = false;
- }
- return result;
- }
-
- private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource, Resource oldResource,
- Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, Map<String, Resource> existingNodeTypesByResourceNames) {
- log.debug("#createResourceInstancesRelations - Going to create relations ");
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Start to create relations");
- List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
- if (isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList) &&
- resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances {
- log.debug(
- "#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
- resource.getUniqueId(), yamlName);
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"No instances found in the resource: {}, is empty, yaml template file name: {}",resource.getName(),yamlName);
- BeEcompErrorManager.getInstance()
- .logInternalDataError("createResourceInstancesRelations",
- "No instances found in a resource or nn yaml template. ", ErrorSeverity.ERROR);
- throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
- }
- Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
- Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
- Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
- Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
- Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
+ policyBusinessLogic.createPoliciesFromParsedCsar(resource, policies);
+ return resource;
+ }
+
+ private void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
+ if (isNotEmpty(property.getGetInputValues())) {
+ if (inputs == null || inputs.isEmpty()) {
+ log.debug("Failed to add property {} to group. Inputs list is empty ", property);
+ rollbackWithException(ActionStatus.INPUTS_NOT_FOUND,
+ property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
+ }
+ ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues().listIterator();
+ while (getInputValuesIter.hasNext()) {
+ GetInputValueDataDefinition getInput = getInputValuesIter.next();
+ Either<InputDefinition, RuntimeException> inputEither = findInputByName(inputs, getInput);
+ if (inputEither.isRight()) {
+ throw inputEither.right().value();
+ } else {
+ InputDefinition input = inputEither.left().value();
+ getInput.setInputId(input.getUniqueId());
+ if (getInput.getGetInputIndex() != null) {
+ GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
+ Either<InputDefinition, RuntimeException> newInputEither = findInputByName(inputs, getInputIndex);
+ if (newInputEither.isRight()) {
+ throw newInputEither.right().value();
+ } else {
+ InputDefinition newInput = newInputEither.left().value();
+ getInputIndex.setInputId(newInput.getUniqueId());
+ }
+ getInputValuesIter.add(getInputIndex);
+ }
+ }
+ }
+ }
+ }
+
+ <T> Either<T, RuntimeException> rollbackWithEither(final ActionStatus actionStatus, final String... params) {
+ return rollbackWithEither(janusGraphDao, actionStatus, params);
+ }
+
+ private Either<InputDefinition, RuntimeException> findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
+ final String inputName = getInput != null ? getInput.getInputName() : "";
+ if (inputs == null || inputs.isEmpty()) {
+ log.debug("#findInputByName - Inputs list is empty");
+ return rollbackWithEither(ActionStatus.INPUTS_NOT_FOUND, inputName);
+ } else {
+ Optional<InputDefinition> inputOpt = inputs.stream().filter(p -> p.getName().equals(inputName)).findFirst();
+ if (!inputOpt.isPresent()) {
+ log.debug("#findInputByName - Failed to find the input {} ", inputName);
+ return rollbackWithEither(ActionStatus.INPUTS_NOT_FOUND, inputName);
+ } else {
+ return Either.left(inputOpt.get());
+ }
+ }
+ }
+
+ private void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
+ groupsAsList.forEach(groupDefinition -> {
+ groupDefinition.setInvariantName(groupDefinition.getName());
+ groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
+ });
+ }
+
+ private Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
+ if (isEmpty(groups)) {
+ return resource;
+ }
+ return updateOrCreateGroups(resource, groups);
+ }
+
+ private Resource updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
+ List<GroupDefinition> groupsFromResource = resource.getGroups();
+ List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
+ List<GroupDefinition> groupsToUpdate = new ArrayList<>();
+ List<GroupDefinition> groupsToDelete = new ArrayList<>();
+ List<GroupDefinition> groupsToCreate = new ArrayList<>();
+ if (isNotEmpty(groupsFromResource)) {
+ addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
+ addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
+ } else {
+ groupsToCreate.addAll(groupsAsList);
+ }
+ if (isNotEmpty(groupsToCreate)) {
+ fillGroupsFinalFields(groupsToCreate);
+ if (isNotEmpty(groupsFromResource)) {
+ groupBusinessLogic.addGroups(resource, groupsToCreate, true).left().on(this::throwComponentException);
+ } else {
+ groupBusinessLogic.createGroups(resource, groupsToCreate, true).left().on(this::throwComponentException);
+ }
+ }
+ if (isNotEmpty(groupsToDelete)) {
+ groupBusinessLogic.deleteGroups(resource, groupsToDelete).left().on(this::throwComponentException);
+ }
+ if (isNotEmpty(groupsToUpdate)) {
+ groupBusinessLogic.updateGroups(resource, groupsToUpdate, true).left().on(this::throwComponentException);
+ }
+ return resource;
+ }
+
+ private void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
+ List<GroupDefinition> groupsToDelete) {
+ for (GroupDefinition group : groupsFromResource) {
+ Optional<GroupDefinition> op = groupsAsList.stream().filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName()))
+ .findAny();
+ if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
+ groupsToDelete.add(group);
+ }
+ }
+ }
+
+ private void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
+ List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
+ for (GroupDefinition group : groupsAsList) {
+ Optional<GroupDefinition> op = groupsFromResource.stream().filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName()))
+ .findAny();
+ if (op.isPresent()) {
+ GroupDefinition groupToUpdate = op.get();
+ groupToUpdate.setMembers(group.getMembers());
+ groupToUpdate.setCapabilities(group.getCapabilities());
+ groupToUpdate.setProperties(group.getProperties());
+ groupsToUpdate.add(groupToUpdate);
+ } else {
+ groupsToCreate.add(group);
+ }
+ }
+ }
+
+ private Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
+ List<InputDefinition> resourceProperties = resource.getInputs();
+ if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
+ Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource);
+ if (createInputs.isRight()) {
+ loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "failed to add inputs from yaml: {}", createInputs.right().value());
+ throw new ByResponseFormatComponentException(createInputs.right().value());
+ }
+ resource.setInputs(createInputs.left().value());
+ }
+ return resource;
+ }
+
+ private List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
+ List<GroupDefinition> result = new ArrayList<>();
+ List<ComponentInstance> componentInstances = component.getComponentInstances();
+ if (groups != null) {
+ Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
+ if (validateCyclicGroupsDependencies.isRight()) {
+ throw new ByResponseFormatComponentException(validateCyclicGroupsDependencies.right().value());
+ }
+ for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
+ String groupName = entry.getKey();
+ GroupDefinition groupDefinition = entry.getValue();
+ GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
+ updatedGroupDefinition.setMembers(null);
+ Map<String, String> members = groupDefinition.getMembers();
+ if (members != null) {
+ updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
+ }
+ result.add(updatedGroupDefinition);
+ }
+ }
+ return result;
+ }
+
+ private void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Resource component,
+ List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
+ Set<String> compInstancesNames = members.keySet();
+ if (CollectionUtils.isEmpty(componentInstances)) {
+ String membersAstString = compInstancesNames.stream().collect(joining(","));
+ log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString,
+ groupName, component.getNormalizedName());
+ throw new ByActionStatusComponentException(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
+ component.getNormalizedName(), getComponentTypeForResponse(component));
+ }
+ // Find all component instances with the member names
+ Map<String, String> memberNames = componentInstances.stream().collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
+ memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
+ Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey()))
+ .collect(toMap(Entry::getKey, Entry::getValue));
+ if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
+ List<String> foundMembers = new ArrayList<>();
+ if (relevantInstances != null) {
+ foundMembers = relevantInstances.keySet().stream().collect(toList());
+ }
+ compInstancesNames.removeAll(foundMembers);
+ String membersAstString = compInstancesNames.stream().collect(joining(","));
+ log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName());
+ throw new ByActionStatusComponentException(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
+ component.getNormalizedName(), getComponentTypeForResponse(component));
+ }
+ updatedGroupDefinition.setMembers(relevantInstances);
+ }
+
+ /**
+ * This Method validates that there is no cyclic group dependencies. meaning group A as member in group B which is member in group A
+ *
+ * @param allGroups
+ * @return
+ */
+ private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
+ Either<Boolean, ResponseFormat> result = Either.left(true);
+ try {
+ Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
+ while (allGroupsItr.hasNext() && result.isLeft()) {
+ Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
+ // Fetches a group member A
+ String groupAName = groupAEntry.getKey();
+ // Finds all group members in group A
+ Set<String> allGroupAMembersNames = new HashSet<>();
+ fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
+ // If A is a group member of itself found cyclic dependency
+ if (allGroupAMembersNames.contains(groupAName)) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
+ result = Either.right(responseFormat);
+ }
+ }
+ } catch (Exception e) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ result = Either.right(responseFormat);
+ log.debug("Exception occurred when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
+ }
+ return result;
+ }
+
+ /**
+ * This Method fills recursively the set groupMembers with all the members of the given group which are also of type group.
+ *
+ * @param groupName
+ * @param allGroups
+ * @param allGroupMembers
+ * @return
+ */
+ private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups, Set<String> allGroupMembers) {
+ // Found Cyclic dependency
+ if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
+ return;
+ }
+ GroupDefinition groupDefinition = allGroups.get(groupName);
+ // All Members Of Current Group Resource Instances & Other Groups
+ Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
+ // Filtered Members Of Current Group containing only members which
+
+ // are groups
+ List<String> currGroupFilteredMembers = currGroupMembers.stream().
+ // Keep Only Elements of type group and not Resource Instances
+ filter(allGroups::containsKey).
+ // Add Filtered Elements to main Set
+ peek(allGroupMembers::add).
+ // Collect results
+ collect(toList());
+ // Recursively call the method for all the filtered group members
+ for (String innerGroupName : currGroupFilteredMembers) {
+ fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
+ }
+ }
+
+ private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
+ Set<String> allGroupMembers) {
+ boolean stop = false;
+ // In Case Not Group Stop
+ if (!allGroups.containsKey(groupName)) {
+ stop = true;
+ }
+ // In Case Group Has no members stop
+ if (!stop) {
+ GroupDefinition groupDefinition = allGroups.get(groupName);
+ stop = isEmpty(groupDefinition.getMembers());
+ }
+ // In Case all group members already contained stop
+ if (!stop) {
+ final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
+ Set<String> membersOfTypeGroup = allMembers.stream().
+ // Filter In Only Group members
+ filter(allGroups::containsKey).
+ // Collect
+ collect(toSet());
+ stop = allGroupMembers.containsAll(membersOfTypeGroup);
+ }
+ return stop;
+ }
+
+ private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
+ Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
+ String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
+ Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
+ String nodeName) {
+ log.debug("************* Going to create all nodes {}", yamlName);
+ handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, nodeTypesInfo,
+ csarInfo, nodeName);
+ log.debug("************* Finished to create all nodes {}", yamlName);
+ log.debug("************* Going to create all resource instances {}", yamlName);
+ Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>();
+ resource = createResourceInstances(yamlName, resource, null, uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes(),
+ existingNodeTypesByResourceNames);
+ log.debug("************* Finished to create all resource instances {}", yamlName);
+ log.debug("************* Going to create all relations {}", yamlName);
+ resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, null, uploadComponentInstanceInfoMap,
+ existingNodeTypesByResourceNames);
+ log.debug("************* Finished to create all relations {}", yamlName);
+ log.debug("************* Going to create positions {}", yamlName);
+ compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
+ log.debug("************* Finished to set positions {}", yamlName);
+ return resource;
+ }
+
+ private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts, List<ArtifactDefinition> artifactsToAdd) {
+ List<String> vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName).collect(toList());
+ artifactsToAdd.stream().forEach(a -> {
+ if (!vfcArtifactNames.contains(a.getArtifactName())) {
+ vfcArtifacts.add(a);
+ } else {
+ log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
+ }
+ });
+ }
+
+ @SuppressWarnings("unchecked")
+ private void handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
+ String nodeName) {
+ try {
+ for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
+ if (nodeTypeEntry.getValue().isNested()) {
+ handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
+ nodeTypeEntry.getKey());
+ log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
+ }
+ }
+ Map<String, Object> mappedToscaTemplate = null;
+ if (StringUtils.isNotEmpty(nodeName) && isNotEmpty(nodeTypesInfo) && nodeTypesInfo.containsKey(nodeName)) {
+ mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
+ }
+ if (isEmpty(mappedToscaTemplate)) {
+ mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
+ }
+ createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
+ nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
+ } catch (ComponentException e) {
+ ResponseFormat responseFormat =
+ e.getResponseFormat() != null ? e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
+ componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
+ throw e;
+ } catch (StorageException e) {
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
+ componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
+ throw e;
+ }
+ }
+
+ private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo, List<ArtifactDefinition> createdArtifacts,
+ ArtifactOperationInfo artifactOperation, boolean shouldLock,
+ boolean inTransaction) {
+ if (csarInfo.getCsar() != null) {
+ String vendorLicenseModelId = null;
+ String vfLicenseModelId = null;
+ if (artifactOperation.isUpdate()) {
+ Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
+ if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
+ for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
+ if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
+ vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
+ }
+ if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
+ vfLicenseModelId = artifactEntry.getValue().getUniqueId();
+ }
+ }
+ }
+ }
+ // Specific Behavior for license artifacts
+ createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL,
+ Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
+ Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId,
+ artifactOperation, null, true, shouldLock, inTransaction);
+ createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
+ ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
+ Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, true, shouldLock,
+ inTransaction);
+ Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, createdArtifacts, shouldLock,
+ inTransaction, artifactOperation);
+ if (eitherCreateResult.isRight()) {
+ return Either.right(eitherCreateResult.right().value());
+ }
+ Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
+ .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
+ if (artifacsMetaCsarStatus.isLeft()) {
+ String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
+ String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
+ Either<Resource, ResponseFormat> createArtifactsFromCsar;
+ if (artifactOperation.isCreateOrLink()) {
+ createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic
+ .createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts);
+ } else {
+ Either<Component, ResponseFormat> result = csarArtifactsAndGroupsBusinessLogic
+ .updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock,
+ inTransaction);
+ if ((result.left().value() instanceof Resource) && result.isLeft()) {
+ Resource service1 = (Resource) result.left().value();
+ createArtifactsFromCsar = Either.left(service1);
+ } else {
+ createArtifactsFromCsar = Either.right(result.right().value());
+ }
+ }
+ if (createArtifactsFromCsar.isRight()) {
+ log.debug("Couldn't create artifacts from artifacts.meta");
+ return Either.right(createArtifactsFromCsar.right().value());
+ }
+ return Either.left(createArtifactsFromCsar.left().value());
+ } else {
+ return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock, inTransaction);
+ }
+ }
+ return Either.left(resource);
+ }
+
+ private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo, String artifactPath,
+ String artifactFileName, String artifactType,
+ ArtifactGroupTypeEnum artifactGroupType, String artifactLabel,
+ String artifactDisplayName, String artifactDescription,
+ String artifactId, ArtifactOperationInfo operation,
+ List<ArtifactDefinition> createdArtifacts, boolean isFromCsar,
+ boolean shouldLock, boolean inTransaction) {
+ byte[] artifactFileBytes = null;
+ if (csarInfo.getCsar().containsKey(artifactPath)) {
+ artifactFileBytes = csarInfo.getCsar().get(artifactPath);
+ }
+ Either<Boolean, ResponseFormat> result = Either.left(true);
+ if (operation.isUpdate() || operation.isDelete()) {
+ if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
+ Either<ArtifactDefinition, ResponseFormat> handleDelete = artifactsBusinessLogic
+ .handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), resource, shouldLock, inTransaction);
+ if (handleDelete.isRight()) {
+ result = Either.right(handleDelete.right().value());
+ } else {
+ ArtifactDefinition value = handleDelete.left().value();
+ String updatedArtifactId = value.getUniqueId();
+ if (artifactGroupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
+ resource.getDeploymentArtifacts().remove(updatedArtifactId);
+ } else {
+ resource.getArtifacts().remove(updatedArtifactId);
+ }
+ }
+ return result;
+ }
+ if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
+ operation = new ArtifactOperationInfo(false, false, ArtifactOperationEnum.CREATE);
+ }
+ }
+ if (artifactFileBytes != null) {
+ Map<String, Object> vendorLicenseModelJson = ArtifactUtils
+ .buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName,
+ artifactDescription, artifactFileBytes, null, isFromCsar);
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic
+ .createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), vendorLicenseModelJson, operation);
+ addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
+ if (eitherNonMetaArtifacts.isRight()) {
+ BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact",
+ "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(), ErrorSeverity.WARNING);
+ return Either.right(eitherNonMetaArtifacts.right().value());
+ }
+ ArtifactDefinition artifactDefinition = eitherNonMetaArtifacts.left().value().left().value();
+ createOrUpdateResourceWithUpdatedArtifact(artifactDefinition, resource, artifactGroupType);
+ }
+ return result;
+ }
+
+ private void createOrUpdateResourceWithUpdatedArtifact(ArtifactDefinition artifact, Resource resource, ArtifactGroupTypeEnum groupTypeEnum) {
+ if (groupTypeEnum == ArtifactGroupTypeEnum.DEPLOYMENT) {
+ resource.getDeploymentArtifacts().put(artifact.getArtifactLabel(), artifact);
+ } else {
+ resource.getArtifacts().put(artifact.getArtifactLabel(), artifact);
+ }
+ }
+
+ private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
+ return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
+ }
+
+ private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts,
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
+ if (operation.isCreateOrLink() && createdArtifacts != null && eitherNonMetaArtifacts.isLeft()) {
+ Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
+ if (eitherResult.isLeft()) {
+ createdArtifacts.add(eitherResult.left().value());
+ }
+ }
+ }
+
+ private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
+ List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
+ boolean inTransaction, ArtifactOperationInfo artifactOperation) {
+ Either<Resource, ResponseFormat> resStatus = null;
+ Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
+ try {
+ Either<List<NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages);
+ if (artifactPathAndNameList.isRight()) {
+ return Either.right(
+ getComponentsUtils().getResponseFormatByArtifactId(ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value()));
+ }
+ EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
+ if (artifactOperation.isCreateOrLink()) {
+ vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
+ vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value());
+ } else {
+ Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
+ resource, artifactPathAndNameList.left().value(), csarInfo.getModifier());
+ if (findVfCsarArtifactsToHandleRes.isRight()) {
+ resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
+ }
+ if (resStatus == null) {
+ vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
+ }
+ }
+ if (resStatus == null && vfCsarArtifactsToHandle != null) {
+ resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, resStatus, vfCsarArtifactsToHandle);
+ }
+ if (resStatus == null) {
+ resStatus = Either.left(resource);
+ }
+ } catch (Exception e) {
+ resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ log.debug("Exception occurred in createNonMetaArtifacts, message:{}", e.getMessage(), e);
+ } finally {
+ CsarUtils.handleWarningMessages(collectedWarningMessages);
+ }
+ return resStatus;
+ }
+
+ private Either<Resource, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Resource resource, List<ArtifactDefinition> createdArtifacts,
+ boolean shouldLock, boolean inTransaction,
+ Either<Resource, ResponseFormat> resStatus,
+ EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
+ for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle.entrySet()) {
+ Optional<ResponseFormat> optionalCreateInDBError =
+ // Stream of artifacts to be created
+ currArtifactOperationPair.getValue().stream()
+ // create each artifact
+ .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(), e.getArtifactName(), e.getArtifactType(),
+ e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), CsarUtils.ARTIFACT_CREATED_FROM_CSAR,
+ e.getArtifactUniqueId(), new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts,
+ e.isFromCsar(), shouldLock, inTransaction))
+ // filter in only error
+ .filter(Either::isRight).
+ // Convert the error from either to
+
+ // ResponseFormat
+ map(e -> e.right().value()).
+ // Check if an error occurred
+ findAny();
+ // Error found on artifact Creation
+ if (optionalCreateInDBError.isPresent()) {
+ resStatus = Either.right(optionalCreateInDBError.get());
+ break;
+ }
+ }
+ return resStatus;
+ }
+
+ private Either<List<NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo,
+ Map<String, Set<List<String>>> collectedWarningMessages) {
+ List<NonMetaArtifactInfo> artifactPathAndNameList =
+ // Stream of file paths contained in csar
+ csarInfo.getCsar().entrySet().stream()
+ // Filter in only VF artifact path location
+ .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
+ // Validate and add warnings
+ .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages))
+ // Filter in Non Warnings
+ .filter(Either::isLeft)
+ // Convert from Either to NonMetaArtifactInfo
+ .map(e -> e.left().value())
+ // collect to List
+ .collect(toList());
+ Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
+ for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
+ if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
+ return Either.right(nonMetaArtifactInfo.getArtifactName());
+ }
+ }
+ return Either.left(artifactPathAndNameList);
+ }
+
+ private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(Resource resource,
+ List<NonMetaArtifactInfo> artifactPathAndNameList,
+ User user) {
+ List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
+ // collect all Deployment and Informational artifacts of VF
+ if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) {
+ existingArtifacts.addAll(resource.getDeploymentArtifacts().values());
+ }
+ if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) {
+ existingArtifacts.addAll(resource.getArtifacts().values());
+ }
+ existingArtifacts = existingArtifacts.stream()
+ // filter MANDATORY artifacts, LICENSE artifacts and artifacts
+
+ // was created from HEAT.meta
+ .filter(this::isNonMetaArtifact).collect(toList());
+ List<String> artifactsToIgnore = new ArrayList<>();
+ // collect IDs of Artifacts of VF which belongs to any group
+ if (resource.getGroups() != null) {
+ resource.getGroups().stream().forEach(g -> {
+ if (g.getArtifacts() != null && !g.getArtifacts().isEmpty()) {
+ artifactsToIgnore.addAll(g.getArtifacts());
+ }
+ });
+ }
+ existingArtifacts = existingArtifacts.stream()
+ // filter artifacts which belongs to any group
+ .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList());
+ return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
+ }
+
+ private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
+ boolean result = true;
+ if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
+ result = false;
+ }
+ return result;
+ }
+
+ private boolean isValidArtifactType(ArtifactDefinition artifact) {
+ boolean result = true;
+ if (artifact.getArtifactType() == null || ArtifactTypeEnum.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE
+ || ArtifactTypeEnum.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
+ result = false;
+ }
+ return result;
+ }
+
+ private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource, Resource oldResource,
+ Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
+ Map<String, Resource> existingNodeTypesByResourceNames) {
+ log.debug("#createResourceInstancesRelations - Going to create relations ");
+ loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
+ "Start to create relations");
+ List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
+ if (isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList) &&
+ resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances {
+ log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
+ resource.getUniqueId(), yamlName);
+ loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "No instances found in the resource: {}, is empty, yaml template file name: {}", resource.getName(), yamlName);
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError("createResourceInstancesRelations", "No instances found in a resource or nn yaml template. ",
+ ErrorSeverity.ERROR);
+ throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ }
+ Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
+ Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
+ Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
+ Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
+ Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
- List<RequirementCapabilityRelDef> relations = new ArrayList<>();
- Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
-
- log.debug("#createResourceInstancesRelations - Before get all datatypes. ");
- Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- JanusGraphOperationStatus status = allDataTypes.right()
- .value();
- BeEcompErrorManager.getInstance()
- .logInternalFlowError("UpdatePropertyValueOnComponentInstance",
- "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
- StatusCode.ERROR,"ERROR while update property value on instance. Status is: "+status);
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
- DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName);
-
- }
- Resource finalResource = resource;
- uploadResInstancesMap.values()
- .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
- instProperties, instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts,
- instAttributes, existingNodeTypesByResourceNames, instInputs, i));
- resource.getComponentInstances()
- .stream()
- .filter(i -> !i.isCreatedFromCsar())
- .forEach(i -> processUiComponentInstance(oldResource, i, instCapabilities, instRequirements,
- instDeploymentArtifacts, instArtifacts, instProperties, instInputs, instAttributes));
-
- associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
- associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
- associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
- associateArtifactsToInstances(yamlName, resource, instArtifacts);
- associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
- associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
- addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
- associateResourceInstances(yamlName, resource, relations);
- handleSubstitutionMappings(resource, uploadResInstancesMap);
- log.debug("************* in create relations, getResource start");
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,"create relations");
- Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
- .getToscaFullElement(resource.getUniqueId());
- log.debug("************* in create relations, getResource end");
- if (eitherGetResource.isRight()) {
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
- StatusCode.ERROR,"ERROR while create relations");
- throw new ByResponseFormatComponentException(componentsUtils
- .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right()
- .value()), resource));
- }
- return eitherGetResource.left()
- .value();
- }
-
- private void processUiComponentInstance(Resource oldResource, ComponentInstance instance,
- Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
- Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
- Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
- Map<String, Map<String, ArtifactDefinition>> instArtifacts, Map<String,
- List<ComponentInstanceProperty>> instProperties, Map<String,
- List<ComponentInstanceInput>> instInputs,
- Map<String, List<AttributeDefinition>> instAttributes) {
- Optional<ComponentInstance> foundInstance = findInstance(oldResource, instance);
- if (foundInstance.isPresent()) {
- if (MapUtils.isNotEmpty(foundInstance.get().getCapabilities())) {
- instCapabilities.put(instance, foundInstance.get().getCapabilities());
- }
- if (MapUtils.isNotEmpty(foundInstance.get().getRequirements())) {
- instRequirements.put(instance, foundInstance.get().getRequirements());
- }
- if (MapUtils.isNotEmpty(foundInstance.get().getDeploymentArtifacts())) {
- instDeploymentArtifacts.put(instance.getUniqueId(), foundInstance.get().getDeploymentArtifacts());
- }
- if(MapUtils.isNotEmpty(foundInstance.get().getArtifacts())){
- instArtifacts.put(instance.getUniqueId(), foundInstance.get().getArtifacts());
- }
- if (MapUtils.isNotEmpty(oldResource.getComponentInstancesProperties()) &&
- CollectionUtils
- .isNotEmpty(oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()))) {
- instProperties.put(instance.getUniqueId(),
- oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()));
- }
- if (MapUtils.isNotEmpty(oldResource.getComponentInstancesInputs()) &&
- CollectionUtils
- .isNotEmpty(oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()))) {
- instInputs.put(instance.getUniqueId(),
- oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()));
- }
- if(MapUtils.isNotEmpty(oldResource.getComponentInstancesAttributes()) &&
- CollectionUtils.isNotEmpty(oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()))){
- instAttributes.put(instance.getUniqueId(), oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()).stream().map(AttributeDefinition::new).collect(toList()));
- }
- }
- }
-
- private Optional<ComponentInstance> findInstance(Resource oldResource, ComponentInstance instance) {
- if(oldResource != null && CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) {
- return oldResource.getComponentInstances().stream().filter(i -> i.getName().equals(instance.getName())).findFirst();
- }
- return Optional.empty();
- }
-
- private void associateResourceInstances(String yamlName, Resource resource,
- List<RequirementCapabilityRelDef> relations) {
- Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade.associateResourceInstances(resource, resource.getUniqueId(), relations);
-
- if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
- StorageOperationStatus status = relationsEither.right().value();
- log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
- status);
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), yamlName);
- } else {
- setResourceInstanceRelationsOnComponent(resource, relationsEither.left().value());
- }
- }
-
- private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource,
- Map<String, List<AttributeDefinition>> instAttributes) {
- StorageOperationStatus addArtToInst;
- addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
- resource);
- if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
- log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
- addArtToInst);
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst),
- yamlName);
- }
- }
-
- private void associateOrAddCalculatedCapReq(String yamlName, Resource resource,
- Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
- Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
- StorageOperationStatus addArtToInst;
- addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
- resource);
- if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
- log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
- addArtToInst);
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
- }
- }
-
- private void associateArtifactsToInstances(String yamlName, Resource resource,
- Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
- StorageOperationStatus addArtToInst;
-
- addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
- if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
- log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
- }
- }
-
- private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource,
- Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
- StorageOperationStatus addArtToInst = toscaOperationFacade
- .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
- if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
- log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
- }
- }
-
- private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource,
- Map<String, List<ComponentInstanceInput>> instInputs) {
- if (MapUtils.isNotEmpty(instInputs)) {
- Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
- .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
- if (addInputToInst.isRight()) {
-
- StorageOperationStatus addInputToInstError = addInputToInst.right().value();
- log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
- addInputToInstError);
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addInputToInstError), yamlName);
- }
- setComponentInstanceInputsOnComponent(resource, instInputs);
- }
- }
-
- private void setComponentInstanceInputsOnComponent(Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) {
- Map<String, List<ComponentInstanceInput>> componentInstancesInputs = resource.getComponentInstancesInputs();
- if (componentInstancesInputs == null)
- componentInstancesInputs = new HashMap<>();
- componentInstancesInputs.putAll(instInputs);
- resource.setComponentInstancesInputs(componentInstancesInputs);
- }
-
- private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource,
- Map<String, List<ComponentInstanceProperty>> instProperties) {
- Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
- .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
- if (addPropToInst.isRight()) {
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
- StatusCode.ERROR,"ERROR while associate compnent insatnce properties of resource: {} status is: {}",resource.getName(),addPropToInst.right().value());
- StorageOperationStatus storageOperationStatus = addPropToInst.right().value();
- log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
- storageOperationStatus);
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), yamlName);
- }
- setComponentInstancePropertiesOnComponent(resource, instProperties);
- }
-
- private void setComponentInstancePropertiesOnComponent(Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) {
- Map<String, List<ComponentInstanceProperty>> componentInstanceProps = resource.getComponentInstancesProperties();
- if (componentInstanceProps == null )
- componentInstanceProps = new HashMap<>();
- componentInstanceProps.putAll(instProperties);
- resource.setComponentInstancesProperties(componentInstanceProps);
- }
-
- private void handleSubstitutionMappings(Resource resource,
- Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
- if (resource.getResourceType() == ResourceTypeEnum.CVFC) {
- Either<Resource, StorageOperationStatus> getResourceRes =
- updateCalculatedCapReqWithSubstitutionMappings(resource, uploadResInstancesMap);
- if (getResourceRes.isRight()) {
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right()
- .value()), resource);
- throw new ByResponseFormatComponentException(responseFormat);
- }
- }
- }
-
- private void addRelationsToRI(String yamlName, Resource resource,
- Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
- List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
- for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
- UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
- ComponentInstance currentCompInstance = null;
- for (ComponentInstance compInstance : componentInstancesList) {
-
- if (compInstance.getName()
- .equals(uploadComponentInstanceInfo.getName())) {
- currentCompInstance = compInstance;
- break;
- }
-
- }
- if (currentCompInstance == null) {
- log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
- resource.getUniqueId());
- BeEcompErrorManager.getInstance()
- .logInternalDataError(
- COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
- resource.getUniqueId(), ErrorSeverity.ERROR);
- throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
- }
-
- ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
- if (addRelationToRiRes.getStatus() != 200) {
- throw new ByResponseFormatComponentException(addRelationToRiRes);
- }
- }
-
- }
-
- private void setResourceInstanceRelationsOnComponent(Resource resource, List<RequirementCapabilityRelDef> relations) {
- if (resource.getComponentInstancesRelations() != null) {
- resource.getComponentInstancesRelations().addAll(relations);
- } else {
- resource.setComponentInstancesRelations(relations);
- }
- }
-
- private void processComponentInstance(String yamlName, Resource resource,
- List<ComponentInstance> componentInstancesList,
- Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
- Map<String, List<ComponentInstanceProperty>> instProperties,
- Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
- Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
- Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
- Map<String, Map<String, ArtifactDefinition>> instArtifacts,
- Map<String, List<AttributeDefinition>> instAttributes,
- Map<String, Resource> originCompMap,
- Map<String, List<ComponentInstanceInput>> instInputs,
- UploadComponentInstanceInfo uploadComponentInstanceInfo) {
- Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
- .filter(i -> i.getName()
- .equals(uploadComponentInstanceInfo.getName()))
- .findFirst();
- if (!currentCompInstanceOpt.isPresent()) {
- log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
- resource.getUniqueId());
- BeEcompErrorManager.getInstance()
- .logInternalDataError(
- COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
- resource.getUniqueId(), ErrorSeverity.ERROR);
- throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
- }
- ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
- String resourceInstanceId = currentCompInstance.getUniqueId();
- Resource originResource = getOriginResource(originCompMap, currentCompInstance);
- if (isNotEmpty(originResource.getRequirements())) {
- instRequirements.put(currentCompInstance, originResource.getRequirements());
- }
- if (isNotEmpty(originResource.getCapabilities())) {
- processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo,
- currentCompInstance, originResource);
- }
- if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts()
- .isEmpty()) {
- instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
- }
- if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) {
- instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
- }
- if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) {
- instAttributes.put(resourceInstanceId, originResource.getAttributes());
- }
- if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
- ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource,
- originResource, currentCompInstance, instProperties, allDataTypes.left()
- .value());
- if (addPropertiesValueToRiRes.getStatus() != 200) {
- throw new ByResponseFormatComponentException(addPropertiesValueToRiRes);
- }
- } else {
- addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, instInputs,
- allDataTypes.left()
- .value());
- }
- }
-
- private Resource getOriginResource(Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
- Resource originResource;
- if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
- Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
- .getToscaFullElement(currentCompInstance.getComponentUid());
- if (getOriginResourceRes.isRight()) {
- log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}",
- currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(),
- getOriginResourceRes);
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right()
- .value()), currentCompInstance.getComponentUid());
- }
- originResource = getOriginResourceRes.left()
- .value();
- originCompMap.put(originResource.getUniqueId(), originResource);
- } else {
- originResource = originCompMap.get(currentCompInstance.getComponentUid());
- }
- return originResource;
- }
-
- private void processComponentInstanceCapabilities(
- Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
- Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
- UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
- Resource originResource) {
- Map<String, List<CapabilityDefinition>> originCapabilities;
- if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
- originCapabilities = new HashMap<>();
- Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
- originResource.getCapabilities()
- .forEach((k, v) -> addCapabilities(originCapabilities, k, v));
- uploadComponentInstanceInfo.getCapabilities()
- .values()
- .forEach(l -> addCapabilitiesProperties(newPropertiesMap, l));
- updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
- } else {
- originCapabilities = originResource.getCapabilities();
- }
- instCapabilties.put(currentCompInstance, originCapabilities);
- }
-
- private void updateCapabilityPropertiesValues(
- Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
- Map<String, List<CapabilityDefinition>> originCapabilities,
- Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
- originCapabilities.values()
- .stream()
- .flatMap(Collection::stream)
- .filter(c -> newPropertiesMap.containsKey(c.getName()))
- .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()),
- allDataTypes.left()
- .value()));
- }
-
- private void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap,
- List<UploadCapInfo> capabilities) {
- for (UploadCapInfo capability : capabilities) {
- if (isNotEmpty(capability.getProperties())) {
- newPropertiesMap.put(capability.getName(), capability.getProperties()
- .stream()
- .collect(toMap(UploadInfo::getName, p -> p)));
- }
- }
- }
-
- private void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type,
- List<CapabilityDefinition> capabilities) {
- List<CapabilityDefinition> list = capabilities.stream()
- .map(CapabilityDefinition::new)
- .collect(toList());
- originCapabilities.put(type, list);
- }
-
- private void updatePropertyValues(List<ComponentInstanceProperty> properties,
- Map<String, UploadPropInfo> newProperties, Map<String, DataTypeDefinition> allDataTypes) {
- properties.forEach(p -> updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
- }
-
- private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
- Map<String, DataTypeDefinition> allDataTypes) {
- String value = null;
- List<GetInputValueDataDefinition> getInputs = null;
- boolean isValidate = true;
- if (null != propertyInfo && propertyInfo.getValue() != null) {
- getInputs = propertyInfo.getGet_input();
- isValidate = getInputs == null || getInputs.isEmpty();
- if (isValidate) {
- value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
- } else {
- value = getPropertyJsonStringValue(propertyInfo.getValue(),
- TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
- }
- }
- property.setValue(value);
+ List<RequirementCapabilityRelDef> relations = new ArrayList<>();
+ Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
+ log.debug("#createResourceInstancesRelations - Before get all datatypes. ");
+ Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
+ if (allDataTypes.isRight()) {
+ JanusGraphOperationStatus status = allDataTypes.right().value();
+ BeEcompErrorManager.getInstance()
+ .logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status,
+ ErrorSeverity.ERROR);
+ loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "ERROR while update property value on instance. Status is: " + status);
+ throw new ByActionStatusComponentException(
+ componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName);
+ }
+ Resource finalResource = resource;
+ uploadResInstancesMap.values().forEach(
+ i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes, instProperties, instCapabilities,
+ instRequirements, instDeploymentArtifacts, instArtifacts, instAttributes, existingNodeTypesByResourceNames, instInputs, i));
+ resource.getComponentInstances().stream().filter(i -> !i.isCreatedFromCsar()).forEach(
+ i -> processUiComponentInstance(oldResource, i, instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts,
+ instProperties, instInputs, instAttributes));
+ associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
+ associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
+ associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
+ associateArtifactsToInstances(yamlName, resource, instArtifacts);
+ associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
+ associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
+ addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
+ associateResourceInstances(yamlName, resource, relations);
+ handleSubstitutionMappings(resource, uploadResInstancesMap);
+ log.debug("************* in create relations, getResource start");
+ loggerSupportability
+ .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE, "create relations");
+ Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaFullElement(resource.getUniqueId());
+ log.debug("************* in create relations, getResource end");
+ if (eitherGetResource.isRight()) {
+ loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "ERROR while create relations");
+ throw new ByResponseFormatComponentException(
+ componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource));
+ }
+ return eitherGetResource.left().value();
+ }
+
+ private void processUiComponentInstance(Resource oldResource, ComponentInstance instance,
+ Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
+ Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
+ Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
+ Map<String, Map<String, ArtifactDefinition>> instArtifacts,
+ Map<String, List<ComponentInstanceProperty>> instProperties,
+ Map<String, List<ComponentInstanceInput>> instInputs,
+ Map<String, List<AttributeDefinition>> instAttributes) {
+ Optional<ComponentInstance> foundInstance = findInstance(oldResource, instance);
+ if (foundInstance.isPresent()) {
+ if (MapUtils.isNotEmpty(foundInstance.get().getCapabilities())) {
+ instCapabilities.put(instance, foundInstance.get().getCapabilities());
+ }
+ if (MapUtils.isNotEmpty(foundInstance.get().getRequirements())) {
+ instRequirements.put(instance, foundInstance.get().getRequirements());
+ }
+ if (MapUtils.isNotEmpty(foundInstance.get().getDeploymentArtifacts())) {
+ instDeploymentArtifacts.put(instance.getUniqueId(), foundInstance.get().getDeploymentArtifacts());
+ }
+ if (MapUtils.isNotEmpty(foundInstance.get().getArtifacts())) {
+ instArtifacts.put(instance.getUniqueId(), foundInstance.get().getArtifacts());
+ }
+ if (MapUtils.isNotEmpty(oldResource.getComponentInstancesProperties()) && CollectionUtils
+ .isNotEmpty(oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()))) {
+ instProperties.put(instance.getUniqueId(), oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()));
+ }
+ if (MapUtils.isNotEmpty(oldResource.getComponentInstancesInputs()) && CollectionUtils
+ .isNotEmpty(oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()))) {
+ instInputs.put(instance.getUniqueId(), oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()));
+ }
+ if (MapUtils.isNotEmpty(oldResource.getComponentInstancesAttributes()) && CollectionUtils
+ .isNotEmpty(oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()))) {
+ instAttributes.put(instance.getUniqueId(),
+ oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()).stream().map(AttributeDefinition::new)
+ .collect(toList()));
+ }
+ }
+ }
+
+ private Optional<ComponentInstance> findInstance(Resource oldResource, ComponentInstance instance) {
+ if (oldResource != null && CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) {
+ return oldResource.getComponentInstances().stream().filter(i -> i.getName().equals(instance.getName())).findFirst();
+ }
+ return Optional.empty();
+ }
+
+ private void associateResourceInstances(String yamlName, Resource resource, List<RequirementCapabilityRelDef> relations) {
+ Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade
+ .associateResourceInstances(resource, resource.getUniqueId(), relations);
+ if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
+ StorageOperationStatus status = relationsEither.right().value();
+ log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), status);
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), yamlName);
+ } else {
+ setResourceInstanceRelationsOnComponent(resource, relationsEither.left().value());
+ }
+ }
+
+ private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource,
+ Map<String, List<AttributeDefinition>> instAttributes) {
+ StorageOperationStatus addArtToInst;
+ addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource);
+ if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
+ log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
+ }
+ }
+
+ private void associateOrAddCalculatedCapReq(String yamlName, Resource resource,
+ Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
+ Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
+ StorageOperationStatus addArtToInst;
+ addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, resource);
+ if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
+ log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
+ }
+ }
+
+ private void associateArtifactsToInstances(String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
+ StorageOperationStatus addArtToInst;
+ addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
+ if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
+ log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
+ }
+ }
+
+ private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource,
+ Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
+ StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
+ if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
+ log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
+ }
+ }
+
+ private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource,
+ Map<String, List<ComponentInstanceInput>> instInputs) {
+ if (MapUtils.isNotEmpty(instInputs)) {
+ Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
+ .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
+ if (addInputToInst.isRight()) {
+ StorageOperationStatus addInputToInstError = addInputToInst.right().value();
+ log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), addInputToInstError);
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addInputToInstError), yamlName);
+ }
+ setComponentInstanceInputsOnComponent(resource, instInputs);
+ }
+ }
+
+ private void setComponentInstanceInputsOnComponent(Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) {
+ Map<String, List<ComponentInstanceInput>> componentInstancesInputs = resource.getComponentInstancesInputs();
+ if (componentInstancesInputs == null) {
+ componentInstancesInputs = new HashMap<>();
+ }
+ componentInstancesInputs.putAll(instInputs);
+ resource.setComponentInstancesInputs(componentInstancesInputs);
+ }
+
+ private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource,
+ Map<String, List<ComponentInstanceProperty>> instProperties) {
+ Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
+ .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
+ if (addPropToInst.isRight()) {
+ loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "ERROR while associate compnent insatnce properties of resource: {} status is: {}", resource.getName(),
+ addPropToInst.right().value());
+ StorageOperationStatus storageOperationStatus = addPropToInst.right().value();
+ log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), storageOperationStatus);
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), yamlName);
+ }
+ setComponentInstancePropertiesOnComponent(resource, instProperties);
+ }
+
+ private void setComponentInstancePropertiesOnComponent(Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) {
+ Map<String, List<ComponentInstanceProperty>> componentInstanceProps = resource.getComponentInstancesProperties();
+ if (componentInstanceProps == null) {
+ componentInstanceProps = new HashMap<>();
+ }
+ componentInstanceProps.putAll(instProperties);
+ resource.setComponentInstancesProperties(componentInstanceProps);
+ }
+
+ private void handleSubstitutionMappings(Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
+ if (resource.getResourceType() == ResourceTypeEnum.CVFC) {
+ Either<Resource, StorageOperationStatus> getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(resource, uploadResInstancesMap);
+ if (getResourceRes.isRight()) {
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
+ throw new ByResponseFormatComponentException(responseFormat);
+ }
+ }
+ }
+
+ private void addRelationsToRI(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
+ List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
+ for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
+ UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
+ ComponentInstance currentCompInstance = null;
+ for (ComponentInstance compInstance : componentInstancesList) {
+ if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
+ currentCompInstance = compInstance;
+ break;
+ }
+ }
+ if (currentCompInstance == null) {
+ log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), resource.getUniqueId());
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, resource.getUniqueId(),
+ ErrorSeverity.ERROR);
+ throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ }
+ ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
+ if (addRelationToRiRes.getStatus() != 200) {
+ throw new ByResponseFormatComponentException(addRelationToRiRes);
+ }
+ }
+ }
+
+ private void setResourceInstanceRelationsOnComponent(Resource resource, List<RequirementCapabilityRelDef> relations) {
+ if (resource.getComponentInstancesRelations() != null) {
+ resource.getComponentInstancesRelations().addAll(relations);
+ } else {
+ resource.setComponentInstancesRelations(relations);
+ }
+ }
+
+ private void processComponentInstance(String yamlName, Resource resource, List<ComponentInstance> componentInstancesList,
+ Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
+ Map<String, List<ComponentInstanceProperty>> instProperties,
+ Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
+ Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
+ Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
+ Map<String, Map<String, ArtifactDefinition>> instArtifacts,
+ Map<String, List<AttributeDefinition>> instAttributes, Map<String, Resource> originCompMap,
+ Map<String, List<ComponentInstanceInput>> instInputs,
+ UploadComponentInstanceInfo uploadComponentInstanceInfo) {
+ Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
+ .filter(i -> i.getName().equals(uploadComponentInstanceInfo.getName())).findFirst();
+ if (!currentCompInstanceOpt.isPresent()) {
+ log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), resource.getUniqueId());
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, resource.getUniqueId(),
+ ErrorSeverity.ERROR);
+ throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ }
+ ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
+ String resourceInstanceId = currentCompInstance.getUniqueId();
+ Resource originResource = getOriginResource(originCompMap, currentCompInstance);
+ if (isNotEmpty(originResource.getRequirements())) {
+ instRequirements.put(currentCompInstance, originResource.getRequirements());
+ }
+ if (isNotEmpty(originResource.getCapabilities())) {
+ processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo, currentCompInstance, originResource);
+ }
+ if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) {
+ instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
+ }
+ if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) {
+ instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
+ }
+ if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) {
+ instAttributes.put(resourceInstanceId, originResource.getAttributes());
+ }
+ if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
+ ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, originResource,
+ currentCompInstance, instProperties, allDataTypes.left().value());
+ if (addPropertiesValueToRiRes.getStatus() != 200) {
+ throw new ByResponseFormatComponentException(addPropertiesValueToRiRes);
+ }
+ } else {
+ addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, instInputs, allDataTypes.left().value());
+ }
+ }
+
+ private Resource getOriginResource(Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
+ Resource originResource;
+ if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
+ Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
+ .getToscaFullElement(currentCompInstance.getComponentUid());
+ if (getOriginResourceRes.isRight()) {
+ log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}", currentCompInstance.getComponentUid(),
+ currentCompInstance.getToscaComponentName(), getOriginResourceRes);
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()),
+ currentCompInstance.getComponentUid());
+ }
+ originResource = getOriginResourceRes.left().value();
+ originCompMap.put(originResource.getUniqueId(), originResource);
+ } else {
+ originResource = originCompMap.get(currentCompInstance.getComponentUid());
+ }
+ return originResource;
+ }
+
+ private void processComponentInstanceCapabilities(Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
+ Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
+ UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
+ Resource originResource) {
+ Map<String, List<CapabilityDefinition>> originCapabilities;
+ if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
+ originCapabilities = new HashMap<>();
+ Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
+ originResource.getCapabilities().forEach((k, v) -> addCapabilities(originCapabilities, k, v));
+ uploadComponentInstanceInfo.getCapabilities().values().forEach(l -> addCapabilitiesProperties(newPropertiesMap, l));
+ updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
+ } else {
+ originCapabilities = originResource.getCapabilities();
+ }
+ instCapabilties.put(currentCompInstance, originCapabilities);
+ }
+
+ private void updateCapabilityPropertiesValues(Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
+ Map<String, List<CapabilityDefinition>> originCapabilities,
+ Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
+ originCapabilities.values().stream().flatMap(Collection::stream).filter(c -> newPropertiesMap.containsKey(c.getName()))
+ .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes.left().value()));
+ }
+
+ private void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap, List<UploadCapInfo> capabilities) {
+ for (UploadCapInfo capability : capabilities) {
+ if (isNotEmpty(capability.getProperties())) {
+ newPropertiesMap.put(capability.getName(), capability.getProperties().stream().collect(toMap(UploadInfo::getName, p -> p)));
+ }
+ }
+ }
+
+ private void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type, List<CapabilityDefinition> capabilities) {
+ List<CapabilityDefinition> list = capabilities.stream().map(CapabilityDefinition::new).collect(toList());
+ originCapabilities.put(type, list);
+ }
+
+ private void updatePropertyValues(List<ComponentInstanceProperty> properties, Map<String, UploadPropInfo> newProperties,
+ Map<String, DataTypeDefinition> allDataTypes) {
+ properties.forEach(p -> updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
+ }
+
+ private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
+ Map<String, DataTypeDefinition> allDataTypes) {
+ String value = null;
+ List<GetInputValueDataDefinition> getInputs = null;
+ boolean isValidate = true;
+ if (null != propertyInfo && propertyInfo.getValue() != null) {
+ getInputs = propertyInfo.getGet_input();
+ isValidate = getInputs == null || getInputs.isEmpty();
+ if (isValidate) {
+ value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
+ } else {
+ value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
+ }
+ }
+ property.setValue(value);
return validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
- }
-
- private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
- Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
- Either<Resource, StorageOperationStatus> updateRes = null;
- Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
- Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
- StorageOperationStatus status = toscaOperationFacade
- .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
- if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
- log.debug(
- "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
- resource.getUniqueId(), status);
- updateRes = Either.right(status);
- }
- if (updateRes == null) {
- fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap,
- updatedInstCapabilities, updatedInstRequirements);
- status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities,
- updatedInstRequirements, resource);
- if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
- log.debug(
- "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}",
- resource.getUniqueId(), status);
- updateRes = Either.right(status);
- }
- }
- if (updateRes == null) {
- updateRes = Either.left(resource);
- }
- return updateRes;
- }
-
- private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
- Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
- Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
- Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
-
- componentInstances.stream()
- .forEach(i -> {
- fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName())
- .getCapabilitiesNamesToUpdate());
- fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName())
- .getRequirementsNamesToUpdate());
- });
- }
-
- private void fillUpdatedInstRequirements(
- Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
- ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
- Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
- Set<String> updatedReqNames = new HashSet<>();
- if (isNotEmpty(requirementsNamesToUpdate)) {
- for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements()
- .entrySet()) {
- updatedRequirements.put(requirements.getKey(), requirements.getValue()
- .stream()
- .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
- && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
- .map(r -> {
- r.setParentName(r.getName());
- r.setName(requirementsNamesToUpdate.get(r.getName()));
- updatedReqNames.add(r.getName());
- return r;
- })
- .collect(toList()));
- }
- }
- if (isNotEmpty(updatedRequirements)) {
- updatedInstRequirements.put(instance, updatedRequirements);
- }
- }
-
- private void fillUpdatedInstCapabilities(
- Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
- ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
- Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
- Set<String> updatedCapNames = new HashSet<>();
- if (isNotEmpty(capabilitiesNamesToUpdate)) {
- for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities()
- .entrySet()) {
- updatedCapabilities.put(requirements.getKey(), requirements.getValue()
- .stream()
- .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
- && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
- .map(c -> {
- c.setParentName(c.getName());
- c.setName(capabilitiesNamesToUpdate.get(c.getName()));
- updatedCapNames.add(c.getName());
- return c;
- })
- .collect(toList()));
- }
- }
- if (isNotEmpty(updatedCapabilities)) {
- updatedInstCapabilties.put(instance, updatedCapabilities);
- }
- }
-
- private ResponseFormat addRelationToRI(String yamlName, Resource resource,
- UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
- List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
-
- ComponentInstance currentCompInstance = null;
-
- for (ComponentInstance compInstance : componentInstancesList) {
-
- if (compInstance.getName()
- .equals(nodesInfoValue.getName())) {
- currentCompInstance = compInstance;
- break;
- }
-
- }
-
- if (currentCompInstance == null) {
- log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId());
- BeEcompErrorManager.getInstance()
- .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
- resource.getUniqueId(), ErrorSeverity.ERROR);
- return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
- }
- String resourceInstanceId = currentCompInstance.getUniqueId();
-
- Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
-
- if (regMap != null) {
- Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet()
- .iterator();
-
- while (nodesRegValue.hasNext()) {
- Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
-
- List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
- for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
- log.debug("Going to create relation {}", uploadRegInfo.getName());
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Started to create relations on instance: {}",uploadRegInfo.getName());
- String regName = uploadRegInfo.getName();
- RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
- regCapRelDef.setFromNode(resourceInstanceId);
- log.debug("try to find available requirement {} ", regName);
- Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
- yamlName, nodesInfoValue, currentCompInstance, uploadRegInfo.getCapabilityName());
- if (eitherReqStatus.isRight()) {
- log.debug("failed to find available requirement {} status is {}", regName,
- eitherReqStatus.right()
- .value());
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR while search available requirement {} status is: {}",regName,eitherReqStatus.right().value());
- return eitherReqStatus.right()
- .value();
- }
-
- RequirementDefinition validReq = eitherReqStatus.left()
- .value();
- List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
- .getRelationships();
- if (reqAndRelationshipPairList == null) {
- reqAndRelationshipPairList = new ArrayList<>();
- }
- RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
- reqAndRelationshipPair.setRequirement(regName);
- reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
- reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
- RelationshipImpl relationship = new RelationshipImpl();
- relationship.setType(validReq.getCapability());
- reqAndRelationshipPair.setRelationships(relationship);
-
- ComponentInstance currentCapCompInstance = null;
- for (ComponentInstance compInstance : componentInstancesList) {
- if (compInstance.getName()
- .equals(uploadRegInfo.getNode())) {
- currentCapCompInstance = compInstance;
- break;
- }
- }
-
- if (currentCapCompInstance == null) {
- log.debug("The component instance with name {} not found on resource {} ",
- uploadRegInfo.getNode(), resource.getUniqueId());
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR component instance with name: {} not found on resource: {}",uploadRegInfo.getNode(),resource.getUniqueId());
- BeEcompErrorManager.getInstance()
- .logInternalDataError(
- COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
- resource.getUniqueId(), ErrorSeverity.ERROR);
- return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
- }
- regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
- log.debug("try to find aviable Capability req name is {} ", validReq.getName());
- CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
- currentCapCompInstance, uploadRegInfo);
-
- if (aviableCapForRel == null) {
- log.debug("aviable capability was not found. req name is {} component instance is {}",
- validReq.getName(), currentCapCompInstance.getUniqueId());
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR available capability was not found. req name is: {} component instance is: {}",validReq.getName(),currentCapCompInstance.getUniqueId());
- BeEcompErrorManager.getInstance()
- .logInternalDataError(
- "aviable capability was not found. req name is " + validReq.getName()
- + " component instance is " + currentCapCompInstance.getUniqueId(),
- resource.getUniqueId(), ErrorSeverity.ERROR);
- return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
- }
- reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
- reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
- reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
-
- CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
- capReqRel.setRelation(reqAndRelationshipPair);
- reqAndRelationshipPairList.add(capReqRel);
- regCapRelDef.setRelationships(reqAndRelationshipPairList);
- relations.add(regCapRelDef);
- }
- }
- } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
- return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
- }
- return componentsUtils.getResponseFormat(ActionStatus.OK);
- }
-
- private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource,
- Resource originResource, ComponentInstance currentCompInstance,
- Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
- Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
- if (MapUtils.isNotEmpty(propMap)) {
- Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
- List<ComponentInstanceInput> instPropList = new ArrayList<>();
-
- if (CollectionUtils.isEmpty(originResource.getInputs())) {
- log.debug("failed to find properties ");
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(),StatusCode.ERROR,"ERROR while try to find properties");
- throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND);
- }
- originResource.getInputs()
- .forEach(p -> addInput(currPropertiesMap, p));
- for (List<UploadPropInfo> propertyList : propMap.values()) {
- processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList,
- propertyList);
- }
- currPropertiesMap.values()
- .forEach(p -> instPropList.add(new ComponentInstanceInput(p)));
- instInputs.put(currentCompInstance.getUniqueId(), instPropList);
- }
- }
-
- private void processProperty(Resource resource, ComponentInstance currentCompInstance,
- Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap,
- List<ComponentInstanceInput> instPropList, List<UploadPropInfo> propertyList) {
- UploadPropInfo propertyInfo = propertyList.get(0);
- String propName = propertyInfo.getName();
- if (!currPropertiesMap.containsKey(propName)) {
- loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
- StatusCode.ERROR,"ERROR failed to find property: {}",propName);
- log.debug("failed to find property {} ", propName);
- throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, propName);
- }
- InputDefinition curPropertyDef = currPropertiesMap.get(propName);
- ComponentInstanceInput property = null;
-
- String value = null;
- List<GetInputValueDataDefinition> getInputs = null;
- boolean isValidate = true;
- if (propertyInfo.getValue() != null) {
- getInputs = propertyInfo.getGet_input();
- isValidate = getInputs == null || getInputs.isEmpty();
- if (isValidate) {
- value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
- } else {
- value = getPropertyJsonStringValue(propertyInfo.getValue(),
- TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
- }
- }
- property = new ComponentInstanceInput(curPropertyDef, value, null);
+ }
+
+ private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
+ Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
+ Either<Resource, StorageOperationStatus> updateRes = null;
+ Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
+ Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
+ StorageOperationStatus status = toscaOperationFacade.deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
+ if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
+ log.debug("Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
+ resource.getUniqueId(), status);
+ updateRes = Either.right(status);
+ }
+ if (updateRes == null) {
+ fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap, updatedInstCapabilities,
+ updatedInstRequirements);
+ status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, resource);
+ if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
+ log.debug(
+ "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}",
+ resource.getUniqueId(), status);
+ updateRes = Either.right(status);
+ }
+ }
+ if (updateRes == null) {
+ updateRes = Either.left(resource);
+ }
+ return updateRes;
+ }
+
+ private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
+ Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
+ Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
+ Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
+ componentInstances.stream().forEach(i -> {
+ fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
+ fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
+ });
+ }
+
+ private void fillUpdatedInstRequirements(Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
+ ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
+ Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
+ Set<String> updatedReqNames = new HashSet<>();
+ if (isNotEmpty(requirementsNamesToUpdate)) {
+ for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
+ updatedRequirements.put(requirements.getKey(), requirements.getValue().stream().filter(
+ r -> requirementsNamesToUpdate.containsKey(r.getName()) && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
+ .map(r -> {
+ r.setParentName(r.getName());
+ r.setName(requirementsNamesToUpdate.get(r.getName()));
+ updatedReqNames.add(r.getName());
+ return r;
+ }).collect(toList()));
+ }
+ }
+ if (isNotEmpty(updatedRequirements)) {
+ updatedInstRequirements.put(instance, updatedRequirements);
+ }
+ }
+
+ private void fillUpdatedInstCapabilities(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
+ ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
+ Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
+ Set<String> updatedCapNames = new HashSet<>();
+ if (isNotEmpty(capabilitiesNamesToUpdate)) {
+ for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
+ updatedCapabilities.put(requirements.getKey(), requirements.getValue().stream().filter(
+ c -> capabilitiesNamesToUpdate.containsKey(c.getName()) && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
+ .map(c -> {
+ c.setParentName(c.getName());
+ c.setName(capabilitiesNamesToUpdate.get(c.getName()));
+ updatedCapNames.add(c.getName());
+ return c;
+ }).collect(toList()));
+ }
+ }
+ if (isNotEmpty(updatedCapabilities)) {
+ updatedInstCapabilties.put(instance, updatedCapabilities);
+ }
+ }
+
+ private ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue,
+ List<RequirementCapabilityRelDef> relations) {
+ List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
+ ComponentInstance currentCompInstance = null;
+ for (ComponentInstance compInstance : componentInstancesList) {
+ if (compInstance.getName().equals(nodesInfoValue.getName())) {
+ currentCompInstance = compInstance;
+ break;
+ }
+ }
+ if (currentCompInstance == null) {
+ log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId());
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, resource.getUniqueId(),
+ ErrorSeverity.ERROR);
+ return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ }
+ String resourceInstanceId = currentCompInstance.getUniqueId();
+ Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
+ if (regMap != null) {
+ Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
+ while (nodesRegValue.hasNext()) {
+ Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
+ List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
+ for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
+ log.debug("Going to create relation {}", uploadRegInfo.getName());
+ loggerSupportability
+ .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
+ "Started to create relations on instance: {}", uploadRegInfo.getName());
+ String regName = uploadRegInfo.getName();
+ RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
+ regCapRelDef.setFromNode(resourceInstanceId);
+ log.debug("try to find available requirement {} ", regName);
+ Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, yamlName, nodesInfoValue,
+ currentCompInstance, uploadRegInfo.getCapabilityName());
+ if (eitherReqStatus.isRight()) {
+ log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
+ loggerSupportability
+ .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "ERROR while search available requirement {} status is: {}", regName, eitherReqStatus.right().value());
+ return eitherReqStatus.right().value();
+ }
+ RequirementDefinition validReq = eitherReqStatus.left().value();
+ List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef.getRelationships();
+ if (reqAndRelationshipPairList == null) {
+ reqAndRelationshipPairList = new ArrayList<>();
+ }
+ RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
+ reqAndRelationshipPair.setRequirement(regName);
+ reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
+ reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
+ RelationshipImpl relationship = new RelationshipImpl();
+ relationship.setType(validReq.getCapability());
+ reqAndRelationshipPair.setRelationships(relationship);
+ ComponentInstance currentCapCompInstance = null;
+ for (ComponentInstance compInstance : componentInstancesList) {
+ if (compInstance.getName().equals(uploadRegInfo.getNode())) {
+ currentCapCompInstance = compInstance;
+ break;
+ }
+ }
+ if (currentCapCompInstance == null) {
+ log.debug("The component instance with name {} not found on resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
+ loggerSupportability
+ .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "ERROR component instance with name: {} not found on resource: {}", uploadRegInfo.getNode(), resource.getUniqueId());
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, resource.getUniqueId(),
+ ErrorSeverity.ERROR);
+ return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ }
+ regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
+ log.debug("try to find aviable Capability req name is {} ", validReq.getName());
+ CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
+ if (aviableCapForRel == null) {
+ log.debug("aviable capability was not found. req name is {} component instance is {}", validReq.getName(),
+ currentCapCompInstance.getUniqueId());
+ loggerSupportability
+ .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "ERROR available capability was not found. req name is: {} component instance is: {}", validReq.getName(),
+ currentCapCompInstance.getUniqueId());
+ BeEcompErrorManager.getInstance().logInternalDataError(
+ "aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance
+ .getUniqueId(), resource.getUniqueId(), ErrorSeverity.ERROR);
+ return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ }
+ reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
+ reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
+ reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
+ CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
+ capReqRel.setRelation(reqAndRelationshipPair);
+ reqAndRelationshipPairList.add(capReqRel);
+ regCapRelDef.setRelationships(reqAndRelationshipPairList);
+ relations.add(regCapRelDef);
+ }
+ }
+ } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
+ return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
+ }
+ return componentsUtils.getResponseFormat(ActionStatus.OK);
+ }
+
+ private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource,
+ ComponentInstance currentCompInstance, Map<String, List<ComponentInstanceInput>> instInputs,
+ Map<String, DataTypeDefinition> allDataTypes) {
+ Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
+ if (MapUtils.isNotEmpty(propMap)) {
+ Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
+ List<ComponentInstanceInput> instPropList = new ArrayList<>();
+ if (CollectionUtils.isEmpty(originResource.getInputs())) {
+ log.debug("failed to find properties ");
+ loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "ERROR while try to find properties");
+ throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND);
+ }
+ originResource.getInputs().forEach(p -> addInput(currPropertiesMap, p));
+ for (List<UploadPropInfo> propertyList : propMap.values()) {
+ processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList, propertyList);
+ }
+ currPropertiesMap.values().forEach(p -> instPropList.add(new ComponentInstanceInput(p)));
+ instInputs.put(currentCompInstance.getUniqueId(), instPropList);
+ }
+ }
+ private void processProperty(Resource resource, ComponentInstance currentCompInstance, Map<String, DataTypeDefinition> allDataTypes,
+ Map<String, InputDefinition> currPropertiesMap, List<ComponentInstanceInput> instPropList,
+ List<UploadPropInfo> propertyList) {
+ UploadPropInfo propertyInfo = propertyList.get(0);
+ String propName = propertyInfo.getName();
+ if (!currPropertiesMap.containsKey(propName)) {
+ loggerSupportability.log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "ERROR failed to find property: {}", propName);
+ log.debug("failed to find property {} ", propName);
+ throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, propName);
+ }
+ InputDefinition curPropertyDef = currPropertiesMap.get(propName);
+ ComponentInstanceInput property = null;
+ String value = null;
+ List<GetInputValueDataDefinition> getInputs = null;
+ boolean isValidate = true;
+ if (propertyInfo.getValue() != null) {
+ getInputs = propertyInfo.getGet_input();
+ isValidate = getInputs == null || getInputs.isEmpty();
+ if (isValidate) {
+ value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
+ } else {
+ value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
+ }
+ }
+ property = new ComponentInstanceInput(curPropertyDef, value, null);
String validPropertyVAlue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
+ property.setValue(validPropertyVAlue);
+ if (isNotEmpty(getInputs)) {
+ List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
+ for (GetInputValueDataDefinition getInput : getInputs) {
+ List<InputDefinition> inputs = resource.getInputs();
+ if (CollectionUtils.isEmpty(inputs)) {
+ loggerSupportability.log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "ERROR Failed to add property: " + propName + " to resource instance: {}. Inputs list is empty ",
+ currentCompInstance.getUniqueId());
+ log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property,
+ currentCompInstance.getUniqueId());
+ throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
+ }
+ Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
+ if (!optional.isPresent()) {
+ loggerSupportability.log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "ERROR Failed to find input: " + getInput.getInputName());
+ log.debug("Failed to find input {} ", getInput.getInputName());
+ // @@TODO error message
+ throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
+ }
+ InputDefinition input = optional.get();
+ getInput.setInputId(input.getUniqueId());
+ getInputValues.add(getInput);
+ GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
+ processGetInput(getInputValues, inputs, getInputIndex);
+ }
+ property.setGetInputValues(getInputValues);
+ }
+ instPropList.add(property);
+ // delete overriden property
+ currPropertiesMap.remove(property.getName());
+ }
+
+ private void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs,
+ GetInputValueDataDefinition getInputIndex) {
+ Optional<InputDefinition> optional;
+ if (getInputIndex != null) {
+ optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
+ if (!optional.isPresent()) {
+ log.debug("Failed to find input {} ", getInputIndex.getInputName());
+ // @@TODO error message
+ throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
+ }
+ InputDefinition inputIndex = optional.get();
+ getInputIndex.setInputId(inputIndex.getUniqueId());
+ getInputValues.add(getInputIndex);
+ }
+ }
- property.setValue(validPropertyVAlue);
-
- if (isNotEmpty(getInputs)) {
- List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
- for (GetInputValueDataDefinition getInput : getInputs) {
- List<InputDefinition> inputs = resource.getInputs();
- if (CollectionUtils.isEmpty(inputs)) {
- loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
- StatusCode.ERROR,"ERROR Failed to add property: "+propName+" to resource instance: {}. Inputs list is empty ",currentCompInstance.getUniqueId());
- log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property,
- currentCompInstance.getUniqueId());
- throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
- }
-
- Optional<InputDefinition> optional = inputs.stream()
- .filter(p -> p.getName()
- .equals(getInput.getInputName()))
- .findAny();
- if (!optional.isPresent()) {
- loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
- StatusCode.ERROR,"ERROR Failed to find input: "+getInput.getInputName());
- log.debug("Failed to find input {} ", getInput.getInputName());
- // @@TODO error message
- throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
- }
- InputDefinition input = optional.get();
- getInput.setInputId(input.getUniqueId());
- getInputValues.add(getInput);
-
- GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
- processGetInput(getInputValues, inputs, getInputIndex);
- }
- property.setGetInputValues(getInputValues);
- }
- instPropList.add(property);
- // delete overriden property
- currPropertiesMap.remove(property.getName());
- }
-
- private void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs,
- GetInputValueDataDefinition getInputIndex) {
- Optional<InputDefinition> optional;
- if (getInputIndex != null) {
- optional = inputs.stream()
- .filter(p -> p.getName()
- .equals(getInputIndex.getInputName()))
- .findAny();
- if (!optional.isPresent()) {
- log.debug("Failed to find input {} ", getInputIndex.getInputName());
- // @@TODO error message
- throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
- }
- InputDefinition inputIndex = optional.get();
- getInputIndex.setInputId(inputIndex.getUniqueId());
- getInputValues.add(getInputIndex);
- }
- }
-
- private void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
- String propName = prop.getName();
- if (!currPropertiesMap.containsKey(propName)) {
- currPropertiesMap.put(propName, prop);
- }
- }
-
- private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
- Resource resource, Resource originResource, ComponentInstance currentCompInstance,
- Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
-
- Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
- Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
-
- List<PropertyDefinition> listFromMap = originResource.getProperties();
- if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
- loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
- StatusCode.ERROR,"ERROR Failed to find properties");
- log.debug("failed to find properties");
- return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
- }
- if (listFromMap == null || listFromMap.isEmpty()) {
- return componentsUtils.getResponseFormat(ActionStatus.OK);
- }
- for (PropertyDefinition prop : listFromMap) {
- String propName = prop.getName();
- if (!currPropertiesMap.containsKey(propName)) {
- currPropertiesMap.put(propName, prop);
- }
- }
- List<ComponentInstanceProperty> instPropList = new ArrayList<>();
- if (propMap != null && propMap.size() > 0) {
- for (List<UploadPropInfo> propertyList : propMap.values()) {
-
- UploadPropInfo propertyInfo = propertyList.get(0);
- String propName = propertyInfo.getName();
- if (!currPropertiesMap.containsKey(propName)) {
- log.debug("failed to find property {} ", propName);
- loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR Failed to find property: {}",propName);
- return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
- }
- PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
- ComponentInstanceProperty property = null;
-
- String value = null;
- List<GetInputValueDataDefinition> getInputs = null;
- boolean isValidate = true;
- if (propertyInfo.getValue() != null) {
- getInputs = propertyInfo.getGet_input();
- isValidate = getInputs == null || getInputs.isEmpty();
- if (isValidate) {
- value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
- } else {
- value = getPropertyJsonStringValue(propertyInfo.getValue(),
- TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
- }
- }
- property = new ComponentInstanceProperty(curPropertyDef, value, null);
+ private void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
+ String propName = prop.getName();
+ if (!currPropertiesMap.containsKey(propName)) {
+ currPropertiesMap.put(propName, prop);
+ }
+ }
+ private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource,
+ ComponentInstance currentCompInstance, Map<String, List<ComponentInstanceProperty>> instProperties,
+ Map<String, DataTypeDefinition> allDataTypes) {
+ Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
+ Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
+ List<PropertyDefinition> listFromMap = originResource.getProperties();
+ if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
+ loggerSupportability.log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "ERROR Failed to find properties");
+ log.debug("failed to find properties");
+ return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
+ }
+ if (listFromMap == null || listFromMap.isEmpty()) {
+ return componentsUtils.getResponseFormat(ActionStatus.OK);
+ }
+ for (PropertyDefinition prop : listFromMap) {
+ String propName = prop.getName();
+ if (!currPropertiesMap.containsKey(propName)) {
+ currPropertiesMap.put(propName, prop);
+ }
+ }
+ List<ComponentInstanceProperty> instPropList = new ArrayList<>();
+ if (propMap != null && propMap.size() > 0) {
+ for (List<UploadPropInfo> propertyList : propMap.values()) {
+ UploadPropInfo propertyInfo = propertyList.get(0);
+ String propName = propertyInfo.getName();
+ if (!currPropertiesMap.containsKey(propName)) {
+ log.debug("failed to find property {} ", propName);
+ loggerSupportability.log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "ERROR Failed to find property: {}", propName);
+ return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
+ }
+ PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
+ ComponentInstanceProperty property = null;
+ String value = null;
+ List<GetInputValueDataDefinition> getInputs = null;
+ boolean isValidate = true;
+ if (propertyInfo.getValue() != null) {
+ getInputs = propertyInfo.getGet_input();
+ isValidate = getInputs == null || getInputs.isEmpty();
+ if (isValidate) {
+ value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
+ } else {
+ value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
+ }
+ }
+ property = new ComponentInstanceProperty(curPropertyDef, value, null);
String validatePropValue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
property.setValue(validatePropValue);
+ if (getInputs != null && !getInputs.isEmpty()) {
+ List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
+ for (GetInputValueDataDefinition getInput : getInputs) {
+ List<InputDefinition> inputs = resource.getInputs();
+ if (inputs == null || inputs.isEmpty()) {
+ log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
+ loggerSupportability
+ .log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "Failed to add property: {} to instance. Inputs list is empty", propName);
+ rollbackWithException(ActionStatus.INPUTS_NOT_FOUND,
+ property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
+ }
+ Either<InputDefinition, RuntimeException> inputEither = findInputByName(inputs, getInput);
+ if (inputEither.isRight()) {
+ throw inputEither.right().value();
+ } else {
+ InputDefinition input = inputEither.left().value();
+ getInput.setInputId(input.getUniqueId());
+ getInputValues.add(getInput);
+ GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
+ if (getInputIndex != null) {
+ Either<InputDefinition, RuntimeException> newInputEither = findInputByName(inputs, getInputIndex);
+ if (inputEither.isRight()) {
+ throw newInputEither.right().value();
+ } else {
+ InputDefinition newInput = newInputEither.left().value();
+ getInputIndex.setInputId(newInput.getUniqueId());
+ }
+ getInputValues.add(getInputIndex);
+ }
+ }
+ }
+ property.setGetInputValues(getInputValues);
+ }
+ instPropList.add(property);
+ // delete overriden property
+ currPropertiesMap.remove(property.getName());
+ }
+ }
+ // add rest of properties
+ if (!currPropertiesMap.isEmpty()) {
+ for (PropertyDefinition value : currPropertiesMap.values()) {
+ instPropList.add(new ComponentInstanceProperty(value));
+ }
+ }
+ instProperties.put(currentCompInstance.getUniqueId(), instPropList);
+ return componentsUtils.getResponseFormat(ActionStatus.OK);
+ }
+
+ // US740820 Relate RIs according to capability name
+ private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, ComponentInstance currentCapCompInstance,
+ UploadReqInfo uploadReqInfo) {
+ if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability()
+ .equals(uploadReqInfo.getCapabilityName())) {// get
+
+ // by
+
+ // capability
+
+ // type
+ return findAvailableCapability(validReq, currentCapCompInstance);
+ }
+ return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
+ }
+
+ private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance,
+ UploadReqInfo uploadReqInfo) {
+ CapabilityDefinition cap = null;
+ Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
+ if (!capMap.containsKey(validReq.getCapability())) {
+ return null;
+ }
+ Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream()
+ .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
+ if (!capByName.isPresent()) {
+ return null;
+ }
+ cap = capByName.get();
+ if (isBoundedByOccurrences(cap)) {
+ String leftOccurrences = cap.getLeftOccurrences();
+ int left = Integer.parseInt(leftOccurrences);
+ if (left > 0) {
+ --left;
+ cap.setLeftOccurrences(String.valueOf(left));
+ }
+ }
+ return cap;
+ }
+
+ private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
+ Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
+ if (capMap.containsKey(validReq.getCapability())) {
+ List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
+ for (CapabilityDefinition cap : capList) {
+ if (isBoundedByOccurrences(cap)) {
+ String leftOccurrences = cap.getLeftOccurrences() != null ? cap.getLeftOccurrences() : cap.getMaxOccurrences();
+ int left = Integer.parseInt(leftOccurrences);
+ if (left > 0) {
+ --left;
+ cap.setLeftOccurrences(String.valueOf(left));
+ return cap;
+ }
+ } else {
+ return cap;
+ }
+ }
+ }
+ return null;
+ }
+
+ private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
+ return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES);
+ }
+
+ private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
+ UploadComponentInstanceInfo uploadComponentInstanceInfo,
+ ComponentInstance currentCompInstance, String capName) {
+ Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
+ List<RequirementDefinition> list = comInstRegDefMap.get(capName);
+ RequirementDefinition validRegDef = null;
+ if (list == null) {
+ for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
+ for (RequirementDefinition reqDef : entry.getValue()) {
+ if (reqDef.getName().equals(regName)) {
+ if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
+ String leftOccurrences = reqDef.getLeftOccurrences();
+ if (leftOccurrences == null) {
+ leftOccurrences = reqDef.getMaxOccurrences();
+ }
+ int left = Integer.parseInt(leftOccurrences);
+ if (left > 0) {
+ --left;
+ reqDef.setLeftOccurrences(String.valueOf(left));
+ validRegDef = reqDef;
+ break;
+ } else {
+ continue;
+ }
+ } else {
+ validRegDef = reqDef;
+ break;
+ }
+ }
+ }
+ if (validRegDef != null) {
+ break;
+ }
+ }
+ } else {
+ for (RequirementDefinition reqDef : list) {
+ if (reqDef.getName().equals(regName)) {
+ if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
+ String leftOccurrences = reqDef.getLeftOccurrences();
+ if (leftOccurrences == null) {
+ leftOccurrences = reqDef.getMaxOccurrences();
+ }
+ int left = Integer.parseInt(leftOccurrences);
+ if (left > 0) {
+ --left;
+ reqDef.setLeftOccurrences(String.valueOf(left));
+ validRegDef = reqDef;
+ break;
+ } else {
+ continue;
+ }
+ } else {
+ validRegDef = reqDef;
+ break;
+ }
+ }
+ }
+ }
+ if (validRegDef == null) {
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
+ uploadComponentInstanceInfo.getType());
+ return Either.right(responseFormat);
+ }
+ return Either.left(validRegDef);
+ }
- if (getInputs != null && !getInputs.isEmpty()) {
- List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
- for (GetInputValueDataDefinition getInput : getInputs) {
- List<InputDefinition> inputs = resource.getInputs();
- if (inputs == null || inputs.isEmpty()) {
- log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
- loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"Failed to add property: {} to instance. Inputs list is empty",propName);
- rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
- .stream()
- .map(GetInputValueDataDefinition::getInputName)
- .collect(toList())
- .toString());
- }
- Either<InputDefinition, RuntimeException> inputEither = findInputByName(inputs, getInput);
- if (inputEither.isRight()) {
- throw inputEither.right().value();
- } else {
- InputDefinition input = inputEither.left().value();
- getInput.setInputId(input.getUniqueId());
- getInputValues.add(getInput);
-
- GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
- if (getInputIndex != null) {
- Either<InputDefinition, RuntimeException> newInputEither = findInputByName(inputs,
- getInputIndex);
- if (inputEither.isRight()) {
- throw newInputEither.right().value();
- } else {
- InputDefinition newInput = newInputEither.left().value();
- getInputIndex.setInputId(newInput.getUniqueId());
- }
- getInputValues.add(getInputIndex);
-
- }
- }
- }
- property.setGetInputValues(getInputValues);
- }
- instPropList.add(property);
- // delete overriden property
- currPropertiesMap.remove(property.getName());
- }
- }
- // add rest of properties
- if (!currPropertiesMap.isEmpty()) {
- for (PropertyDefinition value : currPropertiesMap.values()) {
- instPropList.add(new ComponentInstanceProperty(value));
- }
- }
- instProperties.put(currentCompInstance.getUniqueId(), instPropList);
- return componentsUtils.getResponseFormat(ActionStatus.OK);
- }
-
- // US740820 Relate RIs according to capability name
- private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq,
- ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
- if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability()
- .equals(uploadReqInfo.getCapabilityName())) {// get
- // by
- // capability
- // type
- return findAvailableCapability(validReq, currentCapCompInstance);
- }
- return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
- }
-
- private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq,
- ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
- CapabilityDefinition cap = null;
- Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
- if (!capMap.containsKey(validReq.getCapability())) {
- return null;
- }
- Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability())
- .stream()
- .filter(p -> p.getName()
- .equals(uploadReqInfo.getCapabilityName()))
- .findAny();
- if (!capByName.isPresent()) {
- return null;
- }
- cap = capByName.get();
-
- if (isBoundedByOccurrences(cap)) {
- String leftOccurrences = cap.getLeftOccurrences();
- int left = Integer.parseInt(leftOccurrences);
- if (left > 0) {
- --left;
- cap.setLeftOccurrences(String.valueOf(left));
-
- }
-
- }
- return cap;
- }
-
- private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
- Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
- if (capMap.containsKey(validReq.getCapability())) {
- List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
-
- for (CapabilityDefinition cap : capList) {
- if (isBoundedByOccurrences(cap)) {
- String leftOccurrences = cap.getLeftOccurrences() != null ? cap.getLeftOccurrences()
- : cap.getMaxOccurrences();
- int left = Integer.parseInt(leftOccurrences);
- if (left > 0) {
- --left;
- cap.setLeftOccurrences(String.valueOf(left));
- return cap;
- }
- } else {
- return cap;
- }
- }
- }
- return null;
- }
-
- private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
- return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences()
- .equals(CapabilityDataDefinition.MAX_OCCURRENCES);
- }
-
- private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
- UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
- String capName) {
- Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
- List<RequirementDefinition> list = comInstRegDefMap.get(capName);
- RequirementDefinition validRegDef = null;
- if (list == null) {
- for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
- for (RequirementDefinition reqDef : entry.getValue()) {
- if (reqDef.getName()
- .equals(regName)) {
- if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences()
- .equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
- String leftOccurrences = reqDef.getLeftOccurrences();
- if (leftOccurrences == null) {
- leftOccurrences = reqDef.getMaxOccurrences();
- }
- int left = Integer.parseInt(leftOccurrences);
- if (left > 0) {
- --left;
- reqDef.setLeftOccurrences(String.valueOf(left));
- validRegDef = reqDef;
- break;
- } else {
- continue;
- }
- } else {
- validRegDef = reqDef;
- break;
- }
-
- }
- }
- if (validRegDef != null) {
- break;
- }
- }
- } else {
- for (RequirementDefinition reqDef : list) {
- if (reqDef.getName()
- .equals(regName)) {
- if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences()
- .equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
- String leftOccurrences = reqDef.getLeftOccurrences();
- if (leftOccurrences == null) {
- leftOccurrences = reqDef.getMaxOccurrences();
- }
- int left = Integer.parseInt(leftOccurrences);
- if (left > 0) {
- --left;
- reqDef.setLeftOccurrences(String.valueOf(left));
- validRegDef = reqDef;
- break;
- } else {
- continue;
- }
- } else {
- validRegDef = reqDef;
- break;
- }
- }
- }
- }
- if (validRegDef == null) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
- yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- return Either.right(responseFormat);
- }
- return Either.left(validRegDef);
- }
-
- private Resource createResourceInstances(String yamlName, Resource resource, Resource oldResource,
- Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingNodeTypesByResourceNames) {
-
- Either<Resource, ResponseFormat> eitherResource;
- log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
+ private Resource createResourceInstances(String yamlName, Resource resource, Resource oldResource,
+ Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, Map<String, Resource> nodeNamespaceMap,
+ Map<String, Resource> existingNodeTypesByResourceNames) {
+ Either<Resource, ResponseFormat> eitherResource;
+ log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
if (isEmpty(uploadResInstancesMap) && resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
throw new ByResponseFormatComponentException(responseFormat);
- }
- if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
- nodeNamespaceMap.forEach((k, v) -> existingNodeTypesByResourceNames.put(v.getToscaResourceName(), v));
- }
- Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
- uploadResInstancesMap.values()
- .forEach(i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap,
- existingNodeTypesByResourceNames, resourcesInstancesMap));
- if (oldResource != null && oldResource.getResourceType() != ResourceTypeEnum.CVFC && oldResource.getComponentInstances() != null) {
- Map<String, Resource> existingNodeTypesByUids = existingNodeTypesByResourceNames.values()
- .stream()
- .collect(toMap(Resource::getUniqueId, r -> r));
- oldResource.getComponentInstances()
- .stream()
- .filter(i -> !i.isCreatedFromCsar())
- .forEach(uiInst -> resourcesInstancesMap.put(uiInst,
- getOriginResource(existingNodeTypesByUids, uiInst)));
- }
-
- if (isNotEmpty(resourcesInstancesMap)) {
- try {
- toscaOperationFacade.associateComponentInstancesToComponent(resource,
- resourcesInstancesMap, false, oldResource != null);
- } catch (StorageException exp) {
- if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
- log.debug("Failed to add component instances to container component {}", resource.getName());
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
- eitherResource = Either.right(responseFormat);
- throw new ByResponseFormatComponentException(eitherResource.right().value());
- }
- }
- }
+ }
+ if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
+ nodeNamespaceMap.forEach((k, v) -> existingNodeTypesByResourceNames.put(v.getToscaResourceName(), v));
+ }
+ Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
+ uploadResInstancesMap.values().forEach(
+ i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypesByResourceNames, resourcesInstancesMap));
+ if (oldResource != null && oldResource.getResourceType() != ResourceTypeEnum.CVFC && oldResource.getComponentInstances() != null) {
+ Map<String, Resource> existingNodeTypesByUids = existingNodeTypesByResourceNames.values().stream()
+ .collect(toMap(Resource::getUniqueId, r -> r));
+ oldResource.getComponentInstances().stream().filter(i -> !i.isCreatedFromCsar())
+ .forEach(uiInst -> resourcesInstancesMap.put(uiInst, getOriginResource(existingNodeTypesByUids, uiInst)));
+ }
+ if (isNotEmpty(resourcesInstancesMap)) {
+ try {
+ toscaOperationFacade.associateComponentInstancesToComponent(resource, resourcesInstancesMap, false, oldResource != null);
+ } catch (StorageException exp) {
+ if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
+ log.debug("Failed to add component instances to container component {}", resource.getName());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
+ eitherResource = Either.right(responseFormat);
+ throw new ByResponseFormatComponentException(eitherResource.right().value());
+ }
+ }
+ }
if (CollectionUtils.isEmpty(resource.getComponentInstances()) &&
- resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
- log.debug("Error when create resource instance from csar. ComponentInstances list empty");
- BeEcompErrorManager.getInstance()
- .logBeDaoSystemError(
- "Error when create resource instance from csar. ComponentInstances list empty");
- throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
- }
- return resource;
- }
-
- private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName,
- Resource resource, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap,
- Map<ComponentInstance, Resource> resourcesInstancesMap) {
- Either<Resource, ResponseFormat> eitherResource;
- log.debug("*************Going to create resource instances {}", yamlName);
- // updating type if the type is node type name - we need to take the
- // updated name
- log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
- if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
- uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType())
- .getToscaResourceName());
- }
- Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
- existingnodeTypeMap, resource);
-
- ComponentInstance componentInstance = new ComponentInstance();
- componentInstance.setComponentUid(refResource.getUniqueId());
+ resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
+ log.debug("Error when create resource instance from csar. ComponentInstances list empty");
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource instance from csar. ComponentInstances list empty");
+ throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
+ }
+ return resource;
+ }
+
+ private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName, Resource resource,
+ Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap,
+ Map<ComponentInstance, Resource> resourcesInstancesMap) {
+ Either<Resource, ResponseFormat> eitherResource;
+ log.debug("*************Going to create resource instances {}", yamlName);
+ // updating type if the type is node type name - we need to take the
+
+ // updated name
+ log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
+ if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
+ uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
+ }
+ Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, existingnodeTypeMap, resource);
+ ComponentInstance componentInstance = new ComponentInstance();
+ componentInstance.setComponentUid(refResource.getUniqueId());
Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
- if(directives != null && !directives.isEmpty()) {
+ if (directives != null && !directives.isEmpty()) {
componentInstance.setDirectives(new ArrayList<>(directives));
}
UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
- if (uploadNodeFilterInfo != null){
- componentInstance.setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo,
- componentInstance.getUniqueId()));
+ if (uploadNodeFilterInfo != null) {
+ componentInstance
+ .setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo, componentInstance.getUniqueId()));
}
ComponentTypeEnum containerComponentType = resource.getComponentType();
- NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
- if (containerNodeType == NodeTypeEnum.Resource && isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
- && isNotEmpty(refResource.getCapabilities())) {
- setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
- Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities(
- refResource.getUniqueId(), refResource.getCapabilities(),
- uploadComponentInstanceInfo.getCapabilities());
- componentInstance.setCapabilities(validComponentInstanceCapabilities);
- }
-
+ NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
+ if (containerNodeType == NodeTypeEnum.Resource && isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) && isNotEmpty(
+ refResource.getCapabilities())) {
+ setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
+ Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities(
+ refResource.getUniqueId(), refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
+ componentInstance.setCapabilities(validComponentInstanceCapabilities);
+ }
if (isNotEmpty(uploadComponentInstanceInfo.getArtifacts())) {
Map<String, Map<String, UploadArtifactInfo>> artifacts = uploadComponentInstanceInfo.getArtifacts();
Map<String, ToscaArtifactDataDefinition> toscaArtifacts = new HashMap<>();
Map<String, Map<String, UploadArtifactInfo>> arts = artifacts.entrySet().stream()
- .filter(e -> e.getKey().contains(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName()))
- .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
+ .filter(e -> e.getKey().contains(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName()))
+ .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
Map<String, UploadArtifactInfo> artifact = arts.get(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName());
for (Map.Entry<String, UploadArtifactInfo> entry : artifact.entrySet()) {
ToscaArtifactDataDefinition to = new ToscaArtifactDataDefinition();
@@ -3751,1717 +3170,1420 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
componentInstance.setToscaArtifacts(toscaArtifacts);
}
+ if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
+ log.debug("createResourceInstances - not found lates version for resource instance with name {} and type ",
+ uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+ throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
+ uploadComponentInstanceInfo.getType());
+ }
+ Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
+ componentInstance.setName(uploadComponentInstanceInfo.getName());
+ componentInstance.setIcon(origResource.getIcon());
+ componentInstance.setCreatedFrom(CreatedFrom.CSAR);
+ resourcesInstancesMap.put(componentInstance, origResource);
+ }
+
+ private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
+ Map<String, List<UploadCapInfo>> uploadedCapabilities) {
+ for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
+ if (originCapabilities.containsKey(currEntry.getKey())) {
+ currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey()));
+ }
+ }
+ for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
+ capabilities.getValue().stream().forEach(cap -> {
+ if (uploadedCapabilities.containsKey(cap.getName())) {
+ uploadedCapabilities.get(cap.getName()).stream().forEach(c -> {
+ c.setName(cap.getName());
+ c.setType(cap.getType());
+ });
+ }
+ });
+ }
+ }
+
+ private Resource validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo,
+ Map<String, Resource> nodeNamespaceMap, Resource resource) {
+ log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type {} before create",
+ uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+ Resource refResource;
+ if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
+ refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
+ } else {
+ Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
+ .getByToscaResourceNameMatchingVendorRelease(uploadComponentInstanceInfo.getType(),
+ ((ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition()).getVendorRelease());
+ if (findResourceEither.isRight()) {
+ log.debug("validateResourceInstanceBeforeCreate - not found latest version for resource instance with name {} and type {}",
+ uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
+ }
+ refResource = findResourceEither.left().value();
+ nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
+ }
+ String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
+ if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ log.debug(
+ "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.",
+ refResource.getName(), componentState);
+ throw new ByActionStatusComponentException(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(),
+ refResource.getName(), componentState);
+ }
+ if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
+ log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType());
+ throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
+ uploadComponentInstanceInfo.getType());
+ }
+ return refResource;
+ }
- if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
- log.debug("createResourceInstances - not found lates version for resource instance with name {} and type ",
- uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
- yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- }
- Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
- componentInstance.setName(uploadComponentInstanceInfo.getName());
- componentInstance.setIcon(origResource.getIcon());
- componentInstance.setCreatedFrom(CreatedFrom.CSAR);
- resourcesInstancesMap.put(componentInstance, origResource);
- }
-
- private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
- Map<String, List<UploadCapInfo>> uploadedCapabilities) {
- for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
- if (originCapabilities.containsKey(currEntry.getKey())) {
- currEntry.getValue()
- .stream()
- .forEach(cap -> cap.setType(currEntry.getKey()));
- }
- }
- for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
- capabilities.getValue()
- .stream()
- .forEach(cap -> {
- if (uploadedCapabilities.containsKey(cap.getName())) {
- uploadedCapabilities.get(cap.getName())
- .stream()
- .forEach(c -> {
- c.setName(cap.getName());
- c.setType(cap.getType());
- });
- }
- });
- }
- }
-
- private Resource validateResourceInstanceBeforeCreate(String yamlName,
- UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeNamespaceMap, Resource resource) {
-
- log.debug(
- "validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type {} before create",
- uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- Resource refResource;
- if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
- refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
- } else {
- Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
- .getByToscaResourceNameMatchingVendorRelease(uploadComponentInstanceInfo.getType(),
- ((ResourceMetadataDataDefinition)resource.getComponentMetadataDefinition().getMetadataDataDefinition()).getVendorRelease());
- if (findResourceEither.isRight()) {
- log.debug(
- "validateResourceInstanceBeforeCreate - not found latest version for resource instance with name {} and type {}",
- uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
- }
- refResource = findResourceEither.left().value();
- nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
- }
- String componentState = refResource.getComponentMetadataDefinition()
- .getMetadataDataDefinition()
- .getState();
- if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
- log.debug(
- "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.",
- refResource.getName(), componentState);
- throw new ByActionStatusComponentException(ActionStatus.ILLEGAL_COMPONENT_STATE,
- refResource.getComponentType().getValue(),refResource.getName(), componentState);
- }
-
- if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
- log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType());
- throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
- yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- }
- return refResource;
- }
-
- public Resource propagateStateToCertified(User user, Resource resource,
- LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
- boolean forceCertificationAllowed) {
-
- boolean failed = false;
- try {
- if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed
- && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) {
- nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
- }
- if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
- Either<ArtifactDefinition, Operation> eitherPopulated = populateToscaArtifacts(
- resource, user, false, inTransaction, needLock, false);
- return resource;
- }
- return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
- } catch (ComponentException e) {
- failed = true;
- log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
- throw e;
- } finally {
- if (failed) {
- BeEcompErrorManager.getInstance()
- .logBeSystemError("Change LifecycleState - Certify");
- if (!inTransaction) {
+ public Resource propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
+ boolean needLock, boolean forceCertificationAllowed) {
+ boolean failed = false;
+ try {
+ if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed && lifecycleBusinessLogic
+ .isFirstCertification(resource.getVersion())) {
+ nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
+ }
+ if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
+ Either<ArtifactDefinition, Operation> eitherPopulated = populateToscaArtifacts(resource, user, false, inTransaction, needLock, false);
+ return resource;
+ }
+ return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
+ } catch (ComponentException e) {
+ failed = true;
+ log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
+ throw e;
+ } finally {
+ if (failed) {
+ BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
+ if (!inTransaction) {
janusGraphDao.rollback();
- }
- } else if (!inTransaction) {
+ }
+ } else if (!inTransaction) {
janusGraphDao.commit();
- }
- }
- }
-
- private Resource nodeFullCertification(String uniqueId, User user,
- LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
- Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo,
- inTransaction, needLock);
- if(resourceResponse.isRight()){
- throw new ByResponseFormatComponentException(resourceResponse.right().value());
- }
- return resourceResponse.left().value();
- }
-
- private Resource nodeForceCertification(Resource resource, User user,
- LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
- return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction,
- needLock);
- }
-
- public ImmutablePair<Resource, ActionStatus> createOrUpdateResourceByImport(final Resource resource,
- final User user,
- final boolean isNormative,
- final boolean isInTransaction,
- final boolean needLock,
- final CsarInfo csarInfo,
- final String nodeName,
- final boolean isNested) {
-
- ImmutablePair<Resource, ActionStatus> result = null;
- // check if resource already exists (search by tosca name = type)
- final boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName);
- final Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
- .getLatestByToscaResourceName(resource.getToscaResourceName());
-
- if (latestByToscaName.isLeft()) {
- Resource foundResource = latestByToscaName.left().value();
- // we don't allow updating names of top level types
- if (!isNestedResource && !StringUtils.equals(resource.getName(), foundResource.getName())) {
- BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import",
- ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
- log.debug("resource already exist new name={} old name={} same type={}", resource.getName(),
- foundResource.getName(), resource.getToscaResourceName());
- final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
- componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
- throwComponentException(responseFormat);
- }
- result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested);
- } else if (isNotFound(latestByToscaName)) {
- if (isNestedResource) {
- result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo,
- isNested, nodeName);
- } else {
- result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
- }
- } else {
- StorageOperationStatus status = latestByToscaName.right().value();
- log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils
- .convertFromStorageResponse(latestByToscaName.right().value()), resource);
- componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
- throwComponentException(responseFormat);
- }
- return result;
- }
-
- private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) {
- return csarInfo != null && csarInfo.isUpdate() && nodeName != null;
- }
-
- private ImmutablePair<Resource, ActionStatus> createOrUpdateNestedResource(final Resource resource,
- final User user,
- final boolean isNormative,
- final boolean isInTransaction,
- final boolean needLock,
- final CsarInfo csarInfo,
- final boolean isNested,
- final String nodeName) {
- final Either<Component, StorageOperationStatus> latestByToscaName = toscaOperationFacade
- .getLatestByToscaResourceName(buildNestedToscaResourceName(resource.getResourceType()
- .name(), csarInfo.getVfResourceName(), nodeName).getRight());
- if (latestByToscaName.isLeft()) {
- final Resource nestedResource = (Resource) latestByToscaName.left().value();
- log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
- final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource,
- resource, ValidationUtils.hasBeenCertified(nestedResource.getVersion()));
- if (eitherValidation.isRight()) {
- return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
- }
- return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested);
- } else {
- return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
- }
- }
-
- private boolean isNotFound(Either<Resource, StorageOperationStatus> getResourceEither) {
- return getResourceEither.isRight() && getResourceEither.right()
- .value() == StorageOperationStatus.NOT_FOUND;
- }
-
- private ImmutablePair<Resource, ActionStatus> createResourceByImport(Resource resource, User user,
- boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
- log.debug("resource with name {} does not exist. create new resource", resource.getName());
- validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
- final Resource createResourceByDao = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative,
- isInTransaction);
- Resource createdResource = updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Resource)r).left().value();
- ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createdResource, ActionStatus.CREATED);
- ASDCKpiApi.countImportResourcesKPI();
- return resourcePair;
- }
-
- public boolean isResourceExist(String resourceName) {
- Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
- return latestByName.isLeft();
- }
-
- private ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(Resource newResource,
- Resource oldResource, User user, boolean inTransaction, boolean needLock, boolean isNested) {
- String lockedResourceId = oldResource.getUniqueId();
- log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId,
- oldResource.getVersion(), oldResource.getLifecycleState());
- ImmutablePair<Resource, ActionStatus> resourcePair = null;
- try {
- lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
- oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
- mergeOldResourceMetadataWithNew(oldResource, newResource);
-
- validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
- validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
- // contact info normalization
- newResource.setContactId(newResource.getContactId().toLowerCase());
- PropertyConstraintsUtils.validatePropertiesConstraints(newResource, oldResource);
- // non-updatable fields
- newResource.setCreatorUserId(user.getUserId());
- newResource.setCreatorFullName(user.getFullName());
- newResource.setLastUpdaterUserId(user.getUserId());
- newResource.setLastUpdaterFullName(user.getFullName());
- newResource.setUniqueId(oldResource.getUniqueId());
- newResource.setVersion(oldResource.getVersion());
- newResource.setInvariantUUID(oldResource.getInvariantUUID());
- newResource.setLifecycleState(oldResource.getLifecycleState());
- newResource.setUUID(oldResource.getUUID());
- newResource.setNormalizedName(oldResource.getNormalizedName());
- newResource.setSystemName(oldResource.getSystemName());
- if (oldResource.getCsarUUID() != null) {
- newResource.setCsarUUID(oldResource.getCsarUUID());
- }
- if (oldResource.getImportedToscaChecksum() != null) {
- newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
- }
- newResource.setAbstract(oldResource.isAbstract());
-
- if (CollectionUtils.isEmpty(newResource.getDerivedFrom())){
- newResource.setDerivedFrom(oldResource.getDerivedFrom());
- }
- if (CollectionUtils.isEmpty(newResource.getDataTypes())){
- newResource.setDataTypes(oldResource.getDataTypes());
- }
- if (StringUtils.isEmpty(newResource.getDerivedFromGenericType())){
- newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
- }
- if (StringUtils.isEmpty(newResource.getDerivedFromGenericVersion())){
- newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
- }
- // add for new)
- // created without tosca artifacts - add the placeholders
- if (MapUtils.isEmpty(newResource.getToscaArtifacts())){
- setToscaArtifactsPlaceHolders(newResource, user);
- }
-
- if (MapUtils.isEmpty(newResource.getInterfaces())){
- newResource.setInterfaces(oldResource.getInterfaces());
- }
- if (CollectionUtils.isEmpty(newResource.getAttributes())) {
- newResource.setAttributes(oldResource.getAttributes());
- }
-
- if (CollectionUtils.isEmpty(newResource.getProperties())) {
- newResource.setProperties(oldResource.getProperties());
- }
-
- Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
-
- if (overrideResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right()
- .value()), newResource);
- componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
-
- throwComponentException(responseFormat);
- }
- updateCatalog(overrideResource.left()
- .value(), ChangeTypeEnum.LIFECYCLE);
-
- log.debug("Resource updated successfully!!!");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
- ResourceVersionInfo.newBuilder()
- .state(oldResource.getLifecycleState()
- .name())
- .version(oldResource.getVersion())
- .build());
-
- resourcePair = new ImmutablePair<>(overrideResource.left()
- .value(), ActionStatus.OK);
- return resourcePair;
- } finally {
- if (resourcePair == null) {
- BeEcompErrorManager.getInstance()
- .logBeSystemError("Change LifecycleState - Certify");
- janusGraphDao.rollback();
- } else if (!inTransaction) {
+ }
+ }
+ }
+
+ private Resource nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
+ boolean needLock) {
+ Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic
+ .changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
+ if (resourceResponse.isRight()) {
+ throw new ByResponseFormatComponentException(resourceResponse.right().value());
+ }
+ return resourceResponse.left().value();
+ }
+
+ private Resource nodeForceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
+ boolean needLock) {
+ return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
+ }
+
+ public ImmutablePair<Resource, ActionStatus> createOrUpdateResourceByImport(final Resource resource, final User user, final boolean isNormative,
+ final boolean isInTransaction, final boolean needLock,
+ final CsarInfo csarInfo, final String nodeName,
+ final boolean isNested) {
+ ImmutablePair<Resource, ActionStatus> result = null;
+ // check if resource already exists (search by tosca name = type)
+ final boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName);
+ final Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
+ .getLatestByToscaResourceName(resource.getToscaResourceName());
+ if (latestByToscaName.isLeft()) {
+ Resource foundResource = latestByToscaName.left().value();
+ // we don't allow updating names of top level types
+ if (!isNestedResource && !StringUtils.equals(resource.getName(), foundResource.getName())) {
+ BeEcompErrorManager.getInstance()
+ .logBeComponentMissingError("Create / Update resource by import", ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
+ log.debug("resource already exist new name={} old name={} same type={}", resource.getName(), foundResource.getName(),
+ resource.getToscaResourceName());
+ final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
+ componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
+ throwComponentException(responseFormat);
+ }
+ result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested);
+ } else if (isNotFound(latestByToscaName)) {
+ if (isNestedResource) {
+ result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo, isNested, nodeName);
+ } else {
+ result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
+ }
+ } else {
+ StorageOperationStatus status = latestByToscaName.right().value();
+ log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(latestByToscaName.right().value()), resource);
+ componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
+ throwComponentException(responseFormat);
+ }
+ return result;
+ }
+
+ private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) {
+ return csarInfo != null && csarInfo.isUpdate() && nodeName != null;
+ }
+
+ private ImmutablePair<Resource, ActionStatus> createOrUpdateNestedResource(final Resource resource, final User user, final boolean isNormative,
+ final boolean isInTransaction, final boolean needLock,
+ final CsarInfo csarInfo, final boolean isNested,
+ final String nodeName) {
+ final Either<Component, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(
+ buildNestedToscaResourceName(resource.getResourceType().name(), csarInfo.getVfResourceName(), nodeName).getRight());
+ if (latestByToscaName.isLeft()) {
+ final Resource nestedResource = (Resource) latestByToscaName.left().value();
+ log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
+ final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource, resource,
+ ValidationUtils.hasBeenCertified(nestedResource.getVersion()));
+ if (eitherValidation.isRight()) {
+ return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
+ }
+ return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested);
+ } else {
+ return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
+ }
+ }
+
+ private boolean isNotFound(Either<Resource, StorageOperationStatus> getResourceEither) {
+ return getResourceEither.isRight() && getResourceEither.right().value() == StorageOperationStatus.NOT_FOUND;
+ }
+
+ private ImmutablePair<Resource, ActionStatus> createResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction,
+ CsarInfo csarInfo) {
+ log.debug("resource with name {} does not exist. create new resource", resource.getName());
+ validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
+ final Resource createResourceByDao = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction);
+ Resource createdResource = updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Resource) r).left().value();
+ ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createdResource, ActionStatus.CREATED);
+ ASDCKpiApi.countImportResourcesKPI();
+ return resourcePair;
+ }
+
+ public boolean isResourceExist(String resourceName) {
+ Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
+ return latestByName.isLeft();
+ }
+
+ private ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(Resource newResource, Resource oldResource, User user,
+ boolean inTransaction, boolean needLock, boolean isNested) {
+ String lockedResourceId = oldResource.getUniqueId();
+ log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, oldResource.getVersion(),
+ oldResource.getLifecycleState());
+ ImmutablePair<Resource, ActionStatus> resourcePair = null;
+ try {
+ lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
+ oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
+ mergeOldResourceMetadataWithNew(oldResource, newResource);
+ validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
+ validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
+ // contact info normalization
+ newResource.setContactId(newResource.getContactId().toLowerCase());
+ PropertyConstraintsUtils.validatePropertiesConstraints(newResource, oldResource);
+ // non-updatable fields
+ newResource.setCreatorUserId(user.getUserId());
+ newResource.setCreatorFullName(user.getFullName());
+ newResource.setLastUpdaterUserId(user.getUserId());
+ newResource.setLastUpdaterFullName(user.getFullName());
+ newResource.setUniqueId(oldResource.getUniqueId());
+ newResource.setVersion(oldResource.getVersion());
+ newResource.setInvariantUUID(oldResource.getInvariantUUID());
+ newResource.setLifecycleState(oldResource.getLifecycleState());
+ newResource.setUUID(oldResource.getUUID());
+ newResource.setNormalizedName(oldResource.getNormalizedName());
+ newResource.setSystemName(oldResource.getSystemName());
+ if (oldResource.getCsarUUID() != null) {
+ newResource.setCsarUUID(oldResource.getCsarUUID());
+ }
+ if (oldResource.getImportedToscaChecksum() != null) {
+ newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
+ }
+ newResource.setAbstract(oldResource.isAbstract());
+ if (CollectionUtils.isEmpty(newResource.getDerivedFrom())) {
+ newResource.setDerivedFrom(oldResource.getDerivedFrom());
+ }
+ if (CollectionUtils.isEmpty(newResource.getDataTypes())) {
+ newResource.setDataTypes(oldResource.getDataTypes());
+ }
+ if (StringUtils.isEmpty(newResource.getDerivedFromGenericType())) {
+ newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
+ }
+ if (StringUtils.isEmpty(newResource.getDerivedFromGenericVersion())) {
+ newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
+ }
+ // add for new)
+
+ // created without tosca artifacts - add the placeholders
+ if (MapUtils.isEmpty(newResource.getToscaArtifacts())) {
+ setToscaArtifactsPlaceHolders(newResource, user);
+ }
+ if (MapUtils.isEmpty(newResource.getInterfaces())) {
+ newResource.setInterfaces(oldResource.getInterfaces());
+ }
+ if (CollectionUtils.isEmpty(newResource.getAttributes())) {
+ newResource.setAttributes(oldResource.getAttributes());
+ }
+ if (CollectionUtils.isEmpty(newResource.getProperties())) {
+ newResource.setProperties(oldResource.getProperties());
+ }
+ Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
+ if (overrideResource.isRight()) {
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
+ componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
+ throwComponentException(responseFormat);
+ }
+ updateCatalog(overrideResource.left().value(), ChangeTypeEnum.LIFECYCLE);
+ log.debug("Resource updated successfully!!!");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
+ ResourceVersionInfo.newBuilder().state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build());
+ resourcePair = new ImmutablePair<>(overrideResource.left().value(), ActionStatus.OK);
+ return resourcePair;
+ } finally {
+ if (resourcePair == null) {
+ BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
+ janusGraphDao.rollback();
+ } else if (!inTransaction) {
janusGraphDao.commit();
- }
- if (needLock) {
- log.debug("unlock resource {}", lockedResourceId);
- graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
- }
- }
-
- }
-
- /**
- * Merge old resource with new. Keep old category and vendor name without
- * change
- *
- * @param oldResource
- * @param newResource
- */
- private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
-
- // keep old category and vendor name without change
- // merge the rest of the resource metadata
- if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
- newResource.setTags(oldResource.getTags());
- }
-
- if (newResource.getDescription() == null) {
- newResource.setDescription(oldResource.getDescription());
- }
-
- if (newResource.getVendorRelease() == null) {
- newResource.setVendorRelease(oldResource.getVendorRelease());
- }
-
- if (newResource.getResourceVendorModelNumber() == null) {
- newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
- }
-
- if (newResource.getContactId() == null) {
- newResource.setContactId(oldResource.getContactId());
- }
-
- newResource.setCategories(oldResource.getCategories());
- if (newResource.getVendorName() == null) {
- newResource.setVendorName(oldResource.getVendorName());
- }
- List<GroupDefinition>oldForUpdate = oldResource.getGroups();
- if(CollectionUtils.isNotEmpty(oldForUpdate)){
- List<GroupDefinition>groupForUpdate = oldForUpdate.stream().map(group -> new GroupDefinition(group)).collect(Collectors.toList());
-
- groupForUpdate.stream().filter(group -> group.isVspOriginated())
- .forEach(group -> group.setName(group.getInvariantName()));
-
- newResource.setGroups(groupForUpdate);
- }
-
-
- if(newResource.getResourceType().isAtomicType() && !newResource.getName().equals("Root")&& newResource.getResourceType() != ResourceTypeEnum.CVFC) {
- ResourceTypeEnum updatedResourceType = newResource.getResourceType();
- Component derivedFromResource = getParentComponent(newResource);
- if (derivedFromResource.getComponentType() == ComponentTypeEnum.RESOURCE) {
- Resource parentResource = (Resource) derivedFromResource;
- if (!(parentResource.isAbstract() && (ResourceTypeEnum.VFC == parentResource.getResourceType() || ResourceTypeEnum.ABSTRACT == parentResource.getResourceType())) &&
- parentResource.getResourceType() != updatedResourceType && oldResource.getResourceType() != updatedResourceType) {
- BeEcompErrorManager.getInstance()
- .logInternalDataError("mergeOldResourceMetadataWithNew", "resource type of the resource does not match to derived from resource type",
- ErrorSeverity.ERROR);
- log.debug("#mergeOldResourceMetadataWithNew - resource type {} of the resource {} does not match to derived from resource type {}",
- newResource.getResourceType(), newResource.getToscaResourceName(), parentResource.getResourceType());
- throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_TYPE);
- }
- }
- }
-
- }
-
- private Component getParentComponent(Resource newResource) {
- String toscaResourceNameDerivedFrom = newResource.getDerivedFrom().get(0);
- Either<Component, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(toscaResourceNameDerivedFrom);
- if(latestByToscaResourceName.isRight()){
- BeEcompErrorManager.getInstance()
- .logInternalDataError("mergeOldResourceMetadataWithNew", "derived from resource not found", ErrorSeverity.ERROR);
- log.debug("#mergeOldResourceMetadataWithNew - derived from resource {} not found", toscaResourceNameDerivedFrom);
- throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, toscaResourceNameDerivedFrom);
- }
- return latestByToscaResourceName.left().value();
- }
-
- private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user,
- boolean inTransaction, boolean needLock) {
-
- if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
- // checkout
- return lifecycleBusinessLogic.changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
- new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock)
- .left()
- .on(response -> failOnChangeState(response, user, oldResource, newResource));
- }
- return oldResource;
- }
-
- private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
- log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage());
- componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
- ResourceVersionInfo.newBuilder()
- .state(oldResource.getLifecycleState()
- .name())
- .version(oldResource.getVersion())
- .build());
- throw new ByResponseFormatComponentException(response);
- }
-
- public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum,
- boolean inTransaction, CsarInfo csarInfo) {
-
- validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
- validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
- validateLifecycleTypesCreate(user, resource, actionEnum);
- validateResourceType(user, resource, actionEnum);
- resource.setCreatorUserId(user.getUserId());
- resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
- resource.setContactId(resource.getContactId()
- .toLowerCase());
- if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
- String resourceSystemName;
- if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
- resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
- } else {
- resourceSystemName = resource.getSystemName();
- }
- resource.setToscaResourceName(CommonBeUtils
- .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
- }
-
- // Generate invariant UUID - must be here and not in operation since it
- // should stay constant during clone
- // TODO
- String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
- resource.setInvariantUUID(invariantUUID);
-
- return resource;
- }
-
- private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
- AuditingActionEnum actionEnum) {
- Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
- if (resource.getResourceType() == null) {
- log.debug("Invalid resource type for resource");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- eitherResult = Either.right(errorResponse);
- componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
- }
- return eitherResult;
- }
-
- private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource,
- AuditingActionEnum actionEnum) {
- Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
- if (resource.getInterfaces() != null && resource.getInterfaces()
- .size() > 0) {
- log.debug("validate interface lifecycle Types Exist");
- Iterator<InterfaceDefinition> intItr = resource.getInterfaces()
- .values()
- .iterator();
- while (intItr.hasNext() && eitherResult.isLeft()) {
- InterfaceDefinition interfaceDefinition = intItr.next();
- String intType = interfaceDefinition.getUniqueId();
- Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation
- .getInterface(intType);
- if (eitherCapTypeFound.isRight()) {
- if (eitherCapTypeFound.right()
- .value() == StorageOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance()
- .logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate",
- "Interface", intType);
- log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB",
- intType, resource.getName());
- BeEcompErrorManager.getInstance()
- .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
- log.debug("request to data model failed with error: {}", eitherCapTypeFound.right()
- .value()
- .name());
- }
-
- ResponseFormat errorResponse = componentsUtils
- .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
- eitherResult = Either.right(errorResponse);
- componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
- }
-
- }
- }
- return eitherResult;
- }
-
- private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user,
- ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
- boolean inTransaction) {
-
- Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
- if (resource.getCapabilities() != null && resource.getCapabilities()
- .size() > 0) {
- log.debug("validate capability Types Exist - capabilities section");
-
- for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities()
- .entrySet()) {
-
- eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum,
- eitherResult, typeEntry, inTransaction);
- if (eitherResult.isRight()) {
- return Either.right(eitherResult.right()
- .value());
- }
- }
- }
-
- if (resource.getRequirements() != null && resource.getRequirements()
- .size() > 0) {
- log.debug("validate capability Types Exist - requirements section");
- for (String type : resource.getRequirements()
- .keySet()) {
- eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource,
- resource.getRequirements()
- .get(type),
- actionEnum, eitherResult, type, inTransaction);
- if (eitherResult.isRight()) {
- return Either.right(eitherResult.right()
- .value());
- }
- }
- }
-
- return eitherResult;
- }
-
- // @param typeObject- the object to which the validation is done
- private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
- ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects,
- AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
- boolean inTransaction) {
- Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
- .getCapabilityType(type, inTransaction);
- if (eitherCapTypeFound.isRight()) {
- if (eitherCapTypeFound.right()
- .value() == StorageOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance()
- .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type",
- type);
- log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
- resource.getName());
- BeEcompErrorManager.getInstance()
- .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
- }
- log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right()
- .value()
- .name());
- ResponseFormat errorResponse = null;
- if (type != null) {
- errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
- } else {
- errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
- validationObjects);
- }
- eitherResult = Either.right(errorResponse);
- componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
- }
- return eitherResult;
- }
-
- private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
- ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
- Either<Boolean, ResponseFormat> eitherResult, Entry<String, List<CapabilityDefinition>> typeEntry,
- boolean inTransaction) {
- Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
- .getCapabilityType(typeEntry.getKey(), inTransaction);
- if (eitherCapTypeFound.isRight()) {
- if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance()
- .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type",
- typeEntry.getKey());
- log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB",
- typeEntry.getKey(), resource.getName());
- BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
- }
- log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
- eitherCapTypeFound.right().value().name());
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
- typeEntry.getKey());
- componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
- return Either.right(errorResponse);
- }
- CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
- if (capabilityTypeDefinition.getProperties() != null) {
- for (CapabilityDefinition capDef : typeEntry.getValue()) {
- List<ComponentInstanceProperty> properties = capDef.getProperties();
- List<ComponentInstanceProperty> changedProperties = new ArrayList<>();
- if (properties == null || properties.isEmpty()) {
- for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
- ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
- changedProperties.add(newProp);
- }
- } else {
- List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
- for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
- PropertyDefinition propFromDef = prop.getValue();
- boolean propFound = false;
- for (ComponentInstanceProperty cip : properties) {
- if (propFromDef.getName().equals(cip.getName())) {
- //merge property value and property description only, ignore other fields
- if(cip.getDescription() != null && !cip.getDescription().equals(propFromDef.getDescription())){
- propFromDef.setDescription(cip.getDescription());
- }
- propertyDataValueMergeBusinessLogic.mergePropertyValue(propFromDef, cip, new ArrayList<>());
- if(cip.getValue() != null){
- propFromDef.setValue(cip.getValue());
- }
- propsToAdd.add(new ComponentInstanceProperty(propFromDef));
- propFound = true;
- properties.remove(cip);
- break;
- }
- }
- if(!propFound) {
- propsToAdd.add(new ComponentInstanceProperty(propFromDef));
- }
- }
- if (!propsToAdd.isEmpty()) {
- changedProperties.addAll(propsToAdd);
- }
- }
- capDef.setProperties(changedProperties);
- }
- }
- return eitherResult;
- }
-
- public Resource createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum,
- boolean isNormative, boolean inTransaction) {
- // create resource
-
- // lock new resource name in order to avoid creation resource with same
- // name
- Resource createdResource = null;
- if (!inTransaction) {
- Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
- CREATE_RESOURCE);
- if (lockResult.isRight()) {
- ResponseFormat responseFormat = lockResult.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
- throw new ByResponseFormatComponentException(responseFormat);
- }
-
- log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
- }
- try {
- if (resource.deriveFromGeneric()) {
- handleResourceGenericType(resource);
- }
- createdResource = createResourceTransaction(resource, user, isNormative);
- componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user,
- createdResource, actionEnum);
- ASDCKpiApi.countCreatedResourcesKPI();
- } catch (ComponentException e) {
- ResponseFormat responseFormat = e.getResponseFormat() == null
- ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
- componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
- throw e;
- } catch (StorageException e) {
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
- componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
- throw e;
- } finally {
+ }
+ if (needLock) {
+ log.debug("unlock resource {}", lockedResourceId);
+ graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
+ }
+ }
+ }
+
+ /**
+ * Merge old resource with new. Keep old category and vendor name without change
+ *
+ * @param oldResource
+ * @param newResource
+ */
+ private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
+ // keep old category and vendor name without change
+
+ // merge the rest of the resource metadata
+ if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
+ newResource.setTags(oldResource.getTags());
+ }
+ if (newResource.getDescription() == null) {
+ newResource.setDescription(oldResource.getDescription());
+ }
+ if (newResource.getVendorRelease() == null) {
+ newResource.setVendorRelease(oldResource.getVendorRelease());
+ }
+ if (newResource.getResourceVendorModelNumber() == null) {
+ newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
+ }
+ if (newResource.getContactId() == null) {
+ newResource.setContactId(oldResource.getContactId());
+ }
+ newResource.setCategories(oldResource.getCategories());
+ if (newResource.getVendorName() == null) {
+ newResource.setVendorName(oldResource.getVendorName());
+ }
+ List<GroupDefinition> oldForUpdate = oldResource.getGroups();
+ if (CollectionUtils.isNotEmpty(oldForUpdate)) {
+ List<GroupDefinition> groupForUpdate = oldForUpdate.stream().map(group -> new GroupDefinition(group)).collect(Collectors.toList());
+ groupForUpdate.stream().filter(group -> group.isVspOriginated()).forEach(group -> group.setName(group.getInvariantName()));
+ newResource.setGroups(groupForUpdate);
+ }
+ if (newResource.getResourceType().isAtomicType() && !newResource.getName().equals("Root")
+ && newResource.getResourceType() != ResourceTypeEnum.CVFC) {
+ ResourceTypeEnum updatedResourceType = newResource.getResourceType();
+ Component derivedFromResource = getParentComponent(newResource);
+ if (derivedFromResource.getComponentType() == ComponentTypeEnum.RESOURCE) {
+ Resource parentResource = (Resource) derivedFromResource;
+ if (!(parentResource.isAbstract() && (ResourceTypeEnum.VFC == parentResource.getResourceType()
+ || ResourceTypeEnum.ABSTRACT == parentResource.getResourceType())) && parentResource.getResourceType() != updatedResourceType
+ && oldResource.getResourceType() != updatedResourceType) {
+ BeEcompErrorManager.getInstance().logInternalDataError("mergeOldResourceMetadataWithNew",
+ "resource type of the resource does not match to derived from resource type", ErrorSeverity.ERROR);
+ log.debug(
+ "#mergeOldResourceMetadataWithNew - resource type {} of the resource {} does not match to derived from resource type {}",
+ newResource.getResourceType(), newResource.getToscaResourceName(), parentResource.getResourceType());
+ throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_TYPE);
+ }
+ }
+ }
+ }
+
+ private Component getParentComponent(Resource newResource) {
+ String toscaResourceNameDerivedFrom = newResource.getDerivedFrom().get(0);
+ Either<Component, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade
+ .getLatestByToscaResourceName(toscaResourceNameDerivedFrom);
+ if (latestByToscaResourceName.isRight()) {
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError("mergeOldResourceMetadataWithNew", "derived from resource not found", ErrorSeverity.ERROR);
+ log.debug("#mergeOldResourceMetadataWithNew - derived from resource {} not found", toscaResourceNameDerivedFrom);
+ throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, toscaResourceNameDerivedFrom);
+ }
+ return latestByToscaResourceName.left().value();
+ }
+
+ private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user, boolean inTransaction, boolean needLock) {
+ if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
+ // checkout
+ return lifecycleBusinessLogic
+ .changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"),
+ inTransaction, needLock).left().on(response -> failOnChangeState(response, user, oldResource, newResource));
+ }
+ return oldResource;
+ }
+
+ private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
+ log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage());
+ componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
+ ResourceVersionInfo.newBuilder().state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build());
+ throw new ByResponseFormatComponentException(response);
+ }
+
+ public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction,
+ CsarInfo csarInfo) {
+ validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
+ validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
+ validateLifecycleTypesCreate(user, resource, actionEnum);
+ validateResourceType(user, resource, actionEnum);
+ resource.setCreatorUserId(user.getUserId());
+ resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
+ resource.setContactId(resource.getContactId().toLowerCase());
+ if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
+ String resourceSystemName;
+ if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
+ resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
+ } else {
+ resourceSystemName = resource.getSystemName();
+ }
+ resource
+ .setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
+ }
+ // Generate invariant UUID - must be here and not in operation since it
+
+ // should stay constant during clone
+
+ // TODO
+ String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
+ resource.setInvariantUUID(invariantUUID);
+ return resource;
+ }
+
+ private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource, AuditingActionEnum actionEnum) {
+ Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
+ if (resource.getResourceType() == null) {
+ log.debug("Invalid resource type for resource");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ eitherResult = Either.right(errorResponse);
+ componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+ }
+ return eitherResult;
+ }
+
+ private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource, AuditingActionEnum actionEnum) {
+ Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
+ if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
+ log.debug("validate interface lifecycle Types Exist");
+ Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
+ while (intItr.hasNext() && eitherResult.isLeft()) {
+ InterfaceDefinition interfaceDefinition = intItr.next();
+ String intType = interfaceDefinition.getUniqueId();
+ Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation.getInterface(intType);
+ if (eitherCapTypeFound.isRight()) {
+ if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
+ BeEcompErrorManager.getInstance()
+ .logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType);
+ log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", intType, resource.getName());
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
+ log.debug("request to data model failed with error: {}", eitherCapTypeFound.right().value().name());
+ }
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
+ eitherResult = Either.right(errorResponse);
+ componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+ }
+ }
+ }
+ return eitherResult;
+ }
+
+ private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user, ICapabilityTypeOperation capabilityTypeOperation,
+ Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
+ Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
+ if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
+ log.debug("validate capability Types Exist - capabilities section");
+ for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
+ eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry,
+ inTransaction);
+ if (eitherResult.isRight()) {
+ return Either.right(eitherResult.right().value());
+ }
+ }
+ }
+ if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
+ log.debug("validate capability Types Exist - requirements section");
+ for (String type : resource.getRequirements().keySet()) {
+ eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type), actionEnum,
+ eitherResult, type, inTransaction);
+ if (eitherResult.isRight()) {
+ return Either.right(eitherResult.right().value());
+ }
+ }
+ }
+ return eitherResult;
+ }
+
+ // @param typeObject- the object to which the validation is done
+ private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation,
+ Resource resource, List<?> validationObjects, AuditingActionEnum actionEnum,
+ Either<Boolean, ResponseFormat> eitherResult, String type,
+ boolean inTransaction) {
+ Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(type, inTransaction);
+ if (eitherCapTypeFound.isRight()) {
+ if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
+ BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
+ log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, resource.getName());
+ BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
+ }
+ log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right().value().name());
+ ResponseFormat errorResponse = null;
+ if (type != null) {
+ errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
+ } else {
+ errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, validationObjects);
+ }
+ eitherResult = Either.right(errorResponse);
+ componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+ }
+ return eitherResult;
+ }
+
+ private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation,
+ Resource resource, AuditingActionEnum actionEnum,
+ Either<Boolean, ResponseFormat> eitherResult,
+ Entry<String, List<CapabilityDefinition>> typeEntry, boolean inTransaction) {
+ Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
+ .getCapabilityType(typeEntry.getKey(), inTransaction);
+ if (eitherCapTypeFound.isRight()) {
+ if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
+ BeEcompErrorManager.getInstance()
+ .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
+ log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName());
+ BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
+ }
+ log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), eitherCapTypeFound.right().value().name());
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, typeEntry.getKey());
+ componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+ return Either.right(errorResponse);
+ }
+ CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
+ if (capabilityTypeDefinition.getProperties() != null) {
+ for (CapabilityDefinition capDef : typeEntry.getValue()) {
+ List<ComponentInstanceProperty> properties = capDef.getProperties();
+ List<ComponentInstanceProperty> changedProperties = new ArrayList<>();
+ if (properties == null || properties.isEmpty()) {
+ for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
+ ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
+ changedProperties.add(newProp);
+ }
+ } else {
+ List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
+ for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
+ PropertyDefinition propFromDef = prop.getValue();
+ boolean propFound = false;
+ for (ComponentInstanceProperty cip : properties) {
+ if (propFromDef.getName().equals(cip.getName())) {
+ //merge property value and property description only, ignore other fields
+ if (cip.getDescription() != null && !cip.getDescription().equals(propFromDef.getDescription())) {
+ propFromDef.setDescription(cip.getDescription());
+ }
+ propertyDataValueMergeBusinessLogic.mergePropertyValue(propFromDef, cip, new ArrayList<>());
+ if (cip.getValue() != null) {
+ propFromDef.setValue(cip.getValue());
+ }
+ propsToAdd.add(new ComponentInstanceProperty(propFromDef));
+ propFound = true;
+ properties.remove(cip);
+ break;
+ }
+ }
+ if (!propFound) {
+ propsToAdd.add(new ComponentInstanceProperty(propFromDef));
+ }
+ }
+ if (!propsToAdd.isEmpty()) {
+ changedProperties.addAll(propsToAdd);
+ }
+ }
+ capDef.setProperties(changedProperties);
+ }
+ }
+ return eitherResult;
+ }
+
+ public Resource createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction) {
+ // create resource
+
+ // lock new resource name in order to avoid creation resource with same
+
+ // name
+ Resource createdResource = null;
+ if (!inTransaction) {
+ Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, CREATE_RESOURCE);
+ if (lockResult.isRight()) {
+ ResponseFormat responseFormat = lockResult.right().value();
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ throw new ByResponseFormatComponentException(responseFormat);
+ }
+ log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
+ }
+ try {
+ if (resource.deriveFromGeneric()) {
+ handleResourceGenericType(resource);
+ }
+ createdResource = createResourceTransaction(resource, user, isNormative);
+ componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user, createdResource, actionEnum);
+ ASDCKpiApi.countCreatedResourcesKPI();
+ } catch (ComponentException e) {
+ ResponseFormat responseFormat =
+ e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ throw e;
+ } catch (StorageException e) {
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ throw e;
+ } finally {
if (!inTransaction) {
- graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
- NodeTypeEnum.Resource);
- }
- }
- return createdResource;
- }
-
- private Resource createResourceTransaction(Resource resource, User user, boolean isNormative) {
- // validate resource name uniqueness
- log.debug("validate resource name");
- Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
- resource.getName(), resource.getResourceType(), resource.getComponentType());
- if (eitherValidation.isRight()) {
- loggerSupportability.log(LoggerSupportabilityActions.VALIDATE_NAME,resource.getComponentMetadataForSupportLog(),
- StatusCode.ERROR,"ERROR while validate component name {} Status is: {}",resource.getName(),eitherValidation.right().value());
- log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(),
- eitherValidation.right()
- .value());
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherValidation.right()
- .value()));
- }
- if (eitherValidation.left()
- .value()) {
- log.debug("resource with name: {}, already exists", resource.getName());
- loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
- StatusCode.ERROR,"resource with name: {} already exists",resource.getName());
- throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
- ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
- }
-
- log.debug("send resource {} to dao for create", resource.getName());
-
- createArtifactsPlaceHolderData(resource, user);
- // enrich object
- if (!isNormative) {
- log.debug("enrich resource with creator, version and state");
- resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- resource.setVersion(INITIAL_VERSION);
- resource.setHighestVersion(true);
- if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) {
- resource.setAbstract(false);
- }
- }
- return toscaOperationFacade.createToscaComponent(resource)
- .left()
- .on(r -> throwComponentExceptionByResource(r, resource));
- }
-
- private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource);
- throw new ByResponseFormatComponentException(responseFormat);
- }
-
- private void createArtifactsPlaceHolderData(Resource resource, User user) {
- // create mandatory artifacts
-
- // TODO it must be removed after that artifact uniqueId creation will be
- // moved to ArtifactOperation
-
- setInformationalArtifactsPlaceHolder(resource, user);
- setDeploymentArtifactsPlaceHolder(resource, user);
- setToscaArtifactsPlaceHolders(resource, user);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
- Resource resource = (Resource) component;
- Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
- if (artifactMap == null) {
- artifactMap = new HashMap<>();
- }
- Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
- .getConfiguration()
- .getDeploymentResourceArtifacts();
- if (deploymentResourceArtifacts != null) {
- Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
- deploymentResourceArtifacts
- .forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v));
- }
- resource.setDeploymentArtifacts(artifactMap);
- }
-
- private void processDeploymentResourceArtifacts(User user, Resource resource,
- Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
- Map<String, Object> artifactDetails = (Map<String, Object>) v;
- Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
- if (object != null) {
- List<String> artifactTypes = (List<String>) object;
- if (!artifactTypes.contains(resource.getResourceType()
- .name())) {
- return;
- }
- } else {
- log.info("resource types for artifact placeholder {} were not defined. default is all resources", k);
- }
- if (artifactsBusinessLogic != null) {
- ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
- resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
- if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
- artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
- }
- }
- }
-
- @SuppressWarnings("unchecked")
- private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
- Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
- if (artifactMap == null) {
- artifactMap = new HashMap<>();
- }
- String resourceUniqueId = resource.getUniqueId();
- List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager()
- .getConfiguration()
- .getExcludeResourceCategory();
- List<String> exludeResourceType = ConfigurationManager.getConfigurationManager()
- .getConfiguration()
- .getExcludeResourceType();
- Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
- .getConfiguration()
- .getInformationalResourceArtifacts();
- List<CategoryDefinition> categories = resource.getCategories();
- boolean isCreateArtifact = true;
- if (exludeResourceCategory != null) {
- String category = categories.get(0)
- .getName();
- isCreateArtifact = exludeResourceCategory.stream()
- .noneMatch(e -> e.equalsIgnoreCase(category));
- }
- if (isCreateArtifact && exludeResourceType != null) {
- String resourceType = resource.getResourceType()
- .name();
- isCreateArtifact = exludeResourceType.stream()
- .noneMatch(e -> e.equalsIgnoreCase(resourceType));
- }
- if (informationalResourceArtifacts != null && isCreateArtifact) {
- Set<String> keys = informationalResourceArtifacts.keySet();
- for (String informationalResourceArtifactName : keys) {
- Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
- .get(informationalResourceArtifactName);
- ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
- resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
- ArtifactGroupTypeEnum.INFORMATIONAL);
- artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
-
- }
- }
- resource.setArtifacts(artifactMap);
- }
-
- /**
- * deleteResource
- *
- * @param resourceId
- * @param user
- * @return
- */
- public ResponseFormat deleteResource(String resourceId, User user) {
- ResponseFormat responseFormat;
- validateUserExists(user);
-
- Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
- if (resourceStatus.isRight()) {
- log.debug("failed to get resource {}", resourceId);
- return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right()
- .value()), "");
- }
-
- Resource resource = resourceStatus.left()
- .value();
-
- StorageOperationStatus result = StorageOperationStatus.OK;
- lockComponent(resourceId, resource, "Mark resource to delete");
- try {
-
- result = markComponentToDelete(resource);
- if (result == StorageOperationStatus.OK) {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
- } else {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
- responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
- }
- return responseFormat;
-
- } finally {
- if (result == null || result != StorageOperationStatus.OK) {
- janusGraphDao.rollback();
- } else {
+ graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
+ }
+ }
+ return createdResource;
+ }
+
+ private Resource createResourceTransaction(Resource resource, User user, boolean isNormative) {
+ // validate resource name uniqueness
+ log.debug("validate resource name");
+ Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade
+ .validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
+ if (eitherValidation.isRight()) {
+ loggerSupportability.log(LoggerSupportabilityActions.VALIDATE_NAME, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "ERROR while validate component name {} Status is: {}", resource.getName(), eitherValidation.right().value());
+ log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(), eitherValidation.right().value());
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
+ }
+ if (eitherValidation.left().value()) {
+ log.debug("resource with name: {}, already exists", resource.getName());
+ loggerSupportability
+ .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "resource with name: {} already exists", resource.getName());
+ throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(),
+ resource.getName());
+ }
+ log.debug("send resource {} to dao for create", resource.getName());
+ createArtifactsPlaceHolderData(resource, user);
+ // enrich object
+ if (!isNormative) {
+ log.debug("enrich resource with creator, version and state");
+ resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ resource.setVersion(INITIAL_VERSION);
+ resource.setHighestVersion(true);
+ if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) {
+ resource.setAbstract(false);
+ }
+ }
+ return toscaOperationFacade.createToscaComponent(resource).left().on(r -> throwComponentExceptionByResource(r, resource));
+ }
+
+ private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource);
+ throw new ByResponseFormatComponentException(responseFormat);
+ }
+
+ private void createArtifactsPlaceHolderData(Resource resource, User user) {
+ // create mandatory artifacts
+
+ // TODO it must be removed after that artifact uniqueId creation will be
+
+ // moved to ArtifactOperation
+ setInformationalArtifactsPlaceHolder(resource, user);
+ setDeploymentArtifactsPlaceHolder(resource, user);
+ setToscaArtifactsPlaceHolders(resource, user);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
+ Resource resource = (Resource) component;
+ Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
+ if (artifactMap == null) {
+ artifactMap = new HashMap<>();
+ }
+ Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getDeploymentResourceArtifacts();
+ if (deploymentResourceArtifacts != null) {
+ Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
+ deploymentResourceArtifacts.forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v));
+ }
+ resource.setDeploymentArtifacts(artifactMap);
+ }
+
+ private void processDeploymentResourceArtifacts(User user, Resource resource, Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
+ Map<String, Object> artifactDetails = (Map<String, Object>) v;
+ Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
+ if (object != null) {
+ List<String> artifactTypes = (List<String>) object;
+ if (!artifactTypes.contains(resource.getResourceType().name())) {
+ return;
+ }
+ } else {
+ log.info("resource types for artifact placeholder {} were not defined. default is all resources", k);
+ }
+ if (artifactsBusinessLogic != null) {
+ ArtifactDefinition artifactDefinition = artifactsBusinessLogic
+ .createArtifactPlaceHolderInfo(resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
+ if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
+ artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
+ Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
+ if (artifactMap == null) {
+ artifactMap = new HashMap<>();
+ }
+ String resourceUniqueId = resource.getUniqueId();
+ List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
+ List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
+ Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getInformationalResourceArtifacts();
+ List<CategoryDefinition> categories = resource.getCategories();
+ boolean isCreateArtifact = true;
+ if (exludeResourceCategory != null) {
+ String category = categories.get(0).getName();
+ isCreateArtifact = exludeResourceCategory.stream().noneMatch(e -> e.equalsIgnoreCase(category));
+ }
+ if (isCreateArtifact && exludeResourceType != null) {
+ String resourceType = resource.getResourceType().name();
+ isCreateArtifact = exludeResourceType.stream().noneMatch(e -> e.equalsIgnoreCase(resourceType));
+ }
+ if (informationalResourceArtifacts != null && isCreateArtifact) {
+ Set<String> keys = informationalResourceArtifacts.keySet();
+ for (String informationalResourceArtifactName : keys) {
+ Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
+ ArtifactDefinition artifactDefinition = artifactsBusinessLogic
+ .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
+ ArtifactGroupTypeEnum.INFORMATIONAL);
+ artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
+ }
+ }
+ resource.setArtifacts(artifactMap);
+ }
+
+ /**
+ * deleteResource
+ *
+ * @param resourceId
+ * @param user
+ * @return
+ */
+ public ResponseFormat deleteResource(String resourceId, User user) {
+ ResponseFormat responseFormat;
+ validateUserExists(user);
+ Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
+ if (resourceStatus.isRight()) {
+ log.debug("failed to get resource {}", resourceId);
+ return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), "");
+ }
+ Resource resource = resourceStatus.left().value();
+ StorageOperationStatus result = StorageOperationStatus.OK;
+ lockComponent(resourceId, resource, "Mark resource to delete");
+ try {
+ result = markComponentToDelete(resource);
+ if (result == StorageOperationStatus.OK) {
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
+ } else {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
+ responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
+ }
+ return responseFormat;
+ } finally {
+ if (result == null || result != StorageOperationStatus.OK) {
+ janusGraphDao.rollback();
+ } else {
janusGraphDao.commit();
- }
- graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
- }
-
- }
-
- public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
- validateUserExists(user);
- Resource resource = null;
- StorageOperationStatus result = StorageOperationStatus.OK;
- boolean failed = false;
- try {
-
- Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade
- .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
- if (resourceStatus.isRight()) {
- log.debug("failed to get resource {} version {}", resourceName, version);
- return componentsUtils
- .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right()
- .value()), resourceName);
- }
-
- resource = resourceStatus.left()
- .value();
-
- } finally {
- janusGraphDao.commit();
- }
- if (resource != null) {
- lockComponent(resource.getUniqueId(), resource, DELETE_RESOURCE);
- try {
- result = markComponentToDelete(resource);
- if (result != StorageOperationStatus.OK) {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
- responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
- return responseFormat;
- }
- }catch (ComponentException e){
- failed = true;
- throw e;
- }finally {
- if (failed || result == null || result != StorageOperationStatus.OK) {
- janusGraphDao.rollback();
- } else {
+ }
+ graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
+ }
+ }
+
+ public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
+ validateUserExists(user);
+ Resource resource = null;
+ StorageOperationStatus result = StorageOperationStatus.OK;
+ boolean failed = false;
+ try {
+ Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade
+ .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
+ if (resourceStatus.isRight()) {
+ log.debug("failed to get resource {} version {}", resourceName, version);
+ return componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName);
+ }
+ resource = resourceStatus.left().value();
+ } finally {
+ janusGraphDao.commit();
+ }
+ if (resource != null) {
+ lockComponent(resource.getUniqueId(), resource, DELETE_RESOURCE);
+ try {
+ result = markComponentToDelete(resource);
+ if (result != StorageOperationStatus.OK) {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
+ responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
+ return responseFormat;
+ }
+ } catch (ComponentException e) {
+ failed = true;
+ throw e;
+ } finally {
+ if (failed || result == null || result != StorageOperationStatus.OK) {
+ janusGraphDao.rollback();
+ } else {
janusGraphDao.commit();
- }
- graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
- }
- }
- return responseFormat;
- }
-
- public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
-
- if (user != null) {
- validateUserExists(user);
- }
-
- Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
- if (storageStatus.isRight()) {
- log.debug("failed to get resource by id {}", resourceId);
- return Either.right(componentsUtils
- .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right()
- .value()), resourceId));
- }
- if (!(storageStatus.left()
- .value() instanceof Resource)) {
- return Either.right(componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
- }
- return Either.left(storageStatus.left()
- .value());
-
- }
-
- public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion,
- String userId) {
-
- validateUserExists(userId);
-
- Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
- .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
- if (getResource.isRight()) {
- log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
- return Either.right(componentsUtils
- .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right()
- .value()), resourceName));
- }
- return Either.left(getResource.left()
- .value());
- }
-
- /**
- * updateResourceMetadata
- *
- * @param user
- * - modifier data (userId)
- * @param inTransaction
- * TODO
- * @param resourceIdToUpdate
- * - the resource identifier
- * @param newResource
- * @return Either<Resource , responseFormat>
- */
- public Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource,
- User user, boolean inTransaction) {
-
- validateUserExists(user.getUserId());
-
- log.debug("Get resource with id {}", resourceIdToUpdate);
- boolean needToUnlock = false;
-
- try {
- if (currentResource == null) {
- Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade
- .getToscaElement(resourceIdToUpdate);
- if (storageStatus.isRight()) {
- throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(storageStatus.right()
- .value()),
- ""));
- }
-
- currentResource = storageStatus.left()
- .value();
- }
- // verify that resource is checked-out and the user is the last
- // updater
- if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
- throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- }
-
- // lock resource
- StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate,
- NodeTypeEnum.Resource);
- if (lockResult != StorageOperationStatus.OK) {
- BeEcompErrorManager.getInstance()
- .logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(),
- resourceIdToUpdate);
- log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
- throw new ByResponseFormatComponentException(responseFormat);
- }
-
- needToUnlock = true;
-
- // critical section starts here
- // convert json to object
-
- // Update and updated resource must have a non-empty "derivedFrom"
- // list
- // This code is not called from import resources, because of root
- // VF "derivedFrom" should be null (or ignored)
- if (ModelConverter.isAtomicComponent(currentResource)) {
- validateDerivedFromNotEmpty(null, newResource, null);
- validateDerivedFromNotEmpty(null, currentResource, null);
- } else {
- newResource.setDerivedFrom(null);
- }
-
- Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource,
- user, currentResource, false, true);
+ }
+ graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
+ }
+ }
+ return responseFormat;
+ }
+
+ public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
+ if (user != null) {
+ validateUserExists(user);
+ }
+ Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
+ if (storageStatus.isRight()) {
+ log.debug("failed to get resource by id {}", resourceId);
+ return Either.right(
+ componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId));
+ }
+ if (!(storageStatus.left().value() instanceof Resource)) {
+ return Either.right(componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
+ }
+ return Either.left(storageStatus.left().value());
+ }
+
+ public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion, String userId) {
+ validateUserExists(userId);
+ Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
+ .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
+ if (getResource.isRight()) {
+ log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
+ return Either.right(
+ componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName));
+ }
+ return Either.left(getResource.left().value());
+ }
+
+ /**
+ * updateResourceMetadata
+ *
+ * @param user - modifier data (userId)
+ * @param inTransaction TODO
+ * @param resourceIdToUpdate - the resource identifier
+ * @param newResource
+ * @return Either<Resource, responseFormat>
+ */
+ public Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource, User user,
+ boolean inTransaction) {
+ validateUserExists(user.getUserId());
+ log.debug("Get resource with id {}", resourceIdToUpdate);
+ boolean needToUnlock = false;
+ try {
+ if (currentResource == null) {
+ Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceIdToUpdate);
+ if (storageStatus.isRight()) {
+ throw new ByResponseFormatComponentException(
+ componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
+ }
+ currentResource = storageStatus.left().value();
+ }
+ // verify that resource is checked-out and the user is the last
+
+ // updater
+ if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
+ throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ }
+ // lock resource
+ StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
+ if (lockResult != StorageOperationStatus.OK) {
+ BeEcompErrorManager.getInstance()
+ .logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
+ log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
+ throw new ByResponseFormatComponentException(responseFormat);
+ }
+ needToUnlock = true;
+ // critical section starts here
+
+ // convert json to object
+
+ // Update and updated resource must have a non-empty "derivedFrom"
+
+ // list
+
+ // This code is not called from import resources, because of root
+
+ // VF "derivedFrom" should be null (or ignored)
+ if (ModelConverter.isAtomicComponent(currentResource)) {
+ validateDerivedFromNotEmpty(null, newResource, null);
+ validateDerivedFromNotEmpty(null, currentResource, null);
+ } else {
+ newResource.setDerivedFrom(null);
+ }
+ Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource, user, currentResource, false,
+ true);
if (dataModelResponse.isRight()) {
log.debug("failed to update resource metadata!!!");
throw new ByResponseFormatComponentException(dataModelResponse.right().value());
}
+ log.debug("Resource metadata updated successfully!!!");
+ return dataModelResponse.left().value();
+ } catch (ComponentException | StorageException e) {
+ rollback(inTransaction, newResource, null, null);
+ throw e;
+ } finally {
+ if (!inTransaction) {
+ janusGraphDao.commit();
+ }
+ if (needToUnlock) {
+ graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
+ }
+ }
+ }
+
+ private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, User user,
+ Resource currentResource, boolean shouldLock, boolean inTransaction) {
+ updateVfModuleGroupsNames(currentResource, newResource);
+ validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false);
+ // Setting last updater and uniqueId
+ newResource.setContactId(newResource.getContactId().toLowerCase());
+ newResource.setLastUpdaterUserId(user.getUserId());
+ newResource.setUniqueId(resourceIdToUpdate);
+ // Cannot set highest version through UI
+ newResource.setHighestVersion(currentResource.isHighestVersion());
+ newResource.setCreationDate(currentResource.getCreationDate());
+ Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource, newResource, user.getUserId(),
+ inTransaction);
+ if (processUpdateOfDerivedFrom.isRight()) {
+ log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
+ return Either.right(processUpdateOfDerivedFrom.right().value());
+ }
+ log.debug("send resource {} to dao for update", newResource.getUniqueId());
+ if (isNotEmpty(newResource.getGroups())) {
+ for (GroupDefinition group : newResource.getGroups()) {
+ if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
+ groupBusinessLogic
+ .validateAndUpdateGroupMetadata(newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId(), user,
+ newResource.getComponentType(), group, true, false);
+ }
+ }
+ }
+ Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade.updateToscaElement(newResource);
+ if (dataModelResponse.isRight()) {
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
+ return Either.right(responseFormat);
+ } else if (dataModelResponse.left().value() == null) {
+ log.debug("No response from updateResource");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ return Either.left(dataModelResponse.left().value());
+ }
- log.debug("Resource metadata updated successfully!!!");
- return dataModelResponse.left()
- .value();
+ private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) {
+ if (currentResource.getGroups() != null && !currentResource.getName().equals(newResource.getName())) {
+ List<GroupDefinition> updatedGroups = currentResource.getGroups().stream()
+ .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName())).collect(toList());
+ newResource.setGroups(updatedGroups);
+ }
+ }
- } catch (ComponentException | StorageException e) {
- rollback(inTransaction, newResource, null, null);
- throw e;
- } finally {
- if (!inTransaction) {
- janusGraphDao.commit();
- }
- if (needToUnlock) {
- graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
- }
- }
- }
-
- private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
- User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
- updateVfModuleGroupsNames(currentResource, newResource);
- validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false);
- // Setting last updater and uniqueId
- newResource.setContactId(newResource.getContactId()
- .toLowerCase());
- newResource.setLastUpdaterUserId(user.getUserId());
- newResource.setUniqueId(resourceIdToUpdate);
- // Cannot set highest version through UI
- newResource.setHighestVersion(currentResource.isHighestVersion());
- newResource.setCreationDate(currentResource.getCreationDate());
-
- Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource,
- newResource, user.getUserId(), inTransaction);
-
- if (processUpdateOfDerivedFrom.isRight()) {
- log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
- return Either.right(processUpdateOfDerivedFrom.right()
- .value());
- }
-
- log.debug("send resource {} to dao for update", newResource.getUniqueId());
- if (isNotEmpty(newResource.getGroups())) {
- for (GroupDefinition group : newResource.getGroups()) {
- if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
- groupBusinessLogic.validateAndUpdateGroupMetadata(newResource.getComponentMetadataDefinition()
- .getMetadataDataDefinition()
- .getUniqueId(), user, newResource.getComponentType(), group, true, false);
- }
- }
- }
- Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade
- .updateToscaElement(newResource);
-
- if (dataModelResponse.isRight()) {
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right()
- .value()), newResource);
- return Either.right(responseFormat);
- } else if (dataModelResponse.left()
- .value() == null) {
- log.debug("No response from updateResource");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- return Either.left(dataModelResponse.left()
- .value());
- }
-
- private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) {
- if (currentResource.getGroups() != null && !currentResource.getName()
- .equals(newResource.getName())) {
- List<GroupDefinition> updatedGroups = currentResource.getGroups()
- .stream()
- .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName()))
- .collect(toList());
- newResource.setGroups(updatedGroups);
- }
- }
-
- private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) {
- GroupDefinition updatedGroup = new GroupDefinition(currGroup);
- if (updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType()
- .equals(DEFAULT_GROUP_VF_MODULE)) {
- String prefix = updatedGroup.getName()
- .substring(0, replacePattern.length());
- String newGroupName = updatedGroup.getName()
- .replaceFirst(prefix, with);
- updatedGroup.setName(newGroupName);
- }
- return updatedGroup;
- }
-
- /**
- * validateResourceFieldsBeforeCreate
- *
- * @param user
- * - modifier data (userId)
- */
- private void validateResourceFieldsBeforeCreate(User user, Resource resource,
- AuditingActionEnum actionEnum, boolean inTransaction) {
- componentValidator.validate(user, resource, actionEnum);
- // validate category
- log.debug("validate category");
- validateCategory(user, resource, actionEnum, inTransaction);
- // validate vendor name & release & model number
- log.debug("validate vendor name");
- validateVendorName(user, resource, actionEnum);
- log.debug("validate vendor release");
- validateVendorReleaseName(user, resource, actionEnum);
- log.debug("validate resource vendor model number");
- validateResourceVendorModelNumber(user, resource, actionEnum);
- // validate cost
- log.debug("validate cost");
- validateCost(resource);
- // validate licenseType
- log.debug("validate licenseType");
- validateLicenseType(user, resource, actionEnum);
- // validate template (derived from)
- log.debug("validate derived from");
- if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
- resource.setDerivedFrom(null);
- }
- validateDerivedFromExist(user, resource, actionEnum);
- // warn about non-updatable fields
- checkComponentFieldsForOverrideAttempt(resource);
- String currentCreatorFullName = resource.getCreatorFullName();
- if (currentCreatorFullName != null) {
- log.debug("Resource Creator fullname is automatically set and cannot be updated");
- }
-
- String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
- if (currentLastUpdaterFullName != null) {
- log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
- }
-
- Long currentLastUpdateDate = resource.getLastUpdateDate();
- if (currentLastUpdateDate != null) {
- log.debug("Resource last update date is automatically set and cannot be updated");
- }
-
- Boolean currentAbstract = resource.isAbstract();
- if (currentAbstract != null) {
- log.debug("Resource abstract is automatically set and cannot be updated");
- }
- }
-
- /**
- * validateResourceFieldsBeforeUpdate
- *
- * @param currentResource
- * - Resource object to validate
- * @param isNested
- */
- private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource,
- boolean inTransaction, boolean isNested) {
- validateFields(currentResource, updateInfoResource, inTransaction, isNested);
- warnNonEditableFields(currentResource, updateInfoResource);
- }
-
- private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) {
- String currentResourceVersion = currentResource.getVersion();
- String updatedResourceVersion = updateInfoResource.getVersion();
-
- if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
- log.debug("Resource version is automatically set and cannot be updated");
- }
-
- String currentCreatorUserId = currentResource.getCreatorUserId();
- String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
-
- if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
- log.debug("Resource Creator UserId is automatically set and cannot be updated");
- }
-
- String currentCreatorFullName = currentResource.getCreatorFullName();
- String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
-
- if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
- log.debug("Resource Creator fullname is automatically set and cannot be updated");
- }
-
- String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
- String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
-
- if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
- log.debug("Resource LastUpdater userId is automatically set and cannot be updated");
- }
-
- String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
- String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
-
- if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
- log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
- }
- Long currentCreationDate = currentResource.getCreationDate();
- Long updatedCreationDate = updateInfoResource.getCreationDate();
-
- if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
- log.debug("Resource Creation date is automatically set and cannot be updated");
- }
-
- Long currentLastUpdateDate = currentResource.getLastUpdateDate();
- Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
-
- if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
- log.debug("Resource last update date is automatically set and cannot be updated");
- }
-
- LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
- LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
-
- if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
- log.debug("Resource lifecycle state date is automatically set and cannot be updated");
- }
-
- Boolean currentAbstract = currentResource.isAbstract();
- Boolean updatedAbstract = updateInfoResource.isAbstract();
-
- if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
- log.debug("Resource abstract is automatically set and cannot be updated");
- }
-
- Boolean currentHighestVersion = currentResource.isHighestVersion();
- Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
-
- if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
- log.debug("Resource highest version is automatically set and cannot be updated");
- }
-
- String currentUuid = currentResource.getUUID();
- String updatedUuid = updateInfoResource.getUUID();
-
- if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
- log.debug("Resource UUID is automatically set and cannot be updated");
- }
-
- log.debug("Resource Type cannot be updated");
- String currentInvariantUuid = currentResource.getInvariantUUID();
- String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
-
- if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
- log.debug("Resource invariant UUID is automatically set and cannot be updated");
- updateInfoResource.setInvariantUUID(currentInvariantUuid);
- }
- }
-
- private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction,
- boolean isNested) {
- boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
- log.debug("validate resource name before update");
- validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
- log.debug("validate description before update");
- componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null);
- log.debug("validate icon before update");
- validateIcon(currentResource, updateInfoResource, hasBeenCertified);
- log.debug("validate tags before update");
- componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null);
- log.debug("validate vendor name before update");
- validateVendorName(null, updateInfoResource, null);
- log.debug("validate resource vendor model number before update");
- validateResourceVendorModelNumber(currentResource, updateInfoResource);
- log.debug("validate vendor release before update");
- validateVendorReleaseName(null, updateInfoResource, null);
- log.debug("validate contact info before update");
- componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null);
- log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
- validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
- log.debug("validate category before update");
- validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
- }
-
- private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
- String resourceNameUpdated = updateInfoResource.getName();
- String resourceNameCurrent = currentResource.getName();
- if (resourceNameCurrent.equals(resourceNameUpdated)) {
- return true;
- }
- // In case of CVFC type we should support the case of old VF with CVFC
- // instances that were created without the "Cvfc" suffix
- return currentResource.getResourceType() == ResourceTypeEnum.CVFC
- && resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
- }
-
- private String addCvfcSuffixToResourceName(String resourceName) {
- return resourceName + "Cvfc";
- }
-
- private void validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified,
- boolean isNested) {
- String resourceNameUpdated = updateInfoResource.getName();
- if (!isResourceNameEquals(currentResource, updateInfoResource)) {
- if (isNested || !hasBeenCertified) {
- componentNameValidator.validateAndCorrectField(null, updateInfoResource, null);
- validateResourceNameUniqueness(updateInfoResource);
- currentResource.setName(resourceNameUpdated);
- currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
- currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
-
- } else {
- log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
- resourceNameUpdated);
- throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
- }
- }
- }
-
- private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
- String iconUpdated = updateInfoResource.getIcon();
- String iconCurrent = currentResource.getIcon();
- if (!iconCurrent.equals(iconUpdated)) {
- if (!hasBeenCertified) {
- componentIconValidator.validateAndCorrectField(null, updateInfoResource, null);
- } else {
- log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
- throw new ByActionStatusComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
- }
- }
- }
-
- private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
- String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
- String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
- if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
- validateResourceVendorModelNumber(null, updateInfoResource, null);
- }
- }
-
- private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource,
- boolean hasBeenCertified, boolean inTransaction) {
- validateCategory(null, updateInfoResource, null, inTransaction);
- if (hasBeenCertified) {
- CategoryDefinition currentCategory = currentResource.getCategories()
- .get(0);
- SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories()
- .get(0);
- CategoryDefinition updateCategory = updateInfoResource.getCategories()
- .get(0);
- SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories()
- .get(0);
- if (!currentCategory.getName()
- .equals(updateCategory.getName())
- || !currentSubCategory.getName()
- .equals(updtaeSubCategory.getName())) {
- log.info("Category {} cannot be updated once the resource has been certified once.",
- currentResource.getCategories());
- ResponseFormat errorResponse = componentsUtils
- .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
- return Either.right(errorResponse);
- }
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource,
- Resource updateInfoResource, boolean hasBeenCertified) {
-
- List<String> currentDerivedFrom = currentResource.getDerivedFrom();
- List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
- if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
- || updatedDerivedFrom.isEmpty()) {
- log.trace("Update normative types");
- return Either.left(true);
- }
-
- String derivedFromCurrent = currentDerivedFrom.get(0);
- String derivedFromUpdated = updatedDerivedFrom.get(0);
-
- if (!derivedFromCurrent.equals(derivedFromUpdated)) {
- if (!hasBeenCertified) {
- validateDerivedFromExist(null, updateInfoResource, null);
- } else {
- Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
- currentResource, updateInfoResource, null);
-
- if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left()
- .value()) {
- log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
- return validateDerivedFromExtending;
- }
- }
- } else {
- // For derived from, we must know whether it was actually changed,
- // otherwise we must do no action.
- // Due to changes it inflicts on data model (remove artifacts,
- // properties...), it's not like a flat field which can be
- // overwritten if not changed.
- // So we must indicate that derived from is not changed
- updateInfoResource.setDerivedFrom(null);
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
- Resource updateInfoResource, boolean hasBeenCertified) {
-
- List<String> currentDerivedFrom = currentResource.getDerivedFrom();
- List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
- if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
- || updatedDerivedFrom.isEmpty()) {
- log.trace("Update normative types");
- return Either.left(true);
- }
-
- String derivedFromCurrent = currentDerivedFrom.get(0);
- String derivedFromUpdated = updatedDerivedFrom.get(0);
-
- if (!derivedFromCurrent.equals(derivedFromUpdated)) {
- if (!hasBeenCertified) {
- validateDerivedFromExist(null, updateInfoResource, null);
- } else {
- Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
- currentResource, updateInfoResource, null);
-
- if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left()
- .value()) {
- log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
- return validateDerivedFromExtending;
- }
- }
- }
- return Either.left(true);
- }
-
- private void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
- if (resource.getDerivedFrom() == null || resource.getDerivedFrom()
- .isEmpty()) {
- return;
- }
- String templateName = resource.getDerivedFrom()
- .get(0);
- Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
- .validateToscaResourceNameExists(templateName);
- if (dataModelResponse.isRight()) {
- StorageOperationStatus storageStatus = dataModelResponse.right()
- .value();
- BeEcompErrorManager.getInstance()
- .logBeDaoSystemError("Create Resource - validateDerivedFromExist");
- log.debug("request to data model failed with error: {}", storageStatus);
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
- log.trace("audit before sending response");
- componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
- } else if (!dataModelResponse.left()
- .value()) {
- log.info("resource template with name: {}, does not exists", templateName);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
- componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
- throw new ByActionStatusComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
- }
- }
-
- // Tal G for extending inheritance US815447
- private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
- Resource updateInfoResource, AuditingActionEnum actionEnum) {
- String currentTemplateName = currentResource.getDerivedFrom()
- .get(0);
- String updatedTemplateName = updateInfoResource.getDerivedFrom()
- .get(0);
-
- Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
- .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
- if (dataModelResponse.isRight()) {
- StorageOperationStatus storageStatus = dataModelResponse.right()
- .value();
- BeEcompErrorManager.getInstance()
- .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
- log.trace("audit before sending response");
- componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
- return Either.right(responseFormat);
- }
-
- if (!dataModelResponse.left()
- .value()) {
- log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
- currentTemplateName);
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
- componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
-
- return Either.right(responseFormat);
-
- }
- return Either.left(true);
- }
-
- public void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
- log.debug("validate resource derivedFrom field");
- if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom()
- .isEmpty())
- || (resource.getDerivedFrom()
- .get(0)) == null
- || (resource.getDerivedFrom()
- .get(0)
- .trim()
- .isEmpty())) {
- log.info("derived from (template) field is missing for the resource");
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
- componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
-
- throw new ByActionStatusComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
- }
- }
-
- private void validateResourceNameUniqueness(Resource resource) {
-
- Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
- .validateComponentNameExists(resource.getName(), resource.getResourceType(),
- resource.getComponentType());
- if (resourceOperationResponse.isLeft() && resourceOperationResponse.left()
- .value()) {
- log.debug("resource with name: {}, already exists", resource.getName());
- throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
- ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
- } else if (resourceOperationResponse.isRight()) {
- log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
- throw new StorageException(resourceOperationResponse.right()
- .value());
- }
- }
-
- private void validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
-
- List<CategoryDefinition> categories = resource.getCategories();
- if (CollectionUtils.isEmpty(categories)) {
- log.debug(CATEGORY_IS_EMPTY);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
- ComponentTypeEnum.RESOURCE.getValue());
- componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
- throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
- ComponentTypeEnum.RESOURCE.getValue());
- }
- if (categories.size() > 1) {
- log.debug("Must be only one category for resource");
- throw new ByActionStatusComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES,
- ComponentTypeEnum.RESOURCE.getValue());
- }
- CategoryDefinition category = categories.get(0);
- List<SubCategoryDefinition> subcategories = category.getSubcategories();
- if (CollectionUtils.isEmpty(subcategories)) {
- log.debug("Missinig subcategory for resource");
- throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
- }
- if (subcategories.size() > 1) {
- log.debug("Must be only one sub category for resource");
- throw new ByActionStatusComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
- }
-
- SubCategoryDefinition subcategory = subcategories.get(0);
-
- if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
- log.debug(CATEGORY_IS_EMPTY);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
- ComponentTypeEnum.RESOURCE.getValue());
- componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
- throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
- ComponentTypeEnum.RESOURCE.getValue());
- }
- if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
- log.debug(CATEGORY_IS_EMPTY);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(
- ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
- componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
- throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY,
- ComponentTypeEnum.RESOURCE.getValue());
- }
-
- validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
- }
-
- private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, User user,
- Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
- ResponseFormat responseFormat;
- if (category != null && subcategory != null) {
- log.debug("validating resource category {} against valid categories list", category);
- Either<List<CategoryDefinition>, ActionStatus> categories = elementDao
- .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
- if (categories.isRight()) {
- log.debug("failed to retrieve resource categories from JanusGraph");
- responseFormat = componentsUtils.getResponseFormat(categories.right()
- .value());
- componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
- throw new ByActionStatusComponentException(categories.right()
- .value());
- }
- List<CategoryDefinition> categoryList = categories.left()
- .value();
- Optional<CategoryDefinition> foundCategory = categoryList.stream()
- .filter(cat -> cat.getName()
- .equals(category.getName()))
- .findFirst();
- if (!foundCategory.isPresent()) {
- log.debug("Category {} is not part of resource category group. Resource category valid values are {}",
- category, categoryList);
- failOnInvalidCategory(user, resource, actionEnum);
- }
- Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get()
- .getSubcategories()
- .stream()
- .filter(subcat -> subcat.getName()
- .equals(subcategory.getName()))
- .findFirst();
- if (!foundSubcategory.isPresent()) {
- log.debug(
- "SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
- subcategory, foundCategory.get()
- .getSubcategories());
- failOnInvalidCategory(user, resource, actionEnum);
- }
- }
- }
-
- private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
- ResponseFormat responseFormat;
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
- ComponentTypeEnum.RESOURCE.getValue());
- componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
- throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
- }
-
- public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
- String vendorRelease = resource.getVendorRelease();
- log.debug("validate vendor relese name");
- if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
- log.info("vendor relese name is missing.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
- componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
- throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
- }
-
- validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
- }
-
- public void validateVendorReleaseName(String vendorRelease, User user, Resource resource,
- AuditingActionEnum actionEnum) {
- if (vendorRelease != null) {
- if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
- log.info("vendor release exceds limit.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(
- ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
- componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
- throw new ByActionStatusComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT,
- "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
- }
-
- if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
- log.info("vendor release is not valid.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
- componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+ private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) {
+ GroupDefinition updatedGroup = new GroupDefinition(currGroup);
+ if (updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType().equals(DEFAULT_GROUP_VF_MODULE)) {
+ String prefix = updatedGroup.getName().substring(0, replacePattern.length());
+ String newGroupName = updatedGroup.getName().replaceFirst(prefix, with);
+ updatedGroup.setName(newGroupName);
+ }
+ return updatedGroup;
+ }
+
+ /**
+ * validateResourceFieldsBeforeCreate
+ *
+ * @param user - modifier data (userId)
+ */
+ private void validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
+ componentValidator.validate(user, resource, actionEnum);
+ // validate category
+ log.debug("validate category");
+ validateCategory(user, resource, actionEnum, inTransaction);
+ // validate vendor name & release & model number
+ log.debug("validate vendor name");
+ validateVendorName(user, resource, actionEnum);
+ log.debug("validate vendor release");
+ validateVendorReleaseName(user, resource, actionEnum);
+ log.debug("validate resource vendor model number");
+ validateResourceVendorModelNumber(user, resource, actionEnum);
+ // validate cost
+ log.debug("validate cost");
+ validateCost(resource);
+ // validate licenseType
+ log.debug("validate licenseType");
+ validateLicenseType(user, resource, actionEnum);
+ // validate template (derived from)
+ log.debug("validate derived from");
+ if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
+ resource.setDerivedFrom(null);
+ }
+ validateDerivedFromExist(user, resource, actionEnum);
+ // warn about non-updatable fields
+ checkComponentFieldsForOverrideAttempt(resource);
+ String currentCreatorFullName = resource.getCreatorFullName();
+ if (currentCreatorFullName != null) {
+ log.debug("Resource Creator fullname is automatically set and cannot be updated");
+ }
+ String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
+ if (currentLastUpdaterFullName != null) {
+ log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
+ }
+ Long currentLastUpdateDate = resource.getLastUpdateDate();
+ if (currentLastUpdateDate != null) {
+ log.debug("Resource last update date is automatically set and cannot be updated");
+ }
+ Boolean currentAbstract = resource.isAbstract();
+ if (currentAbstract != null) {
+ log.debug("Resource abstract is automatically set and cannot be updated");
+ }
+ }
+
+ /**
+ * validateResourceFieldsBeforeUpdate
+ *
+ * @param currentResource - Resource object to validate
+ * @param isNested
+ */
+ private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
+ validateFields(currentResource, updateInfoResource, inTransaction, isNested);
+ warnNonEditableFields(currentResource, updateInfoResource);
+ }
+
+ private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) {
+ String currentResourceVersion = currentResource.getVersion();
+ String updatedResourceVersion = updateInfoResource.getVersion();
+ if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
+ log.debug("Resource version is automatically set and cannot be updated");
+ }
+ String currentCreatorUserId = currentResource.getCreatorUserId();
+ String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
+ if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
+ log.debug("Resource Creator UserId is automatically set and cannot be updated");
+ }
+ String currentCreatorFullName = currentResource.getCreatorFullName();
+ String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
+ if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
+ log.debug("Resource Creator fullname is automatically set and cannot be updated");
+ }
+ String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
+ String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
+ if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
+ log.debug("Resource LastUpdater userId is automatically set and cannot be updated");
+ }
+ String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
+ String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
+ if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
+ log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
+ }
+ Long currentCreationDate = currentResource.getCreationDate();
+ Long updatedCreationDate = updateInfoResource.getCreationDate();
+ if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
+ log.debug("Resource Creation date is automatically set and cannot be updated");
+ }
+ Long currentLastUpdateDate = currentResource.getLastUpdateDate();
+ Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
+ if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
+ log.debug("Resource last update date is automatically set and cannot be updated");
+ }
+ LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
+ LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
+ if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
+ log.debug("Resource lifecycle state date is automatically set and cannot be updated");
+ }
+ Boolean currentAbstract = currentResource.isAbstract();
+ Boolean updatedAbstract = updateInfoResource.isAbstract();
+ if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
+ log.debug("Resource abstract is automatically set and cannot be updated");
+ }
+ Boolean currentHighestVersion = currentResource.isHighestVersion();
+ Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
+ if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
+ log.debug("Resource highest version is automatically set and cannot be updated");
+ }
+ String currentUuid = currentResource.getUUID();
+ String updatedUuid = updateInfoResource.getUUID();
+ if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
+ log.debug("Resource UUID is automatically set and cannot be updated");
+ }
+ log.debug("Resource Type cannot be updated");
+ String currentInvariantUuid = currentResource.getInvariantUUID();
+ String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
+ if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
+ log.debug("Resource invariant UUID is automatically set and cannot be updated");
+ updateInfoResource.setInvariantUUID(currentInvariantUuid);
+ }
+ }
+
+ private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
+ boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
+ log.debug("validate resource name before update");
+ validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
+ log.debug("validate description before update");
+ componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null);
+ log.debug("validate icon before update");
+ validateIcon(currentResource, updateInfoResource, hasBeenCertified);
+ log.debug("validate tags before update");
+ componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null);
+ log.debug("validate vendor name before update");
+ validateVendorName(null, updateInfoResource, null);
+ log.debug("validate resource vendor model number before update");
+ validateResourceVendorModelNumber(currentResource, updateInfoResource);
+ log.debug("validate vendor release before update");
+ validateVendorReleaseName(null, updateInfoResource, null);
+ log.debug("validate contact info before update");
+ componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null);
+ log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
+ validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
+ log.debug("validate category before update");
+ validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
+ }
+
+ private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
+ String resourceNameUpdated = updateInfoResource.getName();
+ String resourceNameCurrent = currentResource.getName();
+ if (resourceNameCurrent.equals(resourceNameUpdated)) {
+ return true;
+ }
+ // In case of CVFC type we should support the case of old VF with CVFC
+
+ // instances that were created without the "Cvfc" suffix
+ return currentResource.getResourceType() == ResourceTypeEnum.CVFC && resourceNameUpdated
+ .equals(addCvfcSuffixToResourceName(resourceNameCurrent));
+ }
+
+ private String addCvfcSuffixToResourceName(String resourceName) {
+ return resourceName + "Cvfc";
+ }
+
+ private void validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean isNested) {
+ String resourceNameUpdated = updateInfoResource.getName();
+ if (!isResourceNameEquals(currentResource, updateInfoResource)) {
+ if (isNested || !hasBeenCertified) {
+ componentNameValidator.validateAndCorrectField(null, updateInfoResource, null);
+ validateResourceNameUniqueness(updateInfoResource);
+ currentResource.setName(resourceNameUpdated);
+ currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
+ currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
+ } else {
+ log.info("Resource name: {}, cannot be updated once the resource has been certified once.", resourceNameUpdated);
+ throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
+ }
+ }
+ }
+
+ private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
+ String iconUpdated = updateInfoResource.getIcon();
+ String iconCurrent = currentResource.getIcon();
+ if (!iconCurrent.equals(iconUpdated)) {
+ if (!hasBeenCertified) {
+ componentIconValidator.validateAndCorrectField(null, updateInfoResource, null);
+ } else {
+ log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
+ throw new ByActionStatusComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
+ }
+ }
+ }
+
+ private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
+ String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
+ String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
+ if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
+ validateResourceVendorModelNumber(null, updateInfoResource, null);
+ }
+ }
+
+ private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified,
+ boolean inTransaction) {
+ validateCategory(null, updateInfoResource, null, inTransaction);
+ if (hasBeenCertified) {
+ CategoryDefinition currentCategory = currentResource.getCategories().get(0);
+ SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0);
+ CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0);
+ SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0);
+ if (!currentCategory.getName().equals(updateCategory.getName()) || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) {
+ log.info("Category {} cannot be updated once the resource has been certified once.", currentResource.getCategories());
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
+ return Either.right(errorResponse);
+ }
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource,
+ boolean hasBeenCertified) {
+ List<String> currentDerivedFrom = currentResource.getDerivedFrom();
+ List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
+ if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) {
+ log.trace("Update normative types");
+ return Either.left(true);
+ }
+ String derivedFromCurrent = currentDerivedFrom.get(0);
+ String derivedFromUpdated = updatedDerivedFrom.get(0);
+ if (!derivedFromCurrent.equals(derivedFromUpdated)) {
+ if (!hasBeenCertified) {
+ validateDerivedFromExist(null, updateInfoResource, null);
+ } else {
+ Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource,
+ null);
+ if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
+ log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
+ return validateDerivedFromExtending;
+ }
+ }
+ } else {
+ // For derived from, we must know whether it was actually changed,
+
+ // otherwise we must do no action.
+
+ // Due to changes it inflicts on data model (remove artifacts,
+
+ // properties...), it's not like a flat field which can be
+
+ // overwritten if not changed.
+
+ // So we must indicate that derived from is not changed
+ updateInfoResource.setDerivedFrom(null);
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource,
+ boolean hasBeenCertified) {
+ List<String> currentDerivedFrom = currentResource.getDerivedFrom();
+ List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
+ if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) {
+ log.trace("Update normative types");
+ return Either.left(true);
+ }
+ String derivedFromCurrent = currentDerivedFrom.get(0);
+ String derivedFromUpdated = updatedDerivedFrom.get(0);
+ if (!derivedFromCurrent.equals(derivedFromUpdated)) {
+ if (!hasBeenCertified) {
+ validateDerivedFromExist(null, updateInfoResource, null);
+ } else {
+ Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource,
+ null);
+ if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
+ log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
+ return validateDerivedFromExtending;
+ }
+ }
+ }
+ return Either.left(true);
+ }
+
+ private void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
+ if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
+ return;
+ }
+ String templateName = resource.getDerivedFrom().get(0);
+ Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExists(templateName);
+ if (dataModelResponse.isRight()) {
+ StorageOperationStatus storageStatus = dataModelResponse.right().value();
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
+ log.debug("request to data model failed with error: {}", storageStatus);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
+ log.trace("audit before sending response");
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
+ } else if (!dataModelResponse.left().value()) {
+ log.info("resource template with name: {}, does not exists", templateName);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ throw new ByActionStatusComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
+ }
+ }
+
+ // Tal G for extending inheritance US815447
+ private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource,
+ AuditingActionEnum actionEnum) {
+ String currentTemplateName = currentResource.getDerivedFrom().get(0);
+ String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
+ Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
+ .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
+ if (dataModelResponse.isRight()) {
+ StorageOperationStatus storageStatus = dataModelResponse.right().value();
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
+ log.trace("audit before sending response");
+ componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
+ return Either.right(responseFormat);
+ }
+ if (!dataModelResponse.left().value()) {
+ log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, currentTemplateName);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
+ componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
+ return Either.right(responseFormat);
+ }
+ return Either.left(true);
+ }
+
+ public void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
+ log.debug("validate resource derivedFrom field");
+ if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) || (resource.getDerivedFrom().get(0)) == null || (resource
+ .getDerivedFrom().get(0).trim().isEmpty())) {
+ log.info("derived from (template) field is missing for the resource");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ throw new ByActionStatusComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
+ }
+ }
+
+ private void validateResourceNameUniqueness(Resource resource) {
+ Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
+ .validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
+ if (resourceOperationResponse.isLeft() && resourceOperationResponse.left().value()) {
+ log.debug("resource with name: {}, already exists", resource.getName());
+ throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(),
+ resource.getName());
+ } else if (resourceOperationResponse.isRight()) {
+ log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
+ throw new StorageException(resourceOperationResponse.right().value());
+ }
+ }
+
+ private void validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
+ List<CategoryDefinition> categories = resource.getCategories();
+ if (CollectionUtils.isEmpty(categories)) {
+ log.debug(CATEGORY_IS_EMPTY);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ if (categories.size() > 1) {
+ log.debug("Must be only one category for resource");
+ throw new ByActionStatusComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ CategoryDefinition category = categories.get(0);
+ List<SubCategoryDefinition> subcategories = category.getSubcategories();
+ if (CollectionUtils.isEmpty(subcategories)) {
+ log.debug("Missinig subcategory for resource");
+ throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
+ }
+ if (subcategories.size() > 1) {
+ log.debug("Must be only one sub category for resource");
+ throw new ByActionStatusComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
+ }
+ SubCategoryDefinition subcategory = subcategories.get(0);
+ if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
+ log.debug(CATEGORY_IS_EMPTY);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
+ log.debug(CATEGORY_IS_EMPTY);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
+ }
+
+ private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, User user, Resource resource,
+ AuditingActionEnum actionEnum, boolean inTransaction) {
+ ResponseFormat responseFormat;
+ if (category != null && subcategory != null) {
+ log.debug("validating resource category {} against valid categories list", category);
+ Either<List<CategoryDefinition>, ActionStatus> categories = elementDao.getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
+ if (categories.isRight()) {
+ log.debug("failed to retrieve resource categories from JanusGraph");
+ responseFormat = componentsUtils.getResponseFormat(categories.right().value());
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ throw new ByActionStatusComponentException(categories.right().value());
+ }
+ List<CategoryDefinition> categoryList = categories.left().value();
+ Optional<CategoryDefinition> foundCategory = categoryList.stream().filter(cat -> cat.getName().equals(category.getName())).findFirst();
+ if (!foundCategory.isPresent()) {
+ log.debug("Category {} is not part of resource category group. Resource category valid values are {}", category, categoryList);
+ failOnInvalidCategory(user, resource, actionEnum);
+ }
+ Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get().getSubcategories().stream()
+ .filter(subcat -> subcat.getName().equals(subcategory.getName())).findFirst();
+ if (!foundSubcategory.isPresent()) {
+ log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", subcategory,
+ foundCategory.get().getSubcategories());
+ failOnInvalidCategory(user, resource, actionEnum);
+ }
+ }
+ }
+
+ private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
+ ResponseFormat responseFormat;
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ }
+
+ public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
+ String vendorRelease = resource.getVendorRelease();
+ log.debug("validate vendor relese name");
+ if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
+ log.info("vendor relese name is missing.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
+ componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+ throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
+ }
+ validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
+ }
+
+ public void validateVendorReleaseName(String vendorRelease, User user, Resource resource, AuditingActionEnum actionEnum) {
+ if (vendorRelease != null) {
+ if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
+ log.info("vendor release exceds limit.");
+ ResponseFormat errorResponse = componentsUtils
+ .getResponseFormat(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
+ componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+ throw new ByActionStatusComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
+ }
+ if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
+ log.info("vendor release is not valid.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
+ componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
throw new ByActionStatusComponentException(ActionStatus.INVALID_VENDOR_RELEASE, vendorRelease);
}
}
}
- private void validateVendorName(User user, Resource resource,
- AuditingActionEnum actionEnum) {
+ private void validateVendorName(User user, Resource resource, AuditingActionEnum actionEnum) {
String vendorName = resource.getVendorName();
if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
log.info("vendor name is missing.");
@@ -5472,18 +4594,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
validateVendorName(vendorName, user, resource, actionEnum);
}
- private void validateVendorName(String vendorName, User user, Resource resource,
- AuditingActionEnum actionEnum) {
+ private void validateVendorName(String vendorName, User user, Resource resource, AuditingActionEnum actionEnum) {
if (vendorName != null) {
if (!ValidationUtils.validateVendorNameLength(vendorName)) {
log.info("vendor name exceds limit.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
- "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
+ ResponseFormat errorResponse = componentsUtils
+ .getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
- throw new ByActionStatusComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
- "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
+ throw new ByActionStatusComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
}
-
if (!ValidationUtils.validateVendorName(vendorName)) {
log.info("vendor name is not valid.");
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
@@ -5498,26 +4617,24 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (StringUtils.isNotEmpty(resourceVendorModelNumber)) {
if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
log.info("resource vendor model number exceeds limit.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(
- ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
- "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
+ "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
throw new ByActionStatusComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
- "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
+ "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
}
// resource vendor model number is currently validated as vendor
+
// name
if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
log.info("resource vendor model number is not valid.");
- ResponseFormat errorResponse = componentsUtils
- .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
}
}
}
-
private void validateCost(Resource resource) {
String cost = resource.getCost();
if (cost != null) {
@@ -5528,13 +4645,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
- private void validateLicenseType(User user, Resource resource,
- AuditingActionEnum actionEnum) {
+ private void validateLicenseType(User user, Resource resource, AuditingActionEnum actionEnum) {
log.debug("validate licenseType");
String licenseType = resource.getLicenseType();
if (licenseType != null) {
- List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
- .getLicenseTypes();
+ List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getLicenseTypes();
if (!licenseTypes.contains(licenseType)) {
log.debug("License type {} isn't configured", licenseType);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
@@ -5547,509 +4662,437 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
- private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource,
- Resource updatedResource, String userId, boolean inTransaction) {
- if (updatedResource.getDerivedFrom() != null) {
- log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
- log.debug("1. Removing interface artifacts from graph");
- // Remove all interface artifacts of resource
- String resourceId = updatedResource.getUniqueId();
- Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
-
- if (interfaces != null) {
- Collection<InterfaceDefinition> values = interfaces.values();
- for (InterfaceDefinition interfaceDefinition : values) {
- String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
-
- log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
- Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
- if (operations != null) {
- for (Entry<String, Operation> operationEntry : operations.entrySet()) {
- Operation operation = operationEntry.getValue();
- ArtifactDefinition implementation = operation.getImplementationArtifact();
- if (implementation != null) {
- String uniqueId = implementation.getUniqueId();
- log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}",
- uniqueId, operationEntry.getKey(), interfaceType);
- // only thing that transacts and locks here
- Either<ArtifactDefinition, ResponseFormat> deleteArtifactByInterface =
- artifactsBusinessLogic.deleteArtifactByInterface(resourceId, userId, uniqueId, true);
- if (deleteArtifactByInterface.isRight()) {
- log.debug("Couldn't remove artifact definition with id {}", uniqueId);
- if (!inTransaction) {
- janusGraphDao.rollback();
- }
- return Either.right(deleteArtifactByInterface.right()
- .value());
- }
- } else {
- log.trace("No implementation found for operation {} - nothing to delete",
- operationEntry.getKey());
- }
- }
- } else {
- log.trace("No operations found for interface type {}", interfaceType);
- }
- }
- }
- log.debug("2. Removing properties");
- Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation
- .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
-
- if (findPropertiesOfNode.isRight() && findPropertiesOfNode.right().value() != StorageOperationStatus.OK) {
- log.debug("Failed to remove all properties of resource");
- if (!inTransaction) {
+ private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource, Resource updatedResource, String userId,
+ boolean inTransaction) {
+ if (updatedResource.getDerivedFrom() != null) {
+ log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
+ log.debug("1. Removing interface artifacts from graph");
+ // Remove all interface artifacts of resource
+ String resourceId = updatedResource.getUniqueId();
+ Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
+ if (interfaces != null) {
+ Collection<InterfaceDefinition> values = interfaces.values();
+ for (InterfaceDefinition interfaceDefinition : values) {
+ String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
+ log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
+ Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
+ if (operations != null) {
+ for (Entry<String, Operation> operationEntry : operations.entrySet()) {
+ Operation operation = operationEntry.getValue();
+ ArtifactDefinition implementation = operation.getImplementationArtifact();
+ if (implementation != null) {
+ String uniqueId = implementation.getUniqueId();
+ log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}", uniqueId,
+ operationEntry.getKey(), interfaceType);
+ // only thing that transacts and locks here
+ Either<ArtifactDefinition, ResponseFormat> deleteArtifactByInterface = artifactsBusinessLogic
+ .deleteArtifactByInterface(resourceId, userId, uniqueId, true);
+ if (deleteArtifactByInterface.isRight()) {
+ log.debug("Couldn't remove artifact definition with id {}", uniqueId);
+ if (!inTransaction) {
+ janusGraphDao.rollback();
+ }
+ return Either.right(deleteArtifactByInterface.right().value());
+ }
+ } else {
+ log.trace("No implementation found for operation {} - nothing to delete", operationEntry.getKey());
+ }
+ }
+ } else {
+ log.trace("No operations found for interface type {}", interfaceType);
+ }
+ }
+ }
+ log.debug("2. Removing properties");
+ Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation
+ .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
+ if (findPropertiesOfNode.isRight() && findPropertiesOfNode.right().value() != StorageOperationStatus.OK) {
+ log.debug("Failed to remove all properties of resource");
+ if (!inTransaction) {
janusGraphDao.rollback();
- }
- return Either.right(componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right()
- .value())));
- }
-
- } else {
- log.debug("Derived from wasn't changed during update");
- }
-
- if (inTransaction) {
- return Either.left(true);
- }
+ }
+ return Either
+ .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
+ }
+ } else {
+ log.debug("Derived from wasn't changed during update");
+ }
+ if (inTransaction) {
+ return Either.left(true);
+ }
janusGraphDao.commit();
- return Either.left(true);
-
- }
-
- public ICapabilityTypeOperation getCapabilityTypeOperation() {
- return capabilityTypeOperation;
- }
-
- @Autowired
- public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
- this.capabilityTypeOperation = capabilityTypeOperation;
- }
-
- public Boolean validatePropertiesDefaultValues(Resource resource) {
- log.debug("validate resource properties default values");
- List<PropertyDefinition> properties = resource.getProperties();
- if (properties != null) {
- iterateOverProperties(properties);
- }
- return true;
- }
-
- public void iterateOverProperties(List<PropertyDefinition> properties) {
- String type = null;
- String innerType = null;
- for (PropertyDefinition property : properties) {
- if (!propertyOperation.isPropertyTypeValid(property)) {
- log.info("Invalid type for property {}", property);
- throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_TYPE,
- property.getType(), property.getName());
- }
-
- Map<String, DataTypeDefinition> allDataTypes = getAllDataTypes(applicationDataTypeCache);
- type = property.getType();
-
- if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
- ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes);
- if (responseFormat != null) {
- break;
- }
- }
- validateDefaultPropertyValue(property, allDataTypes, type, innerType);
- }
- }
-
- private void validateDefaultPropertyValue(PropertyDefinition property,
- Map<String, DataTypeDefinition> allDataTypes, String type, String innerType) {
- if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) {
- log.info("Invalid default value for property {}", property);
- ResponseFormat responseFormat;
- if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
- throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
- property.getName(), type, innerType, property.getDefaultValue());
- }
- throw new ByActionStatusComponentException(ActionStatus.INVALID_DEFAULT_VALUE,
- property.getName(), type, property.getDefaultValue());
- }
- }
-
- private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType,
- Map<String, DataTypeDefinition> allDataTypes) {
- ResponseFormat responseFormat = null;
- ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property,
- allDataTypes);
- innerType = propertyInnerTypeValid.getLeft();
- if (!propertyInnerTypeValid.getRight()
- .booleanValue()) {
- log.info("Invalid inner type for property {}", property);
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType,
- property.getName());
- }
- return responseFormat;
- }
-
- @Override
- public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
- return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
- }
-
- @Override
- public ComponentInstanceBusinessLogic getComponentInstanceBL() {
- return componentInstanceBusinessLogic;
- }
-
- private String getComponentTypeForResponse(Component component) {
- String componentTypeForResponse = "SERVICE";
- if (component instanceof Resource) {
- componentTypeForResponse = ((Resource) component).getResourceType()
- .name();
- }
- return componentTypeForResponse;
- }
-
- public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
- // validate user
- if (user != null) {
- validateUserExists(user);
- }
- // get resource from csar uuid
- Either<Resource, StorageOperationStatus> either = toscaOperationFacade
- .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
- if (either.isRight()) {
- ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND,
- csarUuid);
- return Either.right(resp);
- }
-
- return Either.left(either.left()
- .value());
- }
-
- @Override
- public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(
- String componentId, String userId) {
- return null;
- }
-
- private Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(String resourceId,
- Map<String, List<CapabilityDefinition>> defaultCapabilities,
- Map<String, List<UploadCapInfo>> uploadedCapabilities) {
-
- Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
- uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId,
- defaultCapabilities, validCapabilitiesMap));
- return validCapabilitiesMap;
- }
-
- private void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId,
- Map<String, List<CapabilityDefinition>> defaultCapabilities,
- Map<String, List<CapabilityDefinition>> validCapabilitiesMap) {
- String capabilityType = capabilities.get(0)
- .getType();
- if (defaultCapabilities.containsKey(capabilityType)) {
- CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
- validateCapabilityProperties(capabilities, resourceId, defaultCapability);
- List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
- validCapabilityList.add(defaultCapability);
- validCapabilitiesMap.put(key, validCapabilityList);
- } else {
- throw new ByActionStatusComponentException(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType);
- }
- }
-
- private void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId,
- CapabilityDefinition defaultCapability) {
- if (CollectionUtils.isEmpty(defaultCapability.getProperties()) && isNotEmpty(capabilities.get(0)
- .getProperties())) {
- log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
- defaultCapability.getName(), resourceId);
- log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ",
- defaultCapability.getName());
- throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, resourceId);
- } else if (isNotEmpty(capabilities.get(0)
- .getProperties())) {
- validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
- }
- }
-
- private CapabilityDefinition getCapability(String resourceId,
- Map<String, List<CapabilityDefinition>> defaultCapabilities, String capabilityType) {
- CapabilityDefinition defaultCapability;
- if (isNotEmpty(defaultCapabilities.get(capabilityType)
- .get(0)
- .getProperties())) {
- defaultCapability = defaultCapabilities.get(capabilityType)
- .get(0);
- } else {
- Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
- .getToscaFullElement(resourceId);
- if (getFullComponentRes.isRight()) {
- log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right()
- .value());
- throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NOT_FOUND, resourceId);
- }
- defaultCapability = getFullComponentRes.left()
- .value()
- .getCapabilities()
- .get(capabilityType)
- .get(0);
- }
- return defaultCapability;
- }
-
- private void validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability,
- UploadCapInfo uploadedCapability) {
- List<ComponentInstanceProperty> validProperties = new ArrayList<>();
- Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties()
- .stream()
- .collect(toMap(PropertyDefinition::getName, Function.identity()));
- List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
- for (UploadPropInfo property : uploadedProperties) {
- String propertyName = property.getName()
- .toLowerCase();
- String propertyType = property.getType();
- ComponentInstanceProperty validProperty;
- if (defaultProperties.containsKey(propertyName)
- && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
- throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, propertyName);
- }
- validProperty = new ComponentInstanceProperty();
- validProperty.setName(propertyName);
- if (property.getValue() != null) {
- validProperty.setValue(property.getValue()
- .toString());
- }
- validProperty.setDescription(property.getDescription());
- validProperty.setPassword(property.isPassword());
- validProperties.add(validProperty);
- }
- defaultCapability.setProperties(validProperties);
- }
-
- private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName,
- String propertyType) {
- return propertyType != null && !defaultProperties.get(propertyName)
- .getType()
- .equals(propertyType);
- }
-
- private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
- List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
- Resource resource, User user) {
-
- EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
- ArtifactOperationEnum.class);
- Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
- Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
- .left(nodeTypeArtifactsToHandle);
- try {
- // add all found Csar artifacts to list to upload
- List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
- List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
- List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
- for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
- ArtifactDefinition foundArtifact;
-
- if (!existingArtifactsToHandle.isEmpty()) {
- foundArtifact = existingArtifactsToHandle.stream()
- .filter(a -> a.getArtifactName()
- .equals(currNewArtifact.getArtifactName()))
- .findFirst()
- .orElse(null);
- if (foundArtifact != null) {
- if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) {
- if (!foundArtifact.getArtifactChecksum()
- .equals(currNewArtifact.getArtifactChecksum())) {
- currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
- // if current artifact already exists, but has
- // different content, add him to the list to
- // update
- artifactsToUpdate.add(currNewArtifact);
- }
- // remove found artifact from the list of existing
- // artifacts to handle, because it was already
- // handled
- existingArtifactsToHandle.remove(foundArtifact);
- // and remove found artifact from the list to
- // upload, because it should either be updated or be
- // ignored
- artifactsToUpload.remove(currNewArtifact);
- } else {
- log.debug("Can't upload two artifact with the same name {}.",
- currNewArtifact.getArtifactName());
- ResponseFormat responseFormat = ResponseFormatManager.getInstance()
- .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
- currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
- foundArtifact.getArtifactType());
- AuditingActionEnum auditingAction = artifactsBusinessLogic
- .detectAuditingType(new ArtifactOperationInfo(false, false,
- ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
- artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(),
- user, null, null, foundArtifact.getUniqueId(), responseFormat,
- resource.getComponentType(), null);
- responseWrapper.setInnerElement(responseFormat);
- break;
- }
- }
- }
- }
- if (responseWrapper.isEmpty()) {
- for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
- if (currArtifact.getIsFromCsar()) {
- artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
- currArtifact.getArtifactType(),
- currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(),
- currArtifact.getIsFromCsar()));
- } else {
- artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
- currArtifact.getArtifactType(),
- currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(),
- currArtifact.getIsFromCsar()));
-
- }
- }
- }
- if (responseWrapper.isEmpty()) {
- if (!artifactsToUpload.isEmpty()) {
- nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
- }
- if (!artifactsToUpdate.isEmpty()) {
- nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
- }
- if (!artifactsToDelete.isEmpty()) {
- nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
- }
- }
- if (!responseWrapper.isEmpty()) {
- nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
- }
- } catch (Exception e) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- responseWrapper.setInnerElement(responseFormat);
- log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
- }
- return nodeTypeArtifactsToHandleRes;
- }
-
- ImmutablePair<String, String> buildNestedToscaResourceName(final String nodeResourceType,
- final String vfResourceName,
- final String nodeTypeFullName) {
- String actualType;
- String actualVfName;
- if (ResourceTypeEnum.CVFC.name()
- .equals(nodeResourceType)) {
- actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
- actualType = ResourceTypeEnum.VFC.name();
- } else {
- actualVfName = vfResourceName;
- actualType = nodeResourceType;
- }
- String nameWithouNamespacePrefix;
- try {
- final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeTypeFullName);
- log.debug("####### buildNestedToscaResourceName nodeResourceType {}, vfResourceName {}, "
- + "nodeTypeFullName {}, actualType {}, vfResourceName {} ", nodeResourceType, vfResourceName,
- nodeTypeFullName, actualType, vfResourceName);
- final StringBuilder toscaResourceName = new StringBuilder(nodeTypeNamePrefix);
-
- if (!nodeTypeFullName.contains(nodeTypeNamePrefix)) {
- nameWithouNamespacePrefix = nodeTypeFullName;
- } else {
- nameWithouNamespacePrefix = nodeTypeFullName.substring(nodeTypeNamePrefix.length());
- }
- final String[] findTypes = nameWithouNamespacePrefix.split("\\.");
- String actualName;
- if (nodeResourceType.equalsIgnoreCase(findTypes[0])){
- actualName = nameWithouNamespacePrefix.substring(nodeResourceType.length());
- } else {
- actualName = "." + nameWithouNamespacePrefix;
- }
-
- if (actualName.startsWith(Constants.ABSTRACT)) {
- toscaResourceName.append(nodeResourceType.toLowerCase()).append('.')
- .append(ValidationUtils.convertToSystemName(actualVfName));
- } else {
- toscaResourceName.append(actualType.toLowerCase()).append('.')
- .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
- }
- final StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
- final String[] actualNames = actualName.split("\\.");
- if (actualNames.length < 3) {
- return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
- previousToscaResourceName.append(actualName).toString());
- }
- return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
- previousToscaResourceName.append(actualName.substring(actualNames[1].length() + 1)
- .toLowerCase()).toString());
- } catch (final Exception e) {
- log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
- throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
- }
- }
-
- /**
- * Extracts a Node Type Name prefix from the given Node Type Name.
- *
- * @param fullName Node Type Name
- * @return Node Type Name Prefix
- */
- private String getNodeTypeNamePrefix(final String fullName) {
- String tempPrefix = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX;
- final List<String> definedNodeTypeNamespaceList = getDefinedNodeTypeNamespaceList();
- log.debug("************* getPrefiX fullName {} FROM {}", fullName, definedNodeTypeNamespaceList);
- final Optional<String> validNameSpace = validateNodeTypeNamePrefix(fullName, definedNodeTypeNamespaceList);
- if (validNameSpace.isPresent()) {
- tempPrefix = validNameSpace.get();
- }
- log.debug("************* getNodeTypeNamePrefix return fullName {} ", tempPrefix);
- return tempPrefix;
- }
-
- @Override
- public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId,
- List<String> dataParamsToReturn) {
-
- ComponentParametersView paramsToReturn = new ComponentParametersView(dataParamsToReturn);
- Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToReturn);
-
- if (resourceResultEither.isRight()) {
- if (resourceResultEither.right().value() == StorageOperationStatus.NOT_FOUND) {
- log.debug("Failed to found resource with id {} ", resourceId);
- Either
- .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
- }
-
- log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn);
- return Either.right(componentsUtils
- .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right()
- .value()), ""));
- }
-
- Resource resource = resourceResultEither.left().value();
- if (dataParamsToReturn.contains(ComponentFieldsEnum.INPUTS.getValue())) {
- ListUtils.emptyIfNull(resource.getInputs())
- .forEach(input -> input.setConstraints(setInputConstraint(input)));
- }
-
- UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
- dataParamsToReturn);
- return Either.left(dataTransfer);
- }
-
- @Override
- public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
- Resource resource = (Resource) clonedComponent;
- if (ModelConverter.isAtomicComponent(resource.getResourceType())) {
- Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade
- .shouldUpgradeToLatestDerived(resource);
- if (shouldUpgradeToLatestDerived.isRight()) {
- return Either.right(componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right()
- .value()));
- }
- return Either.left(shouldUpgradeToLatestDerived.left()
- .value());
- } else {
- return super.shouldUpgradeToLatestDerived(clonedComponent);
- }
- }
+ return Either.left(true);
+ }
+
+ public ICapabilityTypeOperation getCapabilityTypeOperation() {
+ return capabilityTypeOperation;
+ }
+
+ @Autowired
+ public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
+ this.capabilityTypeOperation = capabilityTypeOperation;
+ }
+
+ public Boolean validatePropertiesDefaultValues(Resource resource) {
+ log.debug("validate resource properties default values");
+ List<PropertyDefinition> properties = resource.getProperties();
+ if (properties != null) {
+ iterateOverProperties(properties);
+ }
+ return true;
+ }
+
+ public void iterateOverProperties(List<PropertyDefinition> properties) {
+ String type = null;
+ String innerType = null;
+ for (PropertyDefinition property : properties) {
+ if (!propertyOperation.isPropertyTypeValid(property)) {
+ log.info("Invalid type for property {}", property);
+ throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
+ }
+ Map<String, DataTypeDefinition> allDataTypes = getAllDataTypes(applicationDataTypeCache);
+ type = property.getType();
+ if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
+ ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes);
+ if (responseFormat != null) {
+ break;
+ }
+ }
+ validateDefaultPropertyValue(property, allDataTypes, type, innerType);
+ }
+ }
+
+ private void validateDefaultPropertyValue(PropertyDefinition property, Map<String, DataTypeDefinition> allDataTypes, String type,
+ String innerType) {
+ if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) {
+ log.info("Invalid default value for property {}", property);
+ ResponseFormat responseFormat;
+ if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
+ throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType,
+ property.getDefaultValue());
+ }
+ throw new ByActionStatusComponentException(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue());
+ }
+ }
+
+ private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType,
+ Map<String, DataTypeDefinition> allDataTypes) {
+ ResponseFormat responseFormat = null;
+ ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, allDataTypes);
+ innerType = propertyInnerTypeValid.getLeft();
+ if (!propertyInnerTypeValid.getRight().booleanValue()) {
+ log.info("Invalid inner type for property {}", property);
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
+ }
+ return responseFormat;
+ }
+
+ @Override
+ public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
+ return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
+ }
+
+ @Override
+ public ComponentInstanceBusinessLogic getComponentInstanceBL() {
+ return componentInstanceBusinessLogic;
+ }
+
+ private String getComponentTypeForResponse(Component component) {
+ String componentTypeForResponse = "SERVICE";
+ if (component instanceof Resource) {
+ componentTypeForResponse = ((Resource) component).getResourceType().name();
+ }
+ return componentTypeForResponse;
+ }
+
+ public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
+ // validate user
+ if (user != null) {
+ validateUserExists(user);
+ }
+ // get resource from csar uuid
+ Either<Resource, StorageOperationStatus> either = toscaOperationFacade
+ .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
+ if (either.isRight()) {
+ ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND, csarUuid);
+ return Either.right(resp);
+ }
+ return Either.left(either.left().value());
+ }
+
+ @Override
+ public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, String userId) {
+ return null;
+ }
+
+ private Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(String resourceId,
+ Map<String, List<CapabilityDefinition>> defaultCapabilities,
+ Map<String, List<UploadCapInfo>> uploadedCapabilities) {
+ Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
+ uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId, defaultCapabilities, validCapabilitiesMap));
+ return validCapabilitiesMap;
+ }
+
+ private void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId,
+ Map<String, List<CapabilityDefinition>> defaultCapabilities,
+ Map<String, List<CapabilityDefinition>> validCapabilitiesMap) {
+ String capabilityType = capabilities.get(0).getType();
+ if (defaultCapabilities.containsKey(capabilityType)) {
+ CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
+ validateCapabilityProperties(capabilities, resourceId, defaultCapability);
+ List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
+ validCapabilityList.add(defaultCapability);
+ validCapabilitiesMap.put(key, validCapabilityList);
+ } else {
+ throw new ByActionStatusComponentException(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType);
+ }
+ }
+
+ private void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId, CapabilityDefinition defaultCapability) {
+ if (CollectionUtils.isEmpty(defaultCapability.getProperties()) && isNotEmpty(capabilities.get(0).getProperties())) {
+ log.debug("Failed to validate capability {} of component {}. Property list is empty. ", defaultCapability.getName(), resourceId);
+ log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ", defaultCapability.getName());
+ throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, resourceId);
+ } else if (isNotEmpty(capabilities.get(0).getProperties())) {
+ validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
+ }
+ }
+
+ private CapabilityDefinition getCapability(String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities,
+ String capabilityType) {
+ CapabilityDefinition defaultCapability;
+ if (isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) {
+ defaultCapability = defaultCapabilities.get(capabilityType).get(0);
+ } else {
+ Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade.getToscaFullElement(resourceId);
+ if (getFullComponentRes.isRight()) {
+ log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right().value());
+ throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NOT_FOUND, resourceId);
+ }
+ defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
+ }
+ return defaultCapability;
+ }
+
+ private void validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability,
+ UploadCapInfo uploadedCapability) {
+ List<ComponentInstanceProperty> validProperties = new ArrayList<>();
+ Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream()
+ .collect(toMap(PropertyDefinition::getName, Function.identity()));
+ List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
+ for (UploadPropInfo property : uploadedProperties) {
+ String propertyName = property.getName().toLowerCase();
+ String propertyType = property.getType();
+ ComponentInstanceProperty validProperty;
+ if (defaultProperties.containsKey(propertyName) && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
+ throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, propertyName);
+ }
+ validProperty = new ComponentInstanceProperty();
+ validProperty.setName(propertyName);
+ if (property.getValue() != null) {
+ validProperty.setValue(property.getValue().toString());
+ }
+ validProperty.setDescription(property.getDescription());
+ validProperty.setPassword(property.isPassword());
+ validProperties.add(validProperty);
+ }
+ defaultCapability.setProperties(validProperties);
+ }
+
+ private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName, String propertyType) {
+ return propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType);
+ }
+
+ private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
+ List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle, Resource resource, User user) {
+ EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
+ Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
+ Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
+ .left(nodeTypeArtifactsToHandle);
+ try {
+ // add all found Csar artifacts to list to upload
+ List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
+ List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
+ List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
+ for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
+ ArtifactDefinition foundArtifact;
+ if (!existingArtifactsToHandle.isEmpty()) {
+ foundArtifact = existingArtifactsToHandle.stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName()))
+ .findFirst().orElse(null);
+ if (foundArtifact != null) {
+ if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) {
+ if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
+ currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
+ // if current artifact already exists, but has
+
+ // different content, add him to the list to
+
+ // update
+ artifactsToUpdate.add(currNewArtifact);
+ }
+ // remove found artifact from the list of existing
+
+ // artifacts to handle, because it was already
+
+ // handled
+ existingArtifactsToHandle.remove(foundArtifact);
+ // and remove found artifact from the list to
+
+ // upload, because it should either be updated or be
+
+ // ignored
+ artifactsToUpload.remove(currNewArtifact);
+ } else {
+ log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
+ ResponseFormat responseFormat = ResponseFormatManager.getInstance()
+ .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
+ currNewArtifact.getArtifactType(), foundArtifact.getArtifactType());
+ AuditingActionEnum auditingAction = artifactsBusinessLogic
+ .detectAuditingType(new ArtifactOperationInfo(false, false, ArtifactOperationEnum.CREATE),
+ foundArtifact.getArtifactChecksum());
+ artifactsBusinessLogic
+ .handleAuditing(auditingAction, resource, resource.getUniqueId(), user, null, null, foundArtifact.getUniqueId(),
+ responseFormat, resource.getComponentType(), null);
+ responseWrapper.setInnerElement(responseFormat);
+ break;
+ }
+ }
+ }
+ }
+ if (responseWrapper.isEmpty()) {
+ for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
+ if (currArtifact.getIsFromCsar()) {
+ artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, currArtifact.getArtifactType(),
+ currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
+ } else {
+ artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, currArtifact.getArtifactType(),
+ currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
+ }
+ }
+ }
+ if (responseWrapper.isEmpty()) {
+ if (!artifactsToUpload.isEmpty()) {
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
+ }
+ if (!artifactsToUpdate.isEmpty()) {
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
+ }
+ if (!artifactsToDelete.isEmpty()) {
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
+ }
+ }
+ if (!responseWrapper.isEmpty()) {
+ nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
+ }
+ } catch (Exception e) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ responseWrapper.setInnerElement(responseFormat);
+ log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
+ }
+ return nodeTypeArtifactsToHandleRes;
+ }
+
+ ImmutablePair<String, String> buildNestedToscaResourceName(final String nodeResourceType, final String vfResourceName,
+ final String nodeTypeFullName) {
+ String actualType;
+ String actualVfName;
+ if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) {
+ actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
+ actualType = ResourceTypeEnum.VFC.name();
+ } else {
+ actualVfName = vfResourceName;
+ actualType = nodeResourceType;
+ }
+ String nameWithouNamespacePrefix;
+ try {
+ final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeTypeFullName);
+ log.debug("####### buildNestedToscaResourceName nodeResourceType {}, vfResourceName {}, "
+ + "nodeTypeFullName {}, actualType {}, vfResourceName {} ", nodeResourceType, vfResourceName, nodeTypeFullName, actualType,
+ vfResourceName);
+ final StringBuilder toscaResourceName = new StringBuilder(nodeTypeNamePrefix);
+ if (!nodeTypeFullName.contains(nodeTypeNamePrefix)) {
+ nameWithouNamespacePrefix = nodeTypeFullName;
+ } else {
+ nameWithouNamespacePrefix = nodeTypeFullName.substring(nodeTypeNamePrefix.length());
+ }
+ final String[] findTypes = nameWithouNamespacePrefix.split("\\.");
+ String actualName;
+ if (nodeResourceType.equalsIgnoreCase(findTypes[0])) {
+ actualName = nameWithouNamespacePrefix.substring(nodeResourceType.length());
+ } else {
+ actualName = "." + nameWithouNamespacePrefix;
+ }
+ if (actualName.startsWith(Constants.ABSTRACT)) {
+ toscaResourceName.append(nodeResourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
+ } else {
+ toscaResourceName.append(actualType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName)).append('.')
+ .append(Constants.ABSTRACT);
+ }
+ final StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
+ final String[] actualNames = actualName.split("\\.");
+ if (actualNames.length < 3) {
+ return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
+ previousToscaResourceName.append(actualName).toString());
+ }
+ return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
+ previousToscaResourceName.append(actualName.substring(actualNames[1].length() + 1).toLowerCase()).toString());
+ } catch (final Exception e) {
+ log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
+ throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
+ }
+ }
+
+ /**
+ * Extracts a Node Type Name prefix from the given Node Type Name.
+ *
+ * @param fullName Node Type Name
+ * @return Node Type Name Prefix
+ */
+ private String getNodeTypeNamePrefix(final String fullName) {
+ String tempPrefix = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX;
+ final List<String> definedNodeTypeNamespaceList = getDefinedNodeTypeNamespaceList();
+ log.debug("************* getPrefiX fullName {} FROM {}", fullName, definedNodeTypeNamespaceList);
+ final Optional<String> validNameSpace = validateNodeTypeNamePrefix(fullName, definedNodeTypeNamespaceList);
+ if (validNameSpace.isPresent()) {
+ tempPrefix = validNameSpace.get();
+ }
+ log.debug("************* getNodeTypeNamePrefix return fullName {} ", tempPrefix);
+ return tempPrefix;
+ }
+
+ @Override
+ public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId,
+ List<String> dataParamsToReturn) {
+ ComponentParametersView paramsToReturn = new ComponentParametersView(dataParamsToReturn);
+ Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToReturn);
+ if (resourceResultEither.isRight()) {
+ if (resourceResultEither.right().value() == StorageOperationStatus.NOT_FOUND) {
+ log.debug("Failed to found resource with id {} ", resourceId);
+ Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
+ }
+ log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn);
+ return Either.right(
+ componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), ""));
+ }
+ Resource resource = resourceResultEither.left().value();
+ if (dataParamsToReturn.contains(ComponentFieldsEnum.INPUTS.getValue())) {
+ ListUtils.emptyIfNull(resource.getInputs()).forEach(input -> input.setConstraints(setInputConstraint(input)));
+ }
+ UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromResourceByParams(resource, dataParamsToReturn);
+ return Either.left(dataTransfer);
+ }
+
+ @Override
+ public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
+ Resource resource = (Resource) clonedComponent;
+ if (ModelConverter.isAtomicComponent(resource.getResourceType())) {
+ Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade.shouldUpgradeToLatestDerived(resource);
+ if (shouldUpgradeToLatestDerived.isRight()) {
+ return Either.right(componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right().value()));
+ }
+ return Either.left(shouldUpgradeToLatestDerived.left().value());
+ } else {
+ return super.shouldUpgradeToLatestDerived(clonedComponent);
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java
index 8ea1c2a28f..787bc3e2de 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java
@@ -19,12 +19,10 @@
* Modifications copyright (c) 2019 Nokia
* ================================================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import static org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaElementOperation.createDataType;
import static org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaElementOperation.createDataTypeDefinitionWithName;
-import static org.openecomp.sdc.be.utils.TypeUtils.setField;
import fj.data.Either;
import java.util.ArrayList;
@@ -102,33 +100,18 @@ import org.yaml.snakeyaml.Yaml;
@Component("resourceImportManager")
public class ResourceImportManager {
- private static final Logger log = Logger.getLogger(ResourceImportManager.class);
-
static final Pattern PROPERTY_NAME_PATTERN_IGNORE_LENGTH = Pattern.compile("[\\w\\-\\_\\d\\:]+");
+ private static final Logger log = Logger.getLogger(ResourceImportManager.class);
private final InterfaceDefinitionHandler interfaceDefinitionHandler;
-
+ private final ComponentsUtils componentsUtils;
+ private final CapabilityTypeOperation capabilityTypeOperation;
private ServletContext servletContext;
-
private AuditingManager auditingManager;
private ResourceBusinessLogic resourceBusinessLogic;
-
- public ServiceBusinessLogic getServiceBusinessLogic() {
- return serviceBusinessLogic;
- }
-
- public void setServiceBusinessLogic(ServiceBusinessLogic serviceBusinessLogic) {
- this.serviceBusinessLogic = serviceBusinessLogic;
- }
-
@Autowired
private ServiceBusinessLogic serviceBusinessLogic;
-
private IGraphLockOperation graphLockOperation;
private ToscaOperationFacade toscaOperationFacade;
-
- private final ComponentsUtils componentsUtils;
- private final CapabilityTypeOperation capabilityTypeOperation;
-
private ResponseFormatManager responseFormatManager;
@Autowired
@@ -139,88 +122,74 @@ public class ResourceImportManager {
this.interfaceDefinitionHandler = interfaceDefinitionHandler;
}
+ public ServiceBusinessLogic getServiceBusinessLogic() {
+ return serviceBusinessLogic;
+ }
+
+ public void setServiceBusinessLogic(ServiceBusinessLogic serviceBusinessLogic) {
+ this.serviceBusinessLogic = serviceBusinessLogic;
+ }
+
@Autowired
public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) {
this.toscaOperationFacade = toscaOperationFacade;
}
- public ImmutablePair<Resource, ActionStatus> importNormativeResource(String resourceYml,
- UploadResourceInfo resourceMetaData,
- User creator, boolean createNewVersion,
- boolean needLock) {
-
+ public ImmutablePair<Resource, ActionStatus> importNormativeResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator,
+ boolean createNewVersion, boolean needLock) {
LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction();
lifecycleChangeInfo.setUserRemarks("certification on import");
- Function<Resource, Boolean> validator = resource -> resourceBusinessLogic
- .validatePropertiesDefaultValues(resource);
-
- return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false,
- createNewVersion, needLock, null, null, false, null, null, false);
+ Function<Resource, Boolean> validator = resource -> resourceBusinessLogic.validatePropertiesDefaultValues(resource);
+ return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock,
+ null, null, false, null, null, false);
}
- public ImmutablePair<Resource, ActionStatus> importNormativeResourceFromCsar(String resourceYml,
- UploadResourceInfo resourceMetaData,
- User creator, boolean createNewVersion,
- boolean needLock) {
-
+ public ImmutablePair<Resource, ActionStatus> importNormativeResourceFromCsar(String resourceYml, UploadResourceInfo resourceMetaData,
+ User creator, boolean createNewVersion, boolean needLock) {
LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction();
lifecycleChangeInfo.setUserRemarks("certification on import");
- Function<Resource, Boolean> validator = resource -> resourceBusinessLogic
- .validatePropertiesDefaultValues(resource);
-
- return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false,
- createNewVersion, needLock, null, null, false, null, null, false);
+ Function<Resource, Boolean> validator = resource -> resourceBusinessLogic.validatePropertiesDefaultValues(resource);
+ return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock,
+ null, null, false, null, null, false);
}
- public ImmutablePair<Resource, ActionStatus> importCertifiedResource(String resourceYml,
- UploadResourceInfo resourceMetaData,
- User creator,
+ public ImmutablePair<Resource, ActionStatus> importCertifiedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator,
Function<Resource, Boolean> validationFunction,
- LifecycleChangeInfoWithAction lifecycleChangeInfo,
- boolean isInTransaction,
+ LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction,
boolean createNewVersion, boolean needLock,
Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
- boolean forceCertificationAllowed,
- CsarInfo csarInfo, String nodeName,
+ boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName,
boolean isNested) {
Resource resource = new Resource();
ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED);
Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> response = Either.left(responsePair);
-
String latestCertifiedResourceId = null;
try {
boolean shouldBeCertified = nodeTypeArtifactsToHandle == null || nodeTypeArtifactsToHandle.isEmpty();
setConstantMetaData(resource, shouldBeCertified);
setMetaDataFromJson(resourceMetaData, resource);
-
populateResourceFromYaml(resourceYml, resource);
-
validationFunction.apply(resource);
if (!createNewVersion) {
- Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade
- .getLatestByName(resource.getName());
+ Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName());
if (latestByName.isLeft()) {
- throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
- resource.getName());
+ throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, resource.getName());
}
} else {
- final Either<Resource, StorageOperationStatus> component = toscaOperationFacade.getComponentByNameAndVendorRelease(resource.getComponentType(), resource.getName(), resource.getVendorRelease(), JsonParseFlagEnum.ParseAll);
+ final Either<Resource, StorageOperationStatus> component = toscaOperationFacade
+ .getComponentByNameAndVendorRelease(resource.getComponentType(), resource.getName(), resource.getVendorRelease(),
+ JsonParseFlagEnum.ParseAll);
if (component.isLeft()) {
- throw new ByActionStatusComponentException(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST,
- resource.getName());
+ throw new ByActionStatusComponentException(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, resource.getName());
}
}
resource = resourceBusinessLogic
- .createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock, csarInfo, nodeName,
- isNested).left;
+ .createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock, csarInfo, nodeName, isNested).left;
Resource changeStateResponse;
-
if (nodeTypeArtifactsToHandle != null && !nodeTypeArtifactsToHandle.isEmpty()) {
- Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
- resourceBusinessLogic
- .handleNodeTypeArtifacts(resource, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts,
- creator, isInTransaction, false);
+ Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = resourceBusinessLogic
+ .handleNodeTypeArtifacts(resource, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, creator, isInTransaction, false);
if (handleNodeTypeArtifactsRes.isRight()) {
//TODO: should be used more correct action
throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
@@ -228,10 +197,8 @@ public class ResourceImportManager {
}
latestCertifiedResourceId = getLatestCertifiedResourceId(resource);
changeStateResponse = resourceBusinessLogic
- .propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock,
- forceCertificationAllowed);
- responsePair = new ImmutablePair<>(changeStateResponse, response.left()
- .value().right);
+ .propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock, forceCertificationAllowed);
+ responsePair = new ImmutablePair<>(changeStateResponse, response.left().value().right);
} catch (RuntimeException e) {
handleImportResourceException(resourceMetaData, creator, true, e);
} finally {
@@ -240,7 +207,6 @@ public class ResourceImportManager {
graphLockOperation.unlockComponent(latestCertifiedResourceId, NodeTypeEnum.Resource);
}
}
-
return responsePair;
}
@@ -279,45 +245,34 @@ public class ResourceImportManager {
}
}
- public ImmutablePair<Resource, ActionStatus> importUserDefinedResource(String resourceYml,
- UploadResourceInfo resourceMetaData,
- User creator, boolean isInTransaction) {
-
+ public ImmutablePair<Resource, ActionStatus> importUserDefinedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator,
+ boolean isInTransaction) {
Resource resource = new Resource();
ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED);
-
try {
setMetaDataFromJson(resourceMetaData, resource);
-
populateResourceFromYaml(resourceYml, resource);
-
// currently import VF isn't supported. In future will be supported
+
// import VF only with CSAR file!!
if (ResourceTypeEnum.VF == resource.getResourceType()) {
log.debug("Now import VF isn't supported. It will be supported in future with CSAR file only");
throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION);
}
-
resourceBusinessLogic.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
Boolean validatePropertiesTypes = resourceBusinessLogic.validatePropertiesDefaultValues(resource);
-
- responsePair = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator,
- false, isInTransaction, true, null, null, false);
-
+ responsePair = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, false, isInTransaction, true, null, null, false);
} catch (RuntimeException e) {
handleImportResourceException(resourceMetaData, creator, false, e);
}
return responsePair;
-
}
private void populateResourceFromYaml(String resourceYml, Resource resource) {
- @SuppressWarnings("unchecked")
- Object ymlObj = new Yaml().load(resourceYml);
+ @SuppressWarnings("unchecked") Object ymlObj = new Yaml().load(resourceYml);
if (ymlObj instanceof Map) {
Map<String, Object> toscaJsonAll = (Map<String, Object>) ymlObj;
Map<String, Object> toscaJson = toscaJsonAll;
-
// Checks if exist and builds the node_types map
if (toscaJsonAll.containsKey(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName())
&& resource.getResourceType() != ResourceTypeEnum.CVFC) {
@@ -326,8 +281,8 @@ public class ResourceImportManager {
toscaJsonAll.get(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName()));
}
final List<Object> foundElements = new ArrayList<>();
- final Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements(toscaJsonAll,
- ToscaTagNamesEnum.DATA_TYPES.getElementName(), ToscaElementTypeEnum.MAP, foundElements);
+ final Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils
+ .findToscaElements(toscaJsonAll, ToscaTagNamesEnum.DATA_TYPES.getElementName(), ToscaElementTypeEnum.MAP, foundElements);
if (toscaElements.isLeft()) {
final Map<String, Object> toscaAttributes = (Map<String, Object>) foundElements.get(0);
if (MapUtils.isNotEmpty(toscaAttributes)) {
@@ -347,7 +302,6 @@ public class ResourceImportManager {
} else {
throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
}
-
}
private void setToscaResourceName(Map<String, Object> toscaJson, Resource resource) {
@@ -366,16 +320,13 @@ public class ResourceImportManager {
Map<String, Object> jsonInterfaces = toscaInterfaces.left().value();
Map<String, InterfaceDefinition> moduleInterfaces = new HashMap<>();
for (final Entry<String, Object> interfaceNameValue : jsonInterfaces.entrySet()) {
- final Either<InterfaceDefinition, ResultStatusEnum> eitherInterface =
- createModuleInterface(interfaceNameValue.getValue());
+ final Either<InterfaceDefinition, ResultStatusEnum> eitherInterface = createModuleInterface(interfaceNameValue.getValue());
if (eitherInterface.isRight()) {
- log.info("error when creating interface:{}, for resource:{}", interfaceNameValue.getKey(),
- resource.getName());
+ log.info("error when creating interface:{}, for resource:{}", interfaceNameValue.getKey(), resource.getName());
} else {
final InterfaceDefinition interfaceDefinition = eitherInterface.left().value();
moduleInterfaces.put(interfaceNameValue.getKey(), interfaceDefinition);
}
-
}
if (!moduleInterfaces.isEmpty()) {
resource.setInterfaces(moduleInterfaces);
@@ -390,13 +341,11 @@ public class ResourceImportManager {
interfaceDefinition.setType((String) interfaceJson);
return Either.left(interfaceDefinition);
}
-
if (interfaceJson instanceof Map) {
final Map<String, Object> interfaceJsonMap = (Map<String, Object>) interfaceJson;
final InterfaceDefinition interfaceDefinition = interfaceDefinitionHandler.create(interfaceJsonMap);
return Either.left(interfaceDefinition);
}
-
return Either.right(ResultStatusEnum.GENERAL_ERROR);
} catch (final Exception e) {
BeEcompErrorManager.getInstance().logBeSystemError("Import Resource- create interface");
@@ -415,6 +364,7 @@ public class ResourceImportManager {
// Checking for name duplication
Set<String> reqNames = new HashSet<>();
// Getting flattened list of capabilities of parent node - cap name
+
// to cap type
Map<String, String> reqName2TypeMap = getReqName2Type(parentResource);
for (Object jsonRequirementObj : jsonRequirements) {
@@ -423,15 +373,11 @@ public class ResourceImportManager {
String requirementName = requirementJsonWrapper.keySet().iterator().next();
String reqNameLowerCase = requirementName.toLowerCase();
if (reqNames.contains(reqNameLowerCase)) {
- log.debug(
- "More than one requirement with same name {} (case-insensitive) in imported TOSCA file is invalid",
- reqNameLowerCase);
- throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME,
- "requirement", reqNameLowerCase);
+ log.debug("More than one requirement with same name {} (case-insensitive) in imported TOSCA file is invalid", reqNameLowerCase);
+ throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "requirement", reqNameLowerCase);
}
reqNames.add(reqNameLowerCase);
- RequirementDefinition requirementDef = createRequirementFromImportFile(requirementJsonWrapper
- .get(requirementName));
+ RequirementDefinition requirementDef = createRequirementFromImportFile(requirementJsonWrapper.get(requirementName));
requirementDef.setName(requirementName);
if (moduleRequirements.containsKey(requirementDef.getCapability())) {
moduleRequirements.get(requirementDef.getCapability()).add(requirementDef);
@@ -440,51 +386,39 @@ public class ResourceImportManager {
list.add(requirementDef);
moduleRequirements.put(requirementDef.getCapability(), list);
}
-
// Validating against req/cap of "derived from" node
- Boolean validateVsParentCap = validateCapNameVsDerived(reqName2TypeMap, requirementDef
- .getCapability(), requirementDef.getName());
+ Boolean validateVsParentCap = validateCapNameVsDerived(reqName2TypeMap, requirementDef.getCapability(), requirementDef.getName());
if (!validateVsParentCap) {
String parentResourceName = parentResource != null ? parentResource.getName() : "";
- log.debug("Requirement with name {} already exists in parent {}", requirementDef.getName(),
- parentResourceName);
- throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED,
- "requirement", requirementDef
- .getName()
- .toLowerCase(), parentResourceName);
+ log.debug("Requirement with name {} already exists in parent {}", requirementDef.getName(), parentResourceName);
+ throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "requirement",
+ requirementDef.getName().toLowerCase(), parentResourceName);
}
}
if (moduleRequirements.size() > 0) {
resource.setRequirements(moduleRequirements);
}
-
}
}
private RequirementDefinition createRequirementFromImportFile(Object requirementJson) {
RequirementDefinition requirement = new RequirementDefinition();
-
if (requirementJson instanceof String) {
String requirementJsonString = (String) requirementJson;
requirement.setCapability(requirementJsonString);
} else if (requirementJson instanceof Map) {
Map<String, Object> requirementJsonMap = (Map<String, Object>) requirementJson;
if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.CAPABILITY.getElementName())) {
- requirement.setCapability(
- (String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.CAPABILITY.getElementName()));
+ requirement.setCapability((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.CAPABILITY.getElementName()));
}
-
if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.NODE.getElementName())) {
requirement.setNode((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.NODE.getElementName()));
}
-
if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.RELATIONSHIP.getElementName())) {
- requirement.setRelationship(
- (String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.RELATIONSHIP.getElementName()));
+ requirement.setRelationship((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.RELATIONSHIP.getElementName()));
}
if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName())) {
- List<Object> occurrencesList = (List) requirementJsonMap
- .get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName());
+ List<Object> occurrencesList = (List) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName());
validateOccurrences(occurrencesList);
requirement.setMinOccurrences(occurrencesList.get(0).toString());
requirement.setMaxOccurrences(occurrencesList.get(1).toString());
@@ -498,8 +432,7 @@ public class ResourceImportManager {
private void setProperties(Map<String, Object> toscaJson, Resource resource) {
Map<String, Object> reducedToscaJson = new HashMap<>(toscaJson);
ImportUtils.removeElementFromJsonMap(reducedToscaJson, "capabilities");
- Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils
- .getProperties(reducedToscaJson);
+ Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(reducedToscaJson);
if (properties.isLeft()) {
List<PropertyDefinition> propertiesList = new ArrayList<>();
Map<String, PropertyDefinition> value = properties.left().value();
@@ -507,11 +440,9 @@ public class ResourceImportManager {
for (Entry<String, PropertyDefinition> entry : value.entrySet()) {
String name = entry.getKey();
if (!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(name).matches()) {
- log.debug("The property with invalid name {} occured upon import resource {}. ", name,
- resource.getName());
- throw new ByActionStatusComponentException(componentsUtils
- .convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME,
- JsonPresentationFields.PROPERTY));
+ log.debug("The property with invalid name {} occured upon import resource {}. ", name, resource.getName());
+ throw new ByActionStatusComponentException(
+ componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, JsonPresentationFields.PROPERTY));
}
PropertyDefinition propertyDefinition = entry.getValue();
propertyDefinition.setName(name);
@@ -520,27 +451,22 @@ public class ResourceImportManager {
}
resource.setProperties(propertiesList);
} else if (properties.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND) {
- throw new ByActionStatusComponentException(componentsUtils.convertFromResultStatusEnum(properties
- .right()
- .value(), JsonPresentationFields.PROPERTY));
+ throw new ByActionStatusComponentException(
+ componentsUtils.convertFromResultStatusEnum(properties.right().value(), JsonPresentationFields.PROPERTY));
}
}
private void setAttributes(final Map<String, Object> originalToscaJsonMap, final Resource resource) {
final Map<String, Object> toscaJsonMap = new HashMap<>(originalToscaJsonMap);
ImportUtils.removeElementFromJsonMap(toscaJsonMap, "capabilities");
- final Either<Map<String, AttributeDefinition>, ResultStatusEnum> getAttributeEither = ImportUtils
- .getAttributes(toscaJsonMap);
-
+ final Either<Map<String, AttributeDefinition>, ResultStatusEnum> getAttributeEither = ImportUtils.getAttributes(toscaJsonMap);
if (getAttributeEither.isRight()) {
final ResultStatusEnum resultStatus = getAttributeEither.right().value();
if (resultStatus == ResultStatusEnum.ELEMENT_NOT_FOUND) {
return;
}
- throw new ByActionStatusComponentException(
- componentsUtils.convertFromResultStatusEnum(resultStatus, JsonPresentationFields.ATTRIBUTES));
+ throw new ByActionStatusComponentException(componentsUtils.convertFromResultStatusEnum(resultStatus, JsonPresentationFields.ATTRIBUTES));
}
-
final List<AttributeDefinition> attributeDefinitionList = new ArrayList<>();
final Map<String, AttributeDefinition> attributeMap = getAttributeEither.left().value();
if (MapUtils.isEmpty(attributeMap)) {
@@ -549,11 +475,9 @@ public class ResourceImportManager {
for (final Entry<String, AttributeDefinition> entry : attributeMap.entrySet()) {
final String name = entry.getKey();
if (!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(name).matches()) {
- log.debug("Detected attribute with invalid name '{}' during resource '{}' import. ",
- name, resource.getName());
- throw new ByActionStatusComponentException(componentsUtils
- .convertFromResultStatusEnum(ResultStatusEnum.INVALID_ATTRIBUTE_NAME,
- JsonPresentationFields.ATTRIBUTES));
+ log.debug("Detected attribute with invalid name '{}' during resource '{}' import. ", name, resource.getName());
+ throw new ByActionStatusComponentException(
+ componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_ATTRIBUTE_NAME, JsonPresentationFields.ATTRIBUTES));
}
final AttributeDefinition attributeDefinition = entry.getValue();
attributeDefinition.setName(name);
@@ -570,9 +494,7 @@ public class ResourceImportManager {
String derivedFrom = toscaDerivedFromElement.left().value();
log.debug("Derived from TOSCA name is {}", derivedFrom);
resource.setDerivedFrom(Arrays.asList(new String[]{derivedFrom}));
- Either<Resource, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade
- .getLatestByToscaResourceName(derivedFrom);
-
+ Either<Resource, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(derivedFrom);
if (latestByToscaResourceName.isRight()) {
StorageOperationStatus operationStatus = latestByToscaResourceName.right().value();
if (operationStatus == StorageOperationStatus.NOT_FOUND) {
@@ -580,8 +502,7 @@ public class ResourceImportManager {
}
log.debug("Error when fetching parent resource {}, error: {}", derivedFrom, operationStatus);
ActionStatus convertFromStorageResponse = componentsUtils.convertFromStorageResponse(operationStatus);
- BeEcompErrorManager.getInstance()
- .logBeComponentMissingError("Import TOSCA YAML", "resource", derivedFrom);
+ BeEcompErrorManager.getInstance().logBeComponentMissingError("Import TOSCA YAML", "resource", derivedFrom);
throw new ByActionStatusComponentException(convertFromStorageResponse, derivedFrom);
}
derivedFromResource = latestByToscaResourceName.left().value();
@@ -599,24 +520,19 @@ public class ResourceImportManager {
Iterator<Entry<String, Object>> capabilitiesNameValue = jsonCapabilities.entrySet().iterator();
Set<String> capNames = new HashSet<>();
// Getting flattened list of capabilities of parent node - cap name
+
// to cap type
Map<String, String> capName2TypeMap = getCapName2Type(parentResource);
while (capabilitiesNameValue.hasNext()) {
Entry<String, Object> capabilityNameValue = capabilitiesNameValue.next();
-
// Validating that no req/cap duplicates exist in imported YAML
String capNameLowerCase = capabilityNameValue.getKey().toLowerCase();
if (capNames.contains(capNameLowerCase)) {
- log.debug(
- "More than one capability with same name {} (case-insensitive) in imported TOSCA file is invalid",
- capNameLowerCase);
- throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "capability",
- capNameLowerCase);
+ log.debug("More than one capability with same name {} (case-insensitive) in imported TOSCA file is invalid", capNameLowerCase);
+ throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "capability", capNameLowerCase);
}
capNames.add(capNameLowerCase);
-
- CapabilityDefinition capabilityDef = createCapabilityFromImportFile(capabilityNameValue
- .getValue());
+ CapabilityDefinition capabilityDef = createCapabilityFromImportFile(capabilityNameValue.getValue());
capabilityDef.setName(capabilityNameValue.getKey());
if (moduleCapabilities.containsKey(capabilityDef.getType())) {
moduleCapabilities.get(capabilityDef.getType()).add(capabilityDef);
@@ -625,22 +541,18 @@ public class ResourceImportManager {
list.add(capabilityDef);
moduleCapabilities.put(capabilityDef.getType(), list);
}
-
// Validating against req/cap of "derived from" node
- Boolean validateVsParentCap = validateCapNameVsDerived(capName2TypeMap, capabilityDef
- .getType(), capabilityDef.getName());
-
+ Boolean validateVsParentCap = validateCapNameVsDerived(capName2TypeMap, capabilityDef.getType(), capabilityDef.getName());
if (!validateVsParentCap) {
// Here parentResource is for sure not null, so it's
+
// null-safe
+
// Check added to avoid sonar warning
String parentResourceName = parentResource != null ? parentResource.getName() : "";
- log.debug("Capability with name {} already exists in parent {}", capabilityDef.getName(),
- parentResourceName);
- throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED,
- "capability", capabilityDef
- .getName()
- .toLowerCase(), parentResourceName);
+ log.debug("Capability with name {} already exists in parent {}", capabilityDef.getName(), parentResourceName);
+ throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "capability",
+ capabilityDef.getName().toLowerCase(), parentResourceName);
}
}
if (moduleCapabilities.size() > 0) {
@@ -659,12 +571,11 @@ public class ResourceImportManager {
String nameLowerCase = capDefinition.getName().toLowerCase();
if (capName2type.get(nameLowerCase) != null) {
String parentResourceName = parentResource.getName();
- log.debug("Resource with name {} has more than one capability with name {}, ignoring case",
- parentResourceName, nameLowerCase);
- BeEcompErrorManager.getInstance()
- .logInternalDataError("Import resource", "Parent resource " + parentResourceName
- + " of imported resource has one or more capabilities with name " + nameLowerCase,
- ErrorSeverity.ERROR);
+ log.debug("Resource with name {} has more than one capability with name {}, ignoring case", parentResourceName,
+ nameLowerCase);
+ BeEcompErrorManager.getInstance().logInternalDataError("Import resource",
+ "Parent resource " + parentResourceName + " of imported resource has one or more capabilities with name "
+ + nameLowerCase, ErrorSeverity.ERROR);
throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
}
capName2type.put(nameLowerCase, capDefinition.getType());
@@ -685,12 +596,11 @@ public class ResourceImportManager {
String nameLowerCase = reqDefinition.getName().toLowerCase();
if (reqName2type.get(nameLowerCase) != null) {
String parentResourceName = parentResource.getName();
- log.debug("Resource with name {} has more than one requirement with name {}, ignoring case",
- parentResourceName, nameLowerCase);
- BeEcompErrorManager.getInstance()
- .logInternalDataError("Import resource", "Parent resource " + parentResourceName
- + " of imported resource has one or more requirements with name " + nameLowerCase,
- ErrorSeverity.ERROR);
+ log.debug("Resource with name {} has more than one requirement with name {}, ignoring case", parentResourceName,
+ nameLowerCase);
+ BeEcompErrorManager.getInstance().logInternalDataError("Import resource",
+ "Parent resource " + parentResourceName + " of imported resource has one or more requirements with name "
+ + nameLowerCase, ErrorSeverity.ERROR);
throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
}
reqName2type.put(nameLowerCase, reqDefinition.getCapability());
@@ -701,26 +611,21 @@ public class ResourceImportManager {
return reqName2type;
}
- private Boolean validateCapNameVsDerived(Map<String, String> parentCapName2Type, String childCapabilityType,
- String reqCapName) {
+ private Boolean validateCapNameVsDerived(Map<String, String> parentCapName2Type, String childCapabilityType, String reqCapName) {
String capNameLowerCase = reqCapName.toLowerCase();
log.trace("Validating capability {} vs parent resource", capNameLowerCase);
String parentCapType = parentCapName2Type.get(capNameLowerCase);
if (parentCapType != null) {
if (childCapabilityType.equals(parentCapType)) {
- log.debug(
- "Capability with name {} is of same type {} for imported resource and its parent - this is OK",
- capNameLowerCase, childCapabilityType);
+ log.debug("Capability with name {} is of same type {} for imported resource and its parent - this is OK", capNameLowerCase,
+ childCapabilityType);
return true;
}
Either<Boolean, StorageOperationStatus> capabilityTypeDerivedFrom = capabilityTypeOperation
.isCapabilityTypeDerivedFrom(childCapabilityType, parentCapType);
if (capabilityTypeDerivedFrom.isRight()) {
log.debug("Couldn't check whether imported resource capability derives from its parent's capability");
- throw new ByActionStatusComponentException(
- componentsUtils.convertFromStorageResponse(capabilityTypeDerivedFrom
- .right()
- .value()));
+ throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(capabilityTypeDerivedFrom.right().value()));
}
return capabilityTypeDerivedFrom.left().value();
}
@@ -728,9 +633,7 @@ public class ResourceImportManager {
}
private CapabilityDefinition createCapabilityFromImportFile(Object capabilityJson) {
-
CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
-
if (capabilityJson instanceof String) {
String capabilityJsonString = (String) capabilityJson;
capabilityDefinition.setType(capabilityJsonString);
@@ -738,66 +641,48 @@ public class ResourceImportManager {
Map<String, Object> capabilityJsonMap = (Map<String, Object>) capabilityJson;
// Type
if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())) {
- capabilityDefinition
- .setType((String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName()));
+ capabilityDefinition.setType((String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName()));
}
// ValidSourceTypes
if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) {
- capabilityDefinition.setValidSourceTypes(
- (List<String>) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES
- .getElementName()));
+ capabilityDefinition
+ .setValidSourceTypes((List<String>) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName()));
}
// ValidSourceTypes
if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
- capabilityDefinition.setDescription(
- (String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName()));
+ capabilityDefinition.setDescription((String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName()));
}
if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName())) {
- List<Object> occurrencesList = (List) capabilityJsonMap
- .get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName());
+ List<Object> occurrencesList = (List) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName());
validateOccurrences(occurrencesList);
capabilityDefinition.setMinOccurrences(occurrencesList.get(0).toString());
capabilityDefinition.setMaxOccurrences(occurrencesList.get(1).toString());
}
if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.PROPERTIES.getElementName())) {
-
- Either<Map<String, PropertyDefinition>, ResultStatusEnum> propertiesRes = ImportUtils
- .getProperties(capabilityJsonMap);
+ Either<Map<String, PropertyDefinition>, ResultStatusEnum> propertiesRes = ImportUtils.getProperties(capabilityJsonMap);
if (propertiesRes.isRight()) {
throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND);
} else {
- propertiesRes.left()
- .value()
- .entrySet()
- .stream()
- .forEach(e -> e.getValue().setName(e.getKey().toLowerCase()));
- List<ComponentInstanceProperty> capabilityProperties = propertiesRes.left()
- .value()
- .values()
- .stream()
- .map(p -> new ComponentInstanceProperty(p, p
- .getDefaultValue(), null))
- .collect(Collectors.toList());
+ propertiesRes.left().value().entrySet().stream().forEach(e -> e.getValue().setName(e.getKey().toLowerCase()));
+ List<ComponentInstanceProperty> capabilityProperties = propertiesRes.left().value().values().stream()
+ .map(p -> new ComponentInstanceProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList());
capabilityDefinition.setProperties(capabilityProperties);
}
}
-
} else if (!(capabilityJson instanceof List)) {
throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML);
}
return capabilityDefinition;
}
- private void handleImportResourceException(UploadResourceInfo resourceMetaData, User user, boolean isNormative,
- RuntimeException e) {
+ private void handleImportResourceException(UploadResourceInfo resourceMetaData, User user, boolean isNormative, RuntimeException e) {
ResponseFormat responseFormat;
ComponentException newException;
if (e instanceof ComponentException) {
ComponentException componentException = (ComponentException) e;
responseFormat = componentException.getResponseFormat();
if (responseFormat == null) {
- responseFormat = getResponseFormatManager()
- .getResponseFormat(componentException.getActionStatus(), componentException.getParams());
+ responseFormat = getResponseFormatManager().getResponseFormat(componentException.getActionStatus(), componentException.getParams());
}
newException = componentException;
} else {
@@ -811,8 +696,7 @@ public class ResourceImportManager {
throw newException;
}
- private void auditErrorImport(UploadResourceInfo resourceMetaData, User user, ResponseFormat errorResponseWrapper,
- boolean isNormative) {
+ private void auditErrorImport(UploadResourceInfo resourceMetaData, User user, ResponseFormat errorResponseWrapper, boolean isNormative) {
String version, lifeCycleState;
if (isNormative) {
version = TypeUtils.getFirstCertifiedVersionVersion();
@@ -820,44 +704,27 @@ public class ResourceImportManager {
} else {
version = "";
lifeCycleState = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name();
-
}
-
String message = "";
if (errorResponseWrapper.getMessageId() != null) {
message = errorResponseWrapper.getMessageId() + ": ";
}
message += errorResponseWrapper.getFormattedMessage();
-
AuditEventFactory factory = new AuditImportResourceAdminEventFactory(
- CommonAuditData.newBuilder()
- .status(errorResponseWrapper.getStatus())
- .description(message)
- .requestId(ThreadLocalsHolder.getUuid())
- .build(),
- new ResourceCommonInfo(resourceMetaData.getName(), ComponentTypeEnum.RESOURCE.getValue()),
- ResourceVersionInfo.newBuilder()
- .state(lifeCycleState)
- .version(version)
- .build(),
- ResourceVersionInfo.newBuilder()
- .state("")
- .version("")
- .build(),
- "", user, "");
+ CommonAuditData.newBuilder().status(errorResponseWrapper.getStatus()).description(message).requestId(ThreadLocalsHolder.getUuid())
+ .build(), new ResourceCommonInfo(resourceMetaData.getName(), ComponentTypeEnum.RESOURCE.getValue()),
+ ResourceVersionInfo.newBuilder().state(lifeCycleState).version(version).build(),
+ ResourceVersionInfo.newBuilder().state("").version("").build(), "", user, "");
getAuditingManager().auditEvent(factory);
-
}
private void setMetaDataFromJson(final UploadResourceInfo resourceMetaData, final Resource resource) {
this.populateResourceMetadata(resourceMetaData, resource);
resource.setCreatorUserId(resourceMetaData.getContactId());
-
final String payloadData = resourceMetaData.getPayloadData();
if (payloadData != null) {
resource.setToscaVersion(getToscaVersion(payloadData));
}
-
final List<CategoryDefinition> categories = resourceMetaData.getCategories();
calculateResourceIsAbstract(resource, categories);
}
@@ -869,8 +736,8 @@ public class ResourceImportManager {
private String getToscaVersion(final String payloadData) {
final Map<String, Object> mappedToscaTemplate = decodePayload(payloadData);
- final Either<String, ResultStatusEnum> findFirstToscaStringElement =
- ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
+ final Either<String, ResultStatusEnum> findFirstToscaStringElement = ImportUtils
+ .findFirstToscaStringElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
if (findFirstToscaStringElement.isLeft()) {
return findFirstToscaStringElement.left().value();
} else {
@@ -882,8 +749,7 @@ public class ResourceImportManager {
if (categories != null && !categories.isEmpty()) {
CategoryDefinition categoryDef = categories.get(0);
resource.setAbstract(false);
- if (categoryDef != null && categoryDef.getName() != null && categoryDef.getName()
- .equals(Constants.ABSTRACT_CATEGORY_NAME)) {
+ if (categoryDef != null && categoryDef.getName() != null && categoryDef.getName().equals(Constants.ABSTRACT_CATEGORY_NAME)) {
SubCategoryDefinition subCategoryDef = categoryDef.getSubcategories().get(0);
if (subCategoryDef != null && subCategoryDef.getName().equals(Constants.ABSTRACT_SUBCATEGORY)) {
resource.setAbstract(true);
@@ -907,16 +773,13 @@ public class ResourceImportManager {
resource.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
resource.setVendorName(ImportUtils.Constants.VENDOR_NAME);
resource.setVendorRelease(ImportUtils.Constants.VENDOR_RELEASE);
-
}
private void validateOccurrences(List<Object> occurrensesList) {
-
if (!ValidationUtils.validateListNotEmpty(occurrensesList)) {
log.debug("Occurrenses list empty");
throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
}
-
if (occurrensesList.size() < 2) {
log.debug("Occurrenses list size not 2");
throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
@@ -935,7 +798,6 @@ public class ResourceImportManager {
log.debug("Invalid occurrenses format.low_bound occurrense negative {}", minOccurrences);
throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
}
-
if (maxObj instanceof String) {
if (!"UNBOUNDED".equals(maxObj)) {
log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj);
@@ -948,10 +810,8 @@ public class ResourceImportManager {
log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj);
throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
}
-
if (maxOccurrences <= 0 || maxOccurrences < minOccurrences) {
- log.debug("Invalid occurrenses format. min occurrence is {}, Max occurrence is {}", minOccurrences,
- maxOccurrences);
+ log.debug("Invalid occurrenses format. min occurrence is {}, Max occurrence is {}", minOccurrences, maxOccurrences);
throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
}
}
@@ -980,10 +840,19 @@ public class ResourceImportManager {
return servletContext;
}
+ public void setServletContext(ServletContext servletContext) {
+ this.servletContext = servletContext;
+ }
+
public AuditingManager getAuditingManager() {
return auditingManager;
}
+ @Autowired
+ public void setAuditingManager(AuditingManager auditingManager) {
+ this.auditingManager = auditingManager;
+ }
+
public ResponseFormatManager getResponseFormatManager() {
return responseFormatManager;
}
@@ -1010,31 +879,19 @@ public class ResourceImportManager {
this.graphLockOperation = graphLockOperation;
}
- public void setServletContext(ServletContext servletContext) {
- this.servletContext = servletContext;
- }
-
- @Autowired
- public void setAuditingManager(AuditingManager auditingManager) {
- this.auditingManager = auditingManager;
- }
-
private List<DataTypeDefinition> extractDataTypeFromJson(final ResourceBusinessLogic resourceBusinessLogic,
final Map<String, Object> foundElements) {
final List<DataTypeDefinition> dataTypeDefinitionList = new ArrayList<>();
if (MapUtils.isNotEmpty(foundElements)) {
- final Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypeCacheAll =
- resourceBusinessLogic.dataTypeCache.getAll();
+ final Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypeCacheAll = resourceBusinessLogic.dataTypeCache.getAll();
if (dataTypeCacheAll.isLeft()) {
for (final Entry<String, Object> attributeNameValue : foundElements.entrySet()) {
final Object value = attributeNameValue.getValue();
if (value instanceof Map) {
- final DataTypeDefinition dataTypeDefinition =
- createDataTypeDefinitionWithName(attributeNameValue);
- final DataTypeDefinition dataTypeDefinitionParent =
- dataTypeCacheAll.left().value().get(dataTypeDefinition.getDerivedFromName());
+ final DataTypeDefinition dataTypeDefinition = createDataTypeDefinitionWithName(attributeNameValue);
+ final DataTypeDefinition dataTypeDefinitionParent = dataTypeCacheAll.left().value()
+ .get(dataTypeDefinition.getDerivedFromName());
dataTypeDefinition.setDerivedFrom(dataTypeDefinitionParent);
-
dataTypeDefinitionList.add(dataTypeDefinition);
} else {
dataTypeDefinitionList.add(createDataType(String.valueOf(value)));
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java
index 2cb03fe2ed..875bcb214c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import org.openecomp.sdc.be.config.ConfigurationManager;
@@ -33,9 +32,9 @@ import org.openecomp.sdc.exception.ServiceException;
public class ResponseFormatManager {
+ private static final Logger log = Logger.getLogger(ResponseFormatManager.class);
private volatile static ResponseFormatManager instance;
private static ConfigurationManager configurationManager;
- private static final Logger log = Logger.getLogger(ResponseFormatManager.class);
public static ResponseFormatManager getInstance() {
if (instance == null) {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java
index ad1f818da6..a87fdb6ca7 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java
@@ -19,7 +19,6 @@
* Modifications copyright (c) 2019 Nokia
* ================================================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
@@ -165,10 +164,10 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.context.WebApplicationContext;
-
@org.springframework.stereotype.Component("serviceBusinessLogic")
public class ServiceBusinessLogic extends ComponentBusinessLogic {
+ static final String IS_VALID = "isValid";
private static final String THE_SERVICE_WITH_SYSTEM_NAME_LOCKED = "The service with system name {} locked. ";
private static final String FAILED_TO_LOCK_SERVICE_RESPONSE_IS = "Failed to lock service {}. Response is {}. ";
private static final String AUDIT_BEFORE_SENDING_RESPONSE = "audit before sending response";
@@ -176,71 +175,40 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
private static final String INITIAL_VERSION = "0.1";
private static final String STATUS_SUCCESS_200 = "200";
private static final String STATUS_DEPLOYED = "DEPLOYED";
- static final String IS_VALID = "isValid";
private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
-
- private ForwardingPathOperation forwardingPathOperation;
- private AuditCassandraDao auditCassandraDao;
-
private final IDistributionEngine distributionEngine;
private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
private final ServiceDistributionValidation serviceDistributionValidation;
private final ForwardingPathValidator forwardingPathValidator;
private final UiComponentDataConverter uiComponentDataConverter;
-
+ private ForwardingPathOperation forwardingPathOperation;
+ private AuditCassandraDao auditCassandraDao;
private ServiceTypeValidator serviceTypeValidator;
private List<ServiceCreationPlugin> serviceCreationPluginList;
-
- @Autowired
- public void setServiceTypeValidator(ServiceTypeValidator serviceTypeValidator) {
- this.serviceTypeValidator = serviceTypeValidator;
- }
-
-
private ServiceFunctionValidator serviceFunctionValidator;
-
- @Autowired
- public void setServiceFunctionValidator(ServiceFunctionValidator serviceFunctionValidator) {
- this.serviceFunctionValidator = serviceFunctionValidator;
- }
-
@Autowired
private ServiceRoleValidator serviceRoleValidator;
-
@Autowired
private ServiceInstantiationTypeValidator serviceInstantiationTypeValidator;
-
@Autowired
private ServiceCategoryValidator serviceCategoryValidator;
-
@Autowired
private ServiceValidator serviceValidator;
-
@Autowired
- public ServiceBusinessLogic(IElementOperation elementDao,
- IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation,
- IGroupTypeOperation groupTypeOperation,
- GroupBusinessLogic groupBusinessLogic,
- InterfaceOperation interfaceOperation,
- InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
- ArtifactsBusinessLogic artifactsBusinessLogic,
+ public ServiceBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+ IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic, InterfaceOperation interfaceOperation,
+ InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsBusinessLogic artifactsBusinessLogic,
IDistributionEngine distributionEngine, ComponentInstanceBusinessLogic componentInstanceBusinessLogic,
ServiceDistributionValidation serviceDistributionValidation, ForwardingPathValidator forwardingPathValidator,
- UiComponentDataConverter uiComponentDataConverter,
- ArtifactsOperations artifactToscaOperation,
- ComponentContactIdValidator componentContactIdValidator,
- ComponentNameValidator componentNameValidator,
- ComponentTagsValidator componentTagsValidator,
- ComponentValidator componentValidator,
- ComponentIconValidator componentIconValidator,
- ComponentProjectCodeValidator componentProjectCodeValidator,
+ UiComponentDataConverter uiComponentDataConverter, ArtifactsOperations artifactToscaOperation,
+ ComponentContactIdValidator componentContactIdValidator, ComponentNameValidator componentNameValidator,
+ ComponentTagsValidator componentTagsValidator, ComponentValidator componentValidator,
+ ComponentIconValidator componentIconValidator, ComponentProjectCodeValidator componentProjectCodeValidator,
ComponentDescriptionValidator componentDescriptionValidator) {
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic,
- interfaceOperation, interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, componentContactIdValidator,
- componentNameValidator, componentTagsValidator, componentValidator,
- componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator);
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic, interfaceOperation,
+ interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, componentContactIdValidator, componentNameValidator,
+ componentTagsValidator, componentValidator, componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator);
this.distributionEngine = distributionEngine;
this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
this.serviceDistributionValidation = serviceDistributionValidation;
@@ -248,12 +216,20 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
this.uiComponentDataConverter = uiComponentDataConverter;
}
+ @Autowired
+ public void setServiceTypeValidator(ServiceTypeValidator serviceTypeValidator) {
+ this.serviceTypeValidator = serviceTypeValidator;
+ }
+
+ @Autowired
+ public void setServiceFunctionValidator(ServiceFunctionValidator serviceFunctionValidator) {
+ this.serviceFunctionValidator = serviceFunctionValidator;
+ }
public Either<List<Map<String, Object>>, ResponseFormat> getComponentAuditRecords(String componentVersion, String componentUUID, String userId) {
validateUserExists(userId);
Either<List<Map<String, Object>>, ActionStatus> result;
try {
-
// Certified Version
if (componentVersion.endsWith(".0")) {
Either<List<ResourceAdminEvent>, ActionStatus> eitherAuditingForCertified = auditCassandraDao.getByServiceInstanceId(componentUUID);
@@ -271,229 +247,154 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
log.debug("get Audit Records failed with exception {}", e);
result = Either.right(ActionStatus.GENERAL_ERROR);
}
-
if (result.isRight()) {
return Either.right(componentsUtils.getResponseFormat(result.right().value()));
} else {
return Either.left(result.left().value());
}
-
}
- public Either<List<Operation>, ResponseFormat> addServiceConsumptionData(String serviceId,
- String serviceInstanceId,
- String operationId,
- List<ServiceConsumptionData> serviceConsumptionDataList,
- String userId) {
+ public Either<List<Operation>, ResponseFormat> addServiceConsumptionData(String serviceId, String serviceInstanceId, String operationId,
+ List<ServiceConsumptionData> serviceConsumptionDataList, String userId) {
List<Operation> operationList = new ArrayList<>();
-
- Either<Service, StorageOperationStatus> serviceEither =
- toscaOperationFacade.getToscaElement(serviceId);
- if(serviceEither.isRight()) {
- return Either.right(componentsUtils.getResponseFormat
- (serviceEither.right().value()));
+ Either<Service, StorageOperationStatus> serviceEither = toscaOperationFacade.getToscaElement(serviceId);
+ if (serviceEither.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(serviceEither.right().value()));
}
-
Service service = serviceEither.left().value();
-
-
- StorageOperationStatus storageOperationStatus =
- graphLockOperation.lockComponent(service.getUniqueId(), NodeTypeEnum.Service);
+ StorageOperationStatus storageOperationStatus = graphLockOperation.lockComponent(service.getUniqueId(), NodeTypeEnum.Service);
if (storageOperationStatus != StorageOperationStatus.OK) {
return Either.right(componentsUtils.getResponseFormat(storageOperationStatus));
}
-
try {
for (ServiceConsumptionData serviceConsumptionData : serviceConsumptionDataList) {
- Either<Operation, ResponseFormat> operationEither =
- addPropertyServiceConsumption(serviceId, serviceInstanceId, operationId,
- userId, serviceConsumptionData);
-
+ Either<Operation, ResponseFormat> operationEither = addPropertyServiceConsumption(serviceId, serviceInstanceId, operationId, userId,
+ serviceConsumptionData);
if (operationEither.isRight()) {
return Either.right(operationEither.right().value());
}
-
operationList.add(operationEither.left().value());
}
-
janusGraphDao.commit();
return Either.left(operationList);
} catch (Exception e) {
janusGraphDao.rollback();
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-
} finally {
graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service);
-
}
}
- public Either <Operation, ResponseFormat> addPropertyServiceConsumption(String serviceId,
- String serviceInstanceId,
- String operationId,
- String userId,
- ServiceConsumptionData serviceConsumptionData) {
+ public Either<Operation, ResponseFormat> addPropertyServiceConsumption(String serviceId, String serviceInstanceId, String operationId,
+ String userId, ServiceConsumptionData serviceConsumptionData) {
validateUserExists(userId);
-
- Either<Service, StorageOperationStatus> serviceEither =
- toscaOperationFacade.getToscaElement(serviceId);
- if(serviceEither.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(serviceEither.right
- ().value()));
+ Either<Service, StorageOperationStatus> serviceEither = toscaOperationFacade.getToscaElement(serviceId);
+ if (serviceEither.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(serviceEither.right().value()));
}
-
Service parentService = serviceEither.left().value();
-
List<ComponentInstance> componentInstances = parentService.getComponentInstances();
- if(CollectionUtils.isEmpty(componentInstances)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus
- .INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
+ if (CollectionUtils.isEmpty(componentInstances)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
}
-
- Optional<ComponentInstance> serviceInstanceCandidate =
- componentInstances.stream().filter(instance -> instance.getUniqueId().equals
- (serviceInstanceId)).findAny();
-
- if(!serviceInstanceCandidate.isPresent()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus
- .INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
+ Optional<ComponentInstance> serviceInstanceCandidate = componentInstances.stream()
+ .filter(instance -> instance.getUniqueId().equals(serviceInstanceId)).findAny();
+ if (!serviceInstanceCandidate.isPresent()) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
}
-
- Map<String, List<ComponentInstanceInterface>> componentInstancesInterfaces =
- parentService.getComponentInstancesInterfaces();
- if(MapUtils.isEmpty(componentInstancesInterfaces)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus
- .INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
+ Map<String, List<ComponentInstanceInterface>> componentInstancesInterfaces = parentService.getComponentInstancesInterfaces();
+ if (MapUtils.isEmpty(componentInstancesInterfaces)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
}
-
List<InterfaceDefinition> interfaces = new ArrayList<>();
- for(ComponentInstanceInterface componentInstanceInterface :
- componentInstancesInterfaces.get(serviceInstanceId)) {
+ for (ComponentInstanceInterface componentInstanceInterface : componentInstancesInterfaces.get(serviceInstanceId)) {
interfaces.add(componentInstanceInterface);
}
-
ComponentInstance serviceInstance = serviceInstanceCandidate.get();
- Optional<InterfaceDefinition> interfaceCandidate = InterfaceOperationUtils
- .getInterfaceDefinitionFromOperationId(interfaces, operationId);
-
- if(!interfaceCandidate.isPresent()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus
- .INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
+ Optional<InterfaceDefinition> interfaceCandidate = InterfaceOperationUtils.getInterfaceDefinitionFromOperationId(interfaces, operationId);
+ if (!interfaceCandidate.isPresent()) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
}
-
InterfaceDefinition interfaceDefinition = interfaceCandidate.get();
Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
- if(MapUtils.isEmpty(operations)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus
- .INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
+ if (MapUtils.isEmpty(operations)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
}
-
Operation operation = operations.get(operationId);
Either<Operation, ResponseFormat> operationEither = Either.left(operation);
-
ListDataDefinition<OperationInputDefinition> inputs = operation.getInputs();
- Optional<OperationInputDefinition> inputCandidate =
- getOperationInputByInputId(serviceConsumptionData, inputs);
-
- if(!inputCandidate.isPresent()) {
+ Optional<OperationInputDefinition> inputCandidate = getOperationInputByInputId(serviceConsumptionData, inputs);
+ if (!inputCandidate.isPresent()) {
return Either.right(new ResponseFormat(HttpStatus.NOT_FOUND.value()));
}
-
OperationInputDefinition operationInputDefinition = inputCandidate.get();
// add data to operation
-
- if(Objects.nonNull(serviceConsumptionData.getValue())) {
- operationEither =
- handleConsumptionValue(parentService, serviceInstanceId, serviceConsumptionData, operation,
- operationInputDefinition);
+ if (Objects.nonNull(serviceConsumptionData.getValue())) {
+ operationEither = handleConsumptionValue(parentService, serviceInstanceId, serviceConsumptionData, operation, operationInputDefinition);
}
-
- if(operationEither.isRight()) {
+ if (operationEither.isRight()) {
return Either.right(operationEither.right().value());
}
-
Operation updatedOperation = operationEither.left().value();
operations.remove(operationId);
operations.put(operationId, updatedOperation);
interfaceDefinition.setOperationsMap(operations);
-
parentService.getComponentInstances().remove(serviceInstance);
- if(CollectionUtils.isEmpty(parentService.getComponentInstances())) {
+ if (CollectionUtils.isEmpty(parentService.getComponentInstances())) {
parentService.setComponentInstances(new ArrayList<>());
}
-
Map<String, Object> instanceInterfaces =
- MapUtils.isEmpty(serviceInstance.getInterfaces())? new HashMap<>() : serviceInstance.getInterfaces();
+ MapUtils.isEmpty(serviceInstance.getInterfaces()) ? new HashMap<>() : serviceInstance.getInterfaces();
instanceInterfaces.remove(interfaceDefinition.getUniqueId());
instanceInterfaces.put(interfaceDefinition.getUniqueId(), interfaceDefinition);
serviceInstance.setInterfaces(instanceInterfaces);
-
removeComponentInstanceInterfaceByInterfaceId(interfaceDefinition.getUniqueId(), componentInstancesInterfaces.get(serviceInstanceId));
- componentInstancesInterfaces.get(serviceInstanceId).add(new ComponentInstanceInterface(interfaceDefinition.getUniqueId(), interfaceDefinition));
-
+ componentInstancesInterfaces.get(serviceInstanceId)
+ .add(new ComponentInstanceInterface(interfaceDefinition.getUniqueId(), interfaceDefinition));
parentService.getComponentInstances().add(serviceInstance);
-
StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceInterfaces(parentService, serviceInstanceId);
-
- if(status != StorageOperationStatus.OK) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus
- .INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
+ if (status != StorageOperationStatus.OK) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
}
-
return Either.left(operation);
}
- private void removeComponentInstanceInterfaceByInterfaceId(String interfaceIdToRemove,
- List<ComponentInstanceInterface> instanceInterfaces) {
- if(CollectionUtils.isEmpty(instanceInterfaces)) {
+ private void removeComponentInstanceInterfaceByInterfaceId(String interfaceIdToRemove, List<ComponentInstanceInterface> instanceInterfaces) {
+ if (CollectionUtils.isEmpty(instanceInterfaces)) {
return;
}
-
- Optional<ComponentInstanceInterface> interfaceToRemove =
- instanceInterfaces.stream().filter(instInterface -> instInterface.getUniqueId().equals
- (interfaceIdToRemove)).findAny();
-
- if(interfaceToRemove.isPresent()) {
+ Optional<ComponentInstanceInterface> interfaceToRemove = instanceInterfaces.stream()
+ .filter(instInterface -> instInterface.getUniqueId().equals(interfaceIdToRemove)).findAny();
+ if (interfaceToRemove.isPresent()) {
instanceInterfaces.remove(interfaceToRemove.get());
}
-
}
- private Either<Operation, ResponseFormat> handleConsumptionValue(Service containerService,
- String serviceInstanceId,
- ServiceConsumptionData serviceConsumptionData,
- Operation operation,
- OperationInputDefinition
- operationInputDefinition) {
+ private Either<Operation, ResponseFormat> handleConsumptionValue(Service containerService, String serviceInstanceId,
+ ServiceConsumptionData serviceConsumptionData, Operation operation,
+ OperationInputDefinition operationInputDefinition) {
String source = serviceConsumptionData.getSource();
String consumptionValue = serviceConsumptionData.getValue();
String type = serviceConsumptionData.getType();
- String operationIdentifier = consumptionValue.contains(".")
- ? consumptionValue.substring(0, consumptionValue.lastIndexOf('.'))
- : consumptionValue;
-
+ String operationIdentifier =
+ consumptionValue.contains(".") ? consumptionValue.substring(0, consumptionValue.lastIndexOf('.')) : consumptionValue;
ServiceConsumptionSource sourceValue = ServiceConsumptionSource.getSourceValue(source);
-
- if(STATIC.equals(sourceValue)) {
+ if (STATIC.equals(sourceValue)) {
// Validate constraint on input value
- Either<Boolean, ResponseFormat> constraintValidationResult =
- validateOperationInputConstraint(operationInputDefinition, consumptionValue, type);
-
+ Either<Boolean, ResponseFormat> constraintValidationResult = validateOperationInputConstraint(operationInputDefinition, consumptionValue,
+ type);
if (constraintValidationResult.isRight()) {
return Either.right(constraintValidationResult.right().value());
}
- return handleConsumptionStaticValue(consumptionValue, type, operation,
- operationInputDefinition);
+ return handleConsumptionStaticValue(consumptionValue, type, operation, operationInputDefinition);
}
-
if (Objects.isNull(sourceValue)) {
List<PropertyDefinition> propertyDefinitions;
Map<String, List<CapabilityDefinition>> capabilities = null;
String componentName;
List<OperationOutputDefinition> outputs = null;
if (source.equals(containerService.getUniqueId())) {
- Either<Service, StorageOperationStatus> serviceToTakePropEither =
- toscaOperationFacade.getToscaElement(source);
+ Either<Service, StorageOperationStatus> serviceToTakePropEither = toscaOperationFacade.getToscaElement(source);
if (serviceToTakePropEither.isRight()) {
return Either.right(componentsUtils.getResponseFormat(serviceToTakePropEither.right().value()));
}
@@ -502,13 +403,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
sourceValue = SERVICE_INPUT;
propertyDefinitions = service.getProperties();
componentName = service.getName();
- outputs = InterfaceOperationUtils.getOtherOperationOutputsOfComponent(operationIdentifier,
- service.getInterfaces()).getListToscaDataDefinition();
+ outputs = InterfaceOperationUtils.getOtherOperationOutputsOfComponent(operationIdentifier, service.getInterfaces())
+ .getListToscaDataDefinition();
} else {
Optional<ComponentInstance> getComponentInstance = containerService.getComponentInstanceById(source);
- if(!getComponentInstance.isPresent()){
- return Either.right(componentsUtils.getResponseFormat(
- ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, source));
+ if (!getComponentInstance.isPresent()) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, source));
}
ComponentInstance componentInstance = getComponentInstance.get();
operationInputDefinition.setSource(componentInstance.getUniqueId());
@@ -516,185 +416,143 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
capabilities = componentInstance.getCapabilities();
componentName = source.equals(serviceInstanceId) ? SELF : componentInstance.getName();
if (MapUtils.isNotEmpty(componentInstance.getInterfaces())) {
- Map<String, InterfaceDataDefinition> componentInstanceInterfaces =
- componentInstance.getInterfaces().entrySet().stream()
- .collect(Collectors.toMap((Map.Entry::getKey),
- (interfaceEntry -> (InterfaceDataDefinition) interfaceEntry.getValue())));
- outputs = InterfaceOperationUtils.getOtherOperationOutputsOfComponent(operationIdentifier,
- componentInstanceInterfaces).getListToscaDataDefinition();
+ Map<String, InterfaceDataDefinition> componentInstanceInterfaces = componentInstance.getInterfaces().entrySet().stream()
+ .collect(Collectors.toMap((Map.Entry::getKey), (interfaceEntry -> (InterfaceDataDefinition) interfaceEntry.getValue())));
+ outputs = InterfaceOperationUtils.getOtherOperationOutputsOfComponent(operationIdentifier, componentInstanceInterfaces)
+ .getListToscaDataDefinition();
}
}
-
- if(sourceValue == ServiceConsumptionSource.SERVICE_INPUT) {
+ if (sourceValue == ServiceConsumptionSource.SERVICE_INPUT) {
//The operation input in service consumption has been mapped to an input in the parent service
- return handleConsumptionInputValue(consumptionValue, containerService, operation,
- operationInputDefinition);
+ return handleConsumptionInputValue(consumptionValue, containerService, operation, operationInputDefinition);
}
- return handleConsumptionPropertyValue(operation, operationInputDefinition,
- serviceConsumptionData, propertyDefinitions, capabilities, outputs, componentName);
+ return handleConsumptionPropertyValue(operation, operationInputDefinition, serviceConsumptionData, propertyDefinitions, capabilities,
+ outputs, componentName);
}
-
operationInputDefinition.setToscaPresentationValue(JsonPresentationFields.SOURCE, source);
operationInputDefinition.setSource(source);
-
return Either.left(operation);
}
private Optional<OperationInputDefinition> getOperationInputByInputId(ServiceConsumptionData serviceConsumptionData,
ListDataDefinition<OperationInputDefinition> inputs) {
-
- if(CollectionUtils.isEmpty(inputs.getListToscaDataDefinition())) {
+ if (CollectionUtils.isEmpty(inputs.getListToscaDataDefinition())) {
return Optional.empty();
}
-
- return inputs.getListToscaDataDefinition().stream().filter(operationInput -> operationInput.getInputId().equals
- (serviceConsumptionData.getInputId()))
- .findAny();
+ return inputs.getListToscaDataDefinition().stream()
+ .filter(operationInput -> operationInput.getInputId().equals(serviceConsumptionData.getInputId())).findAny();
}
- private Either<Operation, ResponseFormat> handleConsumptionPropertyValue(
- Operation operation, OperationInputDefinition operationInputDefinition,
- ServiceConsumptionData serviceConsumptionData, List<PropertyDefinition> properties,Map<String,
- List<CapabilityDefinition>> capabilities,
- List<OperationOutputDefinition> outputs, String componentName) {
-
+ private Either<Operation, ResponseFormat> handleConsumptionPropertyValue(Operation operation, OperationInputDefinition operationInputDefinition,
+ ServiceConsumptionData serviceConsumptionData,
+ List<PropertyDefinition> properties,
+ Map<String, List<CapabilityDefinition>> capabilities,
+ List<OperationOutputDefinition> outputs, String componentName) {
if (CollectionUtils.isEmpty(properties) && CollectionUtils.isEmpty(outputs)) {
return Either.left(operation);
}
String consumptionValue = serviceConsumptionData.getValue();
-
- if (CollectionUtils.isNotEmpty(outputs)
- && isOperationInputMappedToOtherOperationOutput(getOperationOutputName(consumptionValue), outputs)) {
- return handleConsumptionInputMappedToOperationOutput(operation, operationInputDefinition, outputs,
- consumptionValue, componentName);
+ if (CollectionUtils.isNotEmpty(outputs) && isOperationInputMappedToOtherOperationOutput(getOperationOutputName(consumptionValue), outputs)) {
+ return handleConsumptionInputMappedToOperationOutput(operation, operationInputDefinition, outputs, consumptionValue, componentName);
}
-
if (CollectionUtils.isNotEmpty(properties) && PropertiesUtils.isNodeProperty(consumptionValue, properties)) {
- return handleConsumptionInputMappedToProperty(operation, operationInputDefinition, serviceConsumptionData,
- properties, componentName);
+ return handleConsumptionInputMappedToProperty(operation, operationInputDefinition, serviceConsumptionData, properties, componentName);
}
-
if (MapUtils.isNotEmpty(capabilities)) {
- return handleConsumptionInputMappedToCapabilityProperty(operation, operationInputDefinition,
- serviceConsumptionData, capabilities, componentName);
+ return handleConsumptionInputMappedToCapabilityProperty(operation, operationInputDefinition, serviceConsumptionData, capabilities,
+ componentName);
}
-
return Either.left(operation);
}
private Either<Operation, ResponseFormat> handleConsumptionInputMappedToProperty(Operation operation,
- OperationInputDefinition operationInputDefinition, ServiceConsumptionData serviceConsumptionData,
+ OperationInputDefinition operationInputDefinition,
+ ServiceConsumptionData serviceConsumptionData,
List<PropertyDefinition> properties, String componentName) {
- Optional<PropertyDefinition> servicePropertyCandidate =
- properties.stream().filter(property -> property.getName()
- .equals(serviceConsumptionData.getValue())).findAny();
-
+ Optional<PropertyDefinition> servicePropertyCandidate = properties.stream()
+ .filter(property -> property.getName().equals(serviceConsumptionData.getValue())).findAny();
if (servicePropertyCandidate.isPresent()) {
- boolean isInputTypeSimilarToOperation =
- isAssignedValueFromValidType(operationInputDefinition.getType(),
- servicePropertyCandidate.get());
-
+ boolean isInputTypeSimilarToOperation = isAssignedValueFromValidType(operationInputDefinition.getType(), servicePropertyCandidate.get());
if (!isInputTypeSimilarToOperation) {
- return Either.right(componentsUtils.getResponseFormat(
- ActionStatus.INVALID_CONSUMPTION_TYPE, operationInputDefinition.getType()));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONSUMPTION_TYPE, operationInputDefinition.getType()));
}
-
- addPropertyToInputValue(componentName, operation, operationInputDefinition,
- servicePropertyCandidate.get());
+ addPropertyToInputValue(componentName, operation, operationInputDefinition, servicePropertyCandidate.get());
}
return Either.left(operation);
}
private Either<Operation, ResponseFormat> handleConsumptionInputMappedToOperationOutput(Operation operation,
- OperationInputDefinition operationInputDefinition, List<OperationOutputDefinition> outputs,
+ OperationInputDefinition operationInputDefinition,
+ List<OperationOutputDefinition> outputs,
String consumptionValue, String componentName) {
String outputName = getOperationOutputName(consumptionValue);
- Optional<OperationOutputDefinition> servicePropertyOutputCandidate = outputs.stream()
- .filter(output -> output.getName().equals(outputName)).findAny();
+ Optional<OperationOutputDefinition> servicePropertyOutputCandidate = outputs.stream().filter(output -> output.getName().equals(outputName))
+ .findAny();
if (servicePropertyOutputCandidate.isPresent()) {
- boolean isInputTypeSimilarToOperation =
- isAssignedValueFromValidType(operationInputDefinition.getType(),
- servicePropertyOutputCandidate.get());
+ boolean isInputTypeSimilarToOperation = isAssignedValueFromValidType(operationInputDefinition.getType(),
+ servicePropertyOutputCandidate.get());
if (!isInputTypeSimilarToOperation) {
- return Either.right(componentsUtils.getResponseFormat(
- ActionStatus.INVALID_CONSUMPTION_TYPE, operationInputDefinition.getType()));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONSUMPTION_TYPE, operationInputDefinition.getType()));
}
addOutputToInputValue(componentName, consumptionValue, operation, operationInputDefinition);
}
return Either.left(operation);
}
- private void addPropertyToInputValue(String componentName, Operation operation,
- OperationInputDefinition operationInputDefinition,
+ private void addPropertyToInputValue(String componentName, Operation operation, OperationInputDefinition operationInputDefinition,
PropertyDefinition serviceProperty) {
Map<String, List<String>> getProperty = new HashMap<>();
List<String> getPropertyValues = new ArrayList<>();
getPropertyValues.add(componentName);
getPropertyValues.add(serviceProperty.getName());
getProperty.put(ToscaFunctions.GET_PROPERTY.getFunctionName(), getPropertyValues);
-
operationInputDefinition.setSourceProperty(serviceProperty.getUniqueId());
operation.getInputs().delete(operationInputDefinition);
- operationInputDefinition.setToscaPresentationValue(JsonPresentationFields.GET_PROPERTY,
- getPropertyValues);
+ operationInputDefinition.setToscaPresentationValue(JsonPresentationFields.GET_PROPERTY, getPropertyValues);
operationInputDefinition.setValue((new Gson()).toJson(getProperty));
operation.getInputs().add(operationInputDefinition);
}
- private void addOutputToInputValue(String componentName, String consumptionValue,
- Operation operation, OperationInputDefinition operationInputDefinition) {
- Map<String, List<String>> getOperationOutput =
- InterfaceOperationUtils.createMappedOutputDefaultValue(componentName, consumptionValue);
+ private void addOutputToInputValue(String componentName, String consumptionValue, Operation operation,
+ OperationInputDefinition operationInputDefinition) {
+ Map<String, List<String>> getOperationOutput = InterfaceOperationUtils.createMappedOutputDefaultValue(componentName, consumptionValue);
operation.getInputs().delete(operationInputDefinition);
- operationInputDefinition.setToscaPresentationValue(JsonPresentationFields.GET_OPERATION_OUTPUT,
- getOperationOutput);
+ operationInputDefinition.setToscaPresentationValue(JsonPresentationFields.GET_OPERATION_OUTPUT, getOperationOutput);
operationInputDefinition.setValue((new Gson()).toJson(getOperationOutput));
operation.getInputs().add(operationInputDefinition);
}
- public Either<Operation, ResponseFormat> handleConsumptionStaticValue(String value, String type,
- Operation operation,
- OperationInputDefinition
- operationInputDefinition) {
- boolean isInputTypeSimilarToOperation =
- isAssignedValueFromValidType(type, value);
-
- if(!isInputTypeSimilarToOperation) {
- return Either.right(componentsUtils.getResponseFormat(
- ActionStatus.INVALID_CONSUMPTION_TYPE, type));
+ public Either<Operation, ResponseFormat> handleConsumptionStaticValue(String value, String type, Operation operation,
+ OperationInputDefinition operationInputDefinition) {
+ boolean isInputTypeSimilarToOperation = isAssignedValueFromValidType(type, value);
+ if (!isInputTypeSimilarToOperation) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONSUMPTION_TYPE, type));
+ }
+ //Validate Constraint and Value
+ Either<Boolean, ResponseFormat> constraintValidationResponse = validateOperationInputConstraint(operationInputDefinition, value, type);
+ if (constraintValidationResponse.isRight()) {
+ return Either.right(constraintValidationResponse.right().value());
}
-
- //Validate Constraint and Value
- Either<Boolean, ResponseFormat> constraintValidationResponse =
- validateOperationInputConstraint(operationInputDefinition, value, type);
- if(constraintValidationResponse.isRight()) {
- return Either.right(constraintValidationResponse.right().value());
- }
-
addStaticValueToInputOperation(value, operation, operationInputDefinition);
-
return Either.left(operation);
}
- private Either<Boolean, ResponseFormat> validateOperationInputConstraint(
- OperationInputDefinition operationInputDefinition, String value, String type) {
- ComponentInstanceProperty propertyDefinition = new ComponentInstanceProperty();
- propertyDefinition.setType(operationInputDefinition.getParentPropertyType());
-
- InputDefinition inputDefinition = new InputDefinition();
- inputDefinition.setDefaultValue(value);
- inputDefinition.setInputPath(operationInputDefinition.getSubPropertyInputPath());
- inputDefinition.setType(type);
- if (Objects.nonNull(operationInputDefinition.getParentPropertyType())) {
- inputDefinition.setProperties(Collections.singletonList(propertyDefinition));
- }
-
- return PropertyValueConstraintValidationUtil.getInstance()
- .validatePropertyConstraints(Collections.singletonList(inputDefinition), applicationDataTypeCache);
- }
+ private Either<Boolean, ResponseFormat> validateOperationInputConstraint(OperationInputDefinition operationInputDefinition, String value,
+ String type) {
+ ComponentInstanceProperty propertyDefinition = new ComponentInstanceProperty();
+ propertyDefinition.setType(operationInputDefinition.getParentPropertyType());
+ InputDefinition inputDefinition = new InputDefinition();
+ inputDefinition.setDefaultValue(value);
+ inputDefinition.setInputPath(operationInputDefinition.getSubPropertyInputPath());
+ inputDefinition.setType(type);
+ if (Objects.nonNull(operationInputDefinition.getParentPropertyType())) {
+ inputDefinition.setProperties(Collections.singletonList(propertyDefinition));
+ }
+ return PropertyValueConstraintValidationUtil.getInstance()
+ .validatePropertyConstraints(Collections.singletonList(inputDefinition), applicationDataTypeCache);
+ }
- private void addStaticValueToInputOperation(String value, Operation operation,
- OperationInputDefinition operationInputDefinition) {
+ private void addStaticValueToInputOperation(String value, Operation operation, OperationInputDefinition operationInputDefinition) {
operation.getInputs().delete(operationInputDefinition);
operationInputDefinition.setSource(STATIC.getSource());
operationInputDefinition.setSourceProperty(null);
@@ -702,31 +560,21 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
operation.getInputs().add(operationInputDefinition);
}
- private Either<Operation, ResponseFormat> handleConsumptionInputValue(String inputId,
- Service service,
- Operation operation,
- OperationInputDefinition
- operationInputDefinition) {
+ private Either<Operation, ResponseFormat> handleConsumptionInputValue(String inputId, Service service, Operation operation,
+ OperationInputDefinition operationInputDefinition) {
List<InputDefinition> serviceInputs = service.getInputs();
- Optional<InputDefinition> inputForValue =
- serviceInputs.stream().filter(input -> input.getUniqueId().contains(inputId)).findAny();
-
- if(inputForValue.isPresent()) {
- boolean isInputTypeSimilarToOperation =
- isAssignedValueFromValidType(operationInputDefinition.getType(), inputForValue.get());
-
- if(!isInputTypeSimilarToOperation) {
- return Either.right(componentsUtils.getResponseFormat(
- ActionStatus.INVALID_CONSUMPTION_TYPE, operationInputDefinition.getType()));
+ Optional<InputDefinition> inputForValue = serviceInputs.stream().filter(input -> input.getUniqueId().contains(inputId)).findAny();
+ if (inputForValue.isPresent()) {
+ boolean isInputTypeSimilarToOperation = isAssignedValueFromValidType(operationInputDefinition.getType(), inputForValue.get());
+ if (!isInputTypeSimilarToOperation) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONSUMPTION_TYPE, operationInputDefinition.getType()));
}
addGetInputValueToOperationInput(operation, operationInputDefinition, inputForValue.get());
}
-
return Either.left(operation);
}
- private void addGetInputValueToOperationInput(Operation operation,
- OperationInputDefinition operationInputDefinition,
+ private void addGetInputValueToOperationInput(Operation operation, OperationInputDefinition operationInputDefinition,
InputDefinition inputForValue) {
operation.getInputs().delete(operationInputDefinition);
Map<String, String> getInputMap = new HashMap<>();
@@ -739,38 +587,31 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
private Either<List<Map<String, Object>>, ActionStatus> getAuditRecordsForUncertifiedComponent(String componentUUID, String componentVersion) {
// First Query
- Either<List<ResourceAdminEvent>, ActionStatus> eitherprevVerAudit = auditCassandraDao.getAuditByServiceIdAndPrevVersion(componentUUID, componentVersion);
-
+ Either<List<ResourceAdminEvent>, ActionStatus> eitherprevVerAudit = auditCassandraDao
+ .getAuditByServiceIdAndPrevVersion(componentUUID, componentVersion);
if (eitherprevVerAudit.isRight()) {
return Either.right(eitherprevVerAudit.right().value());
}
-
// Second Query
- Either<List<ResourceAdminEvent>, ActionStatus> eitherCurrVerAudit = auditCassandraDao.getAuditByServiceIdAndCurrVersion(componentUUID, componentVersion);
+ Either<List<ResourceAdminEvent>, ActionStatus> eitherCurrVerAudit = auditCassandraDao
+ .getAuditByServiceIdAndCurrVersion(componentUUID, componentVersion);
if (eitherCurrVerAudit.isRight()) {
return Either.right(eitherCurrVerAudit.right().value());
}
-
-
Either<List<ResourceAdminEvent>, ActionStatus> eitherArchiveRestoreList = getArchiveRestoreEventList(componentUUID);
if (eitherArchiveRestoreList.isRight()) {
return Either.right(eitherArchiveRestoreList.right().value());
}
-
List<Map<String, Object>> prevVerAuditList = getAuditingFieldsList(eitherprevVerAudit.left().value());
List<Map<String, Object>> currVerAuditList = getAuditingFieldsList(eitherCurrVerAudit.left().value());
-
List<Map<String, Object>> duplicateElements = new ArrayList<>();
duplicateElements.addAll(prevVerAuditList);
duplicateElements.retainAll(currVerAuditList);
-
List<Map<String, Object>> joinedNonDuplicatedList = new ArrayList<>();
joinedNonDuplicatedList.addAll(prevVerAuditList);
joinedNonDuplicatedList.removeAll(duplicateElements);
joinedNonDuplicatedList.addAll(currVerAuditList);
joinedNonDuplicatedList.addAll(getAuditingFieldsList(eitherArchiveRestoreList.left().value()));
-
-
return Either.left(joinedNonDuplicatedList);
}
@@ -780,17 +621,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
if (eitherArchiveAudit.isRight()) {
return Either.right(eitherArchiveAudit.right().value());
}
-
// Restore Query
Either<List<ResourceAdminEvent>, ActionStatus> eitherRestoreAudit = auditCassandraDao.getRestoreAuditByServiceInstanceId(componentUUID);
if (eitherRestoreAudit.isRight()) {
return Either.right(eitherRestoreAudit.right().value());
}
-
List<ResourceAdminEvent> archiveAudit = new ArrayList<>();
archiveAudit.addAll(eitherArchiveAudit.left().value());
archiveAudit.addAll(eitherRestoreAudit.left().value());
-
return Either.left(archiveAudit);
}
@@ -805,7 +643,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
private List<Map<String, Object>> getAuditingFieldsList(List<? extends AuditingGenericEvent> prevVerAuditList) {
-
List<Map<String, Object>> prevVerAudit = new ArrayList<>();
for (AuditingGenericEvent auditEvent : prevVerAuditList) {
auditEvent.fillFields();
@@ -817,17 +654,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
/**
* createService
*
- * @param service
- * - Service
- * @param user
- * - modifier data (userId)
+ * @param service - Service
+ * @param user - modifier data (userId)
* @return Either<Service, responseFormat>
*/
public Either<Service, ResponseFormat> createService(Service service, User user) {
-
// get user details
user = validateUser(user, "Create Service", service, AuditingActionEnum.CREATE_RESOURCE, false);
- log.debug("User returned from validation: "+ user.toString());
+ log.debug("User returned from validation: " + user.toString());
// validate user role
validateUserRole(user, service, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null);
service.setCreatorUserId(user.getUserId());
@@ -844,11 +678,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
if (createServiceResponse.isRight()) {
return createServiceResponse;
}
- return createServiceByDao(service, user)
- .left()
- .bind(c -> updateCatalog(c, ChangeTypeEnum.LIFECYCLE)
- .left()
- .map (r -> (Service) r));
+ return createServiceByDao(service, user).left().bind(c -> updateCatalog(c, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Service) r));
}
private void checkFieldsForOverideAttampt(Service service) {
@@ -860,17 +690,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
private Either<Service, ResponseFormat> createServiceByDao(final Service service, final User user) {
log.debug("send service {} to dao for create", service.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
-
Either<Boolean, ResponseFormat> lockResult = lockComponentByName(service.getSystemName(), service, "Create Service");
if (lockResult.isRight()) {
ResponseFormat responseFormat = lockResult.right().value();
- componentsUtils.auditComponentAdmin(responseFormat, user, service, AuditingActionEnum.CREATE_RESOURCE,
- ComponentTypeEnum.SERVICE);
+ componentsUtils.auditComponentAdmin(responseFormat, user, service, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
return Either.right(responseFormat);
}
-
log.debug("System name locked is {}, status = {}", service.getSystemName(), lockResult);
-
try {
createMandatoryArtifactsData(service, user);
createServiceApiArtifactsData(service, user);
@@ -879,20 +705,19 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
generatePropertiesFromGenericType(service, genericType);
generateAndAddInputsFromGenericTypeProperties(service, genericType);
beforeCreate(service);
-
Either<Service, StorageOperationStatus> dataModelResponse = toscaOperationFacade.createToscaComponent(service);
if (dataModelResponse.isLeft()) {
log.debug("Service '{}' created successfully", service.getName());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
- componentsUtils.auditComponentAdmin(responseFormat, user, service, AuditingActionEnum.CREATE_RESOURCE,
- ComponentTypeEnum.SERVICE);
+ componentsUtils.auditComponentAdmin(responseFormat, user, service, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
ASDCKpiApi.countCreatedServicesKPI();
return Either.left(dataModelResponse.left().value());
}
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), service, ComponentTypeEnum.SERVICE);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), service,
+ ComponentTypeEnum.SERVICE);
log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
- componentsUtils.auditComponentAdmin(responseFormat, user, service, AuditingActionEnum.CREATE_RESOURCE,
- ComponentTypeEnum.SERVICE);
+ componentsUtils.auditComponentAdmin(responseFormat, user, service, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
return Either.right(responseFormat);
} finally {
graphLockOperation.unlockComponentByName(service.getSystemName(), service.getUniqueId(), NodeTypeEnum.Service);
@@ -903,36 +728,29 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
if (CollectionUtils.isEmpty(serviceCreationPluginList)) {
return;
}
- serviceCreationPluginList.stream()
- .sorted(Comparator.comparingInt(ServiceCreationPlugin::getOrder))
- .forEach(serviceCreationPlugin -> {
- try {
- serviceCreationPlugin.beforeCreate(service);
- } catch (final Exception e) {
- log.error("An error has occurred while running the serviceCreationPlugin '{}'",
- serviceCreationPlugin.getClass(), e);
- }
- });
+ serviceCreationPluginList.stream().sorted(Comparator.comparingInt(ServiceCreationPlugin::getOrder)).forEach(serviceCreationPlugin -> {
+ try {
+ serviceCreationPlugin.beforeCreate(service);
+ } catch (final Exception e) {
+ log.error("An error has occurred while running the serviceCreationPlugin '{}'", serviceCreationPlugin.getClass(), e);
+ }
+ });
}
private void generatePropertiesFromGenericType(final Service service, final Resource genericType) {
if (CollectionUtils.isEmpty(genericType.getProperties())) {
return;
}
- final List<PropertyDefinition> genericTypePropertyList = genericType.getProperties().stream()
- .map(PropertyDefinition::new)
- .peek(propertyDefinition -> propertyDefinition.setUniqueId(null))
- .collect(Collectors.toList());
+ final List<PropertyDefinition> genericTypePropertyList = genericType.getProperties().stream().map(PropertyDefinition::new)
+ .peek(propertyDefinition -> propertyDefinition.setUniqueId(null)).collect(Collectors.toList());
if (service.getProperties() == null) {
service.setProperties(new ArrayList<>(genericTypePropertyList));
} else {
List<PropertyDefinition> servicePropertyList = service.getProperties();
genericTypePropertyList.stream()
- .filter(property -> servicePropertyList.stream()
- .noneMatch(property1 -> property1.getName().equals(property.getName())))
+ .filter(property -> servicePropertyList.stream().noneMatch(property1 -> property1.getName().equals(property.getName())))
.forEach(servicePropertyList::add);
}
-
service.getProperties().forEach(propertyDefinition -> propertyDefinition.setUniqueId(null));
}
@@ -941,15 +759,15 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
// create mandatory artifacts
// TODO it must be removed after that artifact uniqueId creation will be
+
// moved to ArtifactOperation
String serviceUniqueId = service.getUniqueId();
Map<String, ArtifactDefinition> artifactMap = service.getServiceApiArtifacts();
- if (artifactMap == null)
+ if (artifactMap == null) {
artifactMap = new HashMap<>();
-
+ }
Map<String, Object> serviceApiArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceApiArtifacts();
List<String> exludeServiceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeServiceCategory();
-
List<CategoryDefinition> categories = service.getCategories();
boolean isCreateArtifact = true;
if (categories != null && exludeServiceCategory != null && !exludeServiceCategory.isEmpty()) {
@@ -959,59 +777,53 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
break;
}
}
-
}
-
if (serviceApiArtifacts != null && isCreateArtifact) {
Set<String> keys = serviceApiArtifacts.keySet();
for (String serviceApiArtifactName : keys) {
Map<String, Object> artifactInfoMap = (Map<String, Object>) serviceApiArtifacts.get(serviceApiArtifactName);
- ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, serviceApiArtifactName, artifactInfoMap, user, true);
+ ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, serviceApiArtifactName, artifactInfoMap, user,
+ true);
artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.SERVICE_API);
artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
}
-
service.setServiceApiArtifacts(artifactMap);
}
}
@VisibleForTesting
protected Either<Service, ResponseFormat> validateServiceBeforeCreate(Service service, User user, AuditingActionEnum actionEnum) {
-
try {
- serviceValidator.validate(user,service,actionEnum);
+ serviceValidator.validate(user, service, actionEnum);
} catch (ComponentException exp) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(exp);
- componentsUtils.auditComponentAdmin(responseFormat, user, service,
- AuditingActionEnum.CREATE_SERVICE, ComponentTypeEnum.SERVICE);
+ componentsUtils.auditComponentAdmin(responseFormat, user, service, AuditingActionEnum.CREATE_SERVICE, ComponentTypeEnum.SERVICE);
throw exp;
}
-
service.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
service.setContactId(service.getContactId().toLowerCase());
-
// Generate invariant UUID - must be here and not in operation since it
+
// should stay constant during clone
String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
service.setInvariantUUID(invariantUUID);
-
return Either.left(service);
}
public Either<Map<String, Boolean>, ResponseFormat> validateServiceNameExists(String serviceName, String userId) {
validateUserExists(userId);
-
- Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(serviceName, null, ComponentTypeEnum.SERVICE);
+ Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
+ .validateComponentNameUniqueness(serviceName, null, ComponentTypeEnum.SERVICE);
// DE242223
janusGraphDao.commit();
-
if (dataModelResponse.isLeft()) {
Map<String, Boolean> result = new HashMap<>();
result.put(IS_VALID, dataModelResponse.left().value());
log.debug("validation was successfully performed.");
return Either.left(result);
}
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
return Either.right(responseFormat);
}
@@ -1036,19 +848,16 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
user = validateUser(user, "updateServiceMetadata", serviceUpdate, null, false);
// validate user role
validateUserRole(user, serviceUpdate, new ArrayList<>(), null, null);
-
Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
if (storageStatus.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""));
+ return Either.right(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""));
}
-
Service currentService = storageStatus.left().value();
-
if (!ComponentValidationUtils.canWorkOnComponent(currentService, user.getUserId())) {
log.info("Restricted operation for user: {}, on service: {}", user.getUserId(), currentService.getCreatorUserId());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
-
Either<Service, ResponseFormat> validationRsponse = validateAndUpdateServiceMetadata(user, currentService, serviceUpdate);
if (validationRsponse.isRight()) {
log.info("service update metadata: validations field.");
@@ -1056,30 +865,23 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
Service serviceToUpdate = validationRsponse.left().value();
// lock resource
-
lockComponent(serviceId, currentService, "Update Service Metadata");
try {
- return toscaOperationFacade.updateToscaElement(serviceToUpdate)
- .right()
- .map(rf -> {
- janusGraphDao.rollback();
- BeEcompErrorManager.getInstance().logBeSystemError("Update Service Metadata");
- log.debug("failed to update sevice {}", serviceToUpdate.getUniqueId());
- return (componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- })
- .left()
- .bind(c -> updateCatalogAndCommit(c));
-
+ return toscaOperationFacade.updateToscaElement(serviceToUpdate).right().map(rf -> {
+ janusGraphDao.rollback();
+ BeEcompErrorManager.getInstance().logBeSystemError("Update Service Metadata");
+ log.debug("failed to update sevice {}", serviceToUpdate.getUniqueId());
+ return (componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }).left().bind(c -> updateCatalogAndCommit(c));
} finally {
graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
}
}
- private Either<Service, ResponseFormat> updateCatalogAndCommit(Service service){
- Either<Service, ResponseFormat> res = updateCatalog(service, ChangeTypeEnum.LIFECYCLE).left().map(s -> (Service)s);
+ private Either<Service, ResponseFormat> updateCatalogAndCommit(Service service) {
+ Either<Service, ResponseFormat> res = updateCatalog(service, ChangeTypeEnum.LIFECYCLE).left().map(s -> (Service) s);
janusGraphDao.commit();
return res;
-
}
public Set<String> deleteForwardingPaths(String serviceId, Set<String> pathIdsToDelete, User user, boolean lock) {
@@ -1089,7 +891,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
validateUserRole(user, serviceToDelete, new ArrayList<>(), null, null);
Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
if (storageStatus.isRight()) {
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "");
+ throw new ByActionStatusComponentException(
+ componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "");
}
Service service = storageStatus.left().value();
Either<Set<String>, StorageOperationStatus> result = null;
@@ -1098,27 +901,26 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
lockComponent(service.getUniqueId(), service, "Delete Forwarding Path on Service");
} catch (ComponentException e) {
janusGraphDao.rollback();
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse
- (storageStatus.right().value(), ComponentTypeEnum.SERVICE), "");
+ throw new ByActionStatusComponentException(
+ componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "");
}
}
- try{
- result = forwardingPathOperation.deleteForwardingPath(service ,pathIdsToDelete);
+ try {
+ result = forwardingPathOperation.deleteForwardingPath(service, pathIdsToDelete);
if (result.isRight()) {
log.debug(FAILED_TO_LOCK_SERVICE_RESPONSE_IS, service.getName(), result.right().value());
janusGraphDao.rollback();
- throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse
- (storageStatus.right().value(), ComponentTypeEnum.SERVICE));
+ throw new ByActionStatusComponentException(
+ componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE));
}
janusGraphDao.commit();
log.debug(THE_SERVICE_WITH_SYSTEM_NAME_LOCKED, service.getSystemName());
-
- } catch (ComponentException e){
+ } catch (ComponentException e) {
log.error("Exception occurred during delete forwarding path : {}", e.getMessage(), e);
janusGraphDao.rollback();
throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
} finally {
- graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service);
+ graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service);
}
return result.left().value();
}
@@ -1127,19 +929,19 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
Service serviceToDelete = new Service();
serviceToDelete.setUniqueId(serviceId);
serviceToDelete.setForwardingPaths(new HashMap<>());
- pathIdsToDelete.forEach(pathIdToDelete -> serviceToDelete.getForwardingPaths().put(pathIdToDelete, new ForwardingPathDataDefinition()));
+ pathIdsToDelete.forEach(pathIdToDelete -> serviceToDelete.getForwardingPaths().put(pathIdToDelete, new ForwardingPathDataDefinition()));
return serviceToDelete;
}
public Service updateForwardingPath(String serviceId, Service serviceUpdate, User user, boolean lock) {
- return createOrUpdateForwardingPath(serviceId, serviceUpdate, user, true,"updateForwardingPath", lock);
+ return createOrUpdateForwardingPath(serviceId, serviceUpdate, user, true, "updateForwardingPath", lock);
}
public Service createForwardingPath(String serviceId, Service serviceUpdate, User user, boolean lock) {
return createOrUpdateForwardingPath(serviceId, serviceUpdate, user, false, "createForwardingPath", lock);
}
- private ForwardingPathDataDefinition getTrimmedValues(ForwardingPathDataDefinition path){
+ private ForwardingPathDataDefinition getTrimmedValues(ForwardingPathDataDefinition path) {
ForwardingPathDataDefinition dataDefinition = new ForwardingPathDataDefinition(path.getName());
dataDefinition.setName(Strings.nullToEmpty(path.getName()).trim());
dataDefinition.setProtocol(Strings.nullToEmpty(path.getProtocol()).trim());
@@ -1148,46 +950,38 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
dataDefinition.setPathElements(path.getPathElements());
dataDefinition.setDescription(path.getDescription());
dataDefinition.setToscaResourceName(path.getToscaResourceName());
- return dataDefinition;
+ return dataDefinition;
}
- private Service createOrUpdateForwardingPath(String serviceId, Service serviceUpdate, User user, boolean isUpdate, String errorContext, boolean lock) {
+ private Service createOrUpdateForwardingPath(String serviceId, Service serviceUpdate, User user, boolean isUpdate, String errorContext,
+ boolean lock) {
validateUserAndRole(serviceUpdate, user, errorContext);
-
Map<String, ForwardingPathDataDefinition> forwardingPaths = serviceUpdate.getForwardingPaths();
-
- Map<String, ForwardingPathDataDefinition> trimmedForwardingPaths =
- forwardingPaths.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
- entry -> new ForwardingPathDataDefinition(getTrimmedValues(entry.getValue()))));
-
- forwardingPathValidator.validateForwardingPaths(trimmedForwardingPaths.values(),
- serviceId, isUpdate);
-
+ Map<String, ForwardingPathDataDefinition> trimmedForwardingPaths = forwardingPaths.entrySet().stream()
+ .collect(Collectors.toMap(Map.Entry::getKey, entry -> new ForwardingPathDataDefinition(getTrimmedValues(entry.getValue()))));
+ forwardingPathValidator.validateForwardingPaths(trimmedForwardingPaths.values(), serviceId, isUpdate);
Either<Service, StorageOperationStatus> serviceStorageOperationStatusEither = toscaOperationFacade.getToscaElement(serviceId);
-
- if(serviceStorageOperationStatusEither.isRight()){
+ if (serviceStorageOperationStatusEither.isRight()) {
StorageOperationStatus errorStatus = serviceStorageOperationStatusEither.right().value();
log.debug("Failed to fetch service information by service id, error {}", errorStatus);
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(errorStatus));
}
Service storedService = serviceStorageOperationStatusEither.left().value();
-
Either<ForwardingPathDataDefinition, StorageOperationStatus> result;
Component component = getForwardingPathOriginComponent();
final String toscaResourceName;
- if ( component.getComponentType() == ComponentTypeEnum.RESOURCE) {
+ if (component.getComponentType() == ComponentTypeEnum.RESOURCE) {
toscaResourceName = ((Resource) component).getToscaResourceName();
} else {
toscaResourceName = "";
}
if (lock) {
- lockComponent(storedService.getUniqueId(), storedService, "Add or Update Forwarding Path on Service");
- log.debug(THE_SERVICE_WITH_SYSTEM_NAME_LOCKED, storedService.getSystemName());
+ lockComponent(storedService.getUniqueId(), storedService, "Add or Update Forwarding Path on Service");
+ log.debug(THE_SERVICE_WITH_SYSTEM_NAME_LOCKED, storedService.getSystemName());
}
Map<String, ForwardingPathDataDefinition> resultMap = new HashMap<>();
try {
trimmedForwardingPaths.values().forEach(fp -> fp.setToscaResourceName(toscaResourceName));
-
populateForwardingPaths(serviceId, isUpdate, trimmedForwardingPaths, resultMap);
janusGraphDao.commit();
} finally {
@@ -1199,7 +993,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
private Component getForwardingPathOriginComponent() {
- Either<Component, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade.getLatestByName(ForwardingPathUtils.FORWARDING_PATH_NODE_NAME);
+ Either<Component, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade
+ .getLatestByName(ForwardingPathUtils.FORWARDING_PATH_NODE_NAME);
if (forwardingPathOrigin.isRight()) {
StorageOperationStatus errorStatus = forwardingPathOrigin.right().value();
log.debug("Failed to fetch normative forwarding path resource by tosca name, error {}", errorStatus);
@@ -1208,7 +1003,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return forwardingPathOrigin.left().value();
}
- private void populateForwardingPaths(String serviceId, boolean isUpdate, Map<String, ForwardingPathDataDefinition> trimmedForwardingPaths, Map<String, ForwardingPathDataDefinition> resultMap) {
+ private void populateForwardingPaths(String serviceId, boolean isUpdate, Map<String, ForwardingPathDataDefinition> trimmedForwardingPaths,
+ Map<String, ForwardingPathDataDefinition> resultMap) {
Either<ForwardingPathDataDefinition, StorageOperationStatus> result;
try {
for (ForwardingPathDataDefinition forwardingPathDataDefinition : trimmedForwardingPaths.values()) {
@@ -1219,24 +1015,22 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
if (result.isRight()) {
janusGraphDao.rollback();
- throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(result.right().value(), ComponentTypeEnum.SERVICE),
- ""));
+ throw new ByResponseFormatComponentException(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value(), ComponentTypeEnum.SERVICE), ""));
} else {
ForwardingPathDataDefinition fpDataDefinition = result.left().value();
resultMap.put(fpDataDefinition.getUniqueId(), forwardingPathDataDefinition);
}
}
-
} catch (ComponentException e) {
janusGraphDao.rollback();
- log.error("Exception occurred during add or update forwarding path property values: {}",
- e.getMessage(), e);
+ log.error("Exception occurred during add or update forwarding path property values: {}", e.getMessage(), e);
throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
}
}
- private Service createServiceWithForwardingPathForResponse(String serviceId, Map<String,ForwardingPathDataDefinition> forwardingPathDataDefinitionMap) {
+ private Service createServiceWithForwardingPathForResponse(String serviceId,
+ Map<String, ForwardingPathDataDefinition> forwardingPathDataDefinitionMap) {
Service service = new Service();
service.setUniqueId(serviceId);
service.setForwardingPaths(forwardingPathDataDefinitionMap);
@@ -1250,87 +1044,70 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
@VisibleForTesting
Either<Service, ResponseFormat> validateAndUpdateServiceMetadata(User user, Service currentService, Service serviceUpdate) {
-
try {
boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentService.getVersion());
- Either<Boolean, ResponseFormat> response = validateAndUpdateCategory(user, currentService, serviceUpdate, hasBeenCertified, UPDATE_SERVICE_METADATA);
+ Either<Boolean, ResponseFormat> response = validateAndUpdateCategory(user, currentService, serviceUpdate, hasBeenCertified,
+ UPDATE_SERVICE_METADATA);
if (response.isRight()) {
ResponseFormat errorResponse = response.right().value();
return Either.right(errorResponse);
}
-
verifyValuesAreIdentical(serviceUpdate.getCreatorUserId(), currentService.getCreatorUserId(), "creatorUserId");
verifyValuesAreIdentical(serviceUpdate.getCreatorFullName(), currentService.getCreatorFullName(), "creatorFullName");
verifyValuesAreIdentical(serviceUpdate.getLastUpdaterUserId(), currentService.getLastUpdaterUserId(), "lastUpdaterUserId");
verifyValuesAreIdentical(serviceUpdate.getLastUpdaterFullName(), currentService.getLastUpdaterFullName(), "lastUpdaterFullName");
-
response = validateAndUpdateServiceName(user, currentService, serviceUpdate, hasBeenCertified, null);
if (response.isRight()) {
return Either.right(response.right().value());
}
-
verifyValuesAreIdentical(serviceUpdate.getDistributionStatus(), currentService.getDistributionStatus(), "distributionStatus");
-
if (serviceUpdate.getProjectCode() != null) {
response = validateAndUpdateProjectCode(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA);
if (response.isRight()) {
return Either.right(response.right().value());
}
}
-
response = validateAndUpdateIcon(user, currentService, serviceUpdate, hasBeenCertified, UPDATE_SERVICE_METADATA);
if (response.isRight()) {
return Either.right(response.right().value());
}
-
verifyValuesAreIdentical(serviceUpdate.getCreationDate(), currentService.getCreationDate(), "creationDate");
verifyValuesAreIdentical(serviceUpdate.getVersion(), currentService.getVersion(), "version");
-
response = validateAndUpdateDescription(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA);
if (response.isRight()) {
return Either.right(response.right().value());
}
-
response = validateAndUpdateTags(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA);
if (response.isRight()) {
return Either.right(response.right().value());
}
-
response = validateAndUpdateContactId(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA);
if (response.isRight()) {
return Either.right(response.right().value());
}
-
verifyValuesAreIdentical(serviceUpdate.getLastUpdateDate(), currentService.getLastUpdateDate(), "lastUpdateDate");
verifyValuesAreIdentical(serviceUpdate.getLifecycleState(), currentService.getLifecycleState(), "lifecycleState");
verifyValuesAreIdentical(serviceUpdate.isHighestVersion(), currentService.isHighestVersion(), "isHighestVersion");
verifyValuesAreIdentical(serviceUpdate.getUUID(), currentService.getUUID(), "uuid");
-
validateAndUpdateServiceType(currentService, serviceUpdate);
validateAndUpdateServiceFunction(currentService, serviceUpdate);
-
response = validateAndUpdateServiceRole(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA);
if (response.isRight()) {
return Either.right(response.right().value());
}
-
response = validateAndUpdateInstantiationTypeValue(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA);
if (response.isRight()) {
return Either.right(response.right().value());
}
-
verifyValuesAreIdentical(serviceUpdate.getInvariantUUID(), currentService.getInvariantUUID(), "invariantUUID");
-
validateAndUpdateEcompNaming(currentService, serviceUpdate);
-
currentService.setEnvironmentContext(serviceUpdate.getEnvironmentContext());
currentService.setCategorySpecificMetadata(serviceUpdate.getCategorySpecificMetadata());
return Either.left(currentService);
-
} catch (ComponentException exception) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(exception);
- componentsUtils.auditComponentAdmin(responseFormat, user, serviceUpdate,
- AuditingActionEnum.UPDATE_SERVICE_METADATA, ComponentTypeEnum.SERVICE);
+ componentsUtils
+ .auditComponentAdmin(responseFormat, user, serviceUpdate, AuditingActionEnum.UPDATE_SERVICE_METADATA, ComponentTypeEnum.SERVICE);
return Either.right(responseFormat);
}
}
@@ -1358,7 +1135,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
}
- private Either<Boolean, ResponseFormat> validateAndUpdateContactId(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) {
+ private Either<Boolean, ResponseFormat> validateAndUpdateContactId(User user, Service currentService, Service serviceUpdate,
+ AuditingActionEnum audatingAction) {
String contactIdUpdated = serviceUpdate.getContactId();
String contactIdCurrent = currentService.getContactId();
if (!contactIdCurrent.equals(contactIdUpdated)) {
@@ -1368,7 +1146,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.left(true);
}
- private Either<Boolean, ResponseFormat> validateAndUpdateTags(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) {
+ private Either<Boolean, ResponseFormat> validateAndUpdateTags(User user, Service currentService, Service serviceUpdate,
+ AuditingActionEnum audatingAction) {
List<String> tagsUpdated = serviceUpdate.getTags();
List<String> tagsCurrent = currentService.getTags();
if (tagsUpdated == null || tagsUpdated.isEmpty()) {
@@ -1376,7 +1155,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
componentsUtils.auditComponentAdmin(responseFormat, user, serviceUpdate, audatingAction, ComponentTypeEnum.SERVICE);
return Either.right(responseFormat);
}
-
if (!(tagsCurrent.containsAll(tagsUpdated) && tagsUpdated.containsAll(tagsCurrent))) {
componentTagsValidator.validateAndCorrectField(user, serviceUpdate, audatingAction);
currentService.setTags(tagsUpdated);
@@ -1384,7 +1162,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.left(true);
}
- private Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) {
+ private Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Service currentService, Service serviceUpdate,
+ AuditingActionEnum audatingAction) {
String descriptionUpdated = serviceUpdate.getDescription();
String descriptionCurrent = currentService.getDescription();
if (!descriptionCurrent.equals(descriptionUpdated)) {
@@ -1394,12 +1173,11 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.left(true);
}
- private Either<Boolean, ResponseFormat> validateAndUpdateProjectCode(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) {
+ private Either<Boolean, ResponseFormat> validateAndUpdateProjectCode(User user, Service currentService, Service serviceUpdate,
+ AuditingActionEnum audatingAction) {
String projectCodeUpdated = serviceUpdate.getProjectCode();
String projectCodeCurrent = currentService.getProjectCode();
- if (StringUtils.isEmpty(projectCodeCurrent)
- || !projectCodeCurrent.equals(projectCodeUpdated)) {
-
+ if (StringUtils.isEmpty(projectCodeCurrent) || !projectCodeCurrent.equals(projectCodeUpdated)) {
try {
componentProjectCodeValidator.validateAndCorrectField(user, serviceUpdate, audatingAction);
} catch (ComponentException exp) {
@@ -1407,12 +1185,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.right(errorRespons);
}
currentService.setProjectCode(projectCodeUpdated);
-
}
return Either.left(true);
}
- private Either<Boolean, ResponseFormat> validateAndUpdateIcon(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
+ private Either<Boolean, ResponseFormat> validateAndUpdateIcon(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified,
+ AuditingActionEnum audatingAction) {
String iconUpdated = serviceUpdate.getIcon();
String iconCurrent = currentService.getIcon();
if (!iconCurrent.equals(iconUpdated)) {
@@ -1428,7 +1206,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.left(true);
}
- private Either<Boolean, ResponseFormat> validateAndUpdateServiceName(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum auditingAction) {
+ private Either<Boolean, ResponseFormat> validateAndUpdateServiceName(User user, Service currentService, Service serviceUpdate,
+ boolean hasBeenCertified, AuditingActionEnum auditingAction) {
String serviceNameUpdated = serviceUpdate.getName();
String serviceNameCurrent = currentService.getName();
if (!serviceNameCurrent.equals(serviceNameUpdated)) {
@@ -1440,9 +1219,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.right(exp.getResponseFormat());
}
currentService.setName(serviceNameUpdated);
- currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(serviceNameUpdated));
- currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setSystemName(ValidationUtils.convertToSystemName(serviceNameUpdated));
-
+ currentService.getComponentMetadataDefinition().getMetadataDataDefinition()
+ .setNormalizedName(ValidationUtils.normaliseComponentName(serviceNameUpdated));
+ currentService.getComponentMetadataDefinition().getMetadataDataDefinition()
+ .setSystemName(ValidationUtils.convertToSystemName(serviceNameUpdated));
} else {
log.info("service name {} cannot be updated once the service has been certified once.", serviceNameUpdated);
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NAME_CANNOT_BE_CHANGED);
@@ -1470,7 +1250,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
}
- private Either<Boolean, ResponseFormat> validateAndUpdateServiceRole(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) {
+ private Either<Boolean, ResponseFormat> validateAndUpdateServiceRole(User user, Service currentService, Service updatedService,
+ AuditingActionEnum auditingAction) {
String updatedServiceRole = updatedService.getServiceRole();
String currentServiceRole = currentService.getServiceRole();
if (!currentServiceRole.equals(updatedServiceRole)) {
@@ -1486,8 +1267,9 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.left(true);
}
- private Either<Boolean, ResponseFormat> validateAndUpdateInstantiationTypeValue(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) {
- String updatedInstaType= updatedService.getInstantiationType();
+ private Either<Boolean, ResponseFormat> validateAndUpdateInstantiationTypeValue(User user, Service currentService, Service updatedService,
+ AuditingActionEnum auditingAction) {
+ String updatedInstaType = updatedService.getInstantiationType();
String currentInstaType = currentService.getInstantiationType();
if (!currentInstaType.equals(updatedInstaType)) {
try {
@@ -1502,7 +1284,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.left(true);
}
- private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
+ private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Service currentService, Service serviceUpdate,
+ boolean hasBeenCertified, AuditingActionEnum audatingAction) {
try {
List<CategoryDefinition> categoryUpdated = serviceUpdate.getCategories();
List<CategoryDefinition> categoryCurrent = currentService.getCategories();
@@ -1520,32 +1303,27 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.right(exp.getResponseFormat());
}
return Either.left(true);
-
}
public Either<ServiceRelations, ResponseFormat> getServiceComponentsRelations(String serviceId, User user) {
Either<Service, ResponseFormat> serviceResponseFormatEither = getService(serviceId, user);
- if (serviceResponseFormatEither.isRight()){
+ if (serviceResponseFormatEither.isRight()) {
return Either.right(serviceResponseFormatEither.right().value());
}
- final ServiceRelations serviceRelations = new ForwardingPathUtils().convertServiceToServiceRelations(serviceResponseFormatEither.left().value());
+ final ServiceRelations serviceRelations = new ForwardingPathUtils()
+ .convertServiceToServiceRelations(serviceResponseFormatEither.left().value());
return Either.left(serviceRelations);
-
-
}
public ResponseFormat deleteService(String serviceId, User user) {
ResponseFormat responseFormat;
-
validateUserExists(user);
Either<Service, StorageOperationStatus> serviceStatus = toscaOperationFacade.getToscaElement(serviceId);
if (serviceStatus.isRight()) {
log.debug("failed to get service {}", serviceId);
return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceStatus.right().value()), "");
}
-
Service service = serviceStatus.left().value();
-
StorageOperationStatus result = StorageOperationStatus.OK;
try {
lockComponent(service, "Mark service to delete");
@@ -1557,9 +1335,9 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName());
}
return responseFormat;
- }catch (ComponentException e){
+ } catch (ComponentException e) {
return e.getResponseFormat();
- }finally {
+ } finally {
if (result == null || result != StorageOperationStatus.OK) {
log.warn("operation failed. do rollback");
BeEcompErrorManager.getInstance().logBeSystemError("Delete Service");
@@ -1577,15 +1355,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
String ecompErrorContext = "delete service";
validateUserNotEmpty(user, ecompErrorContext);
user = validateUserExists(user);
-
Either<Service, ResponseFormat> getResult = getServiceByNameAndVersion(serviceName, version, user.getUserId());
if (getResult.isRight()) {
return getResult.right().value();
}
Service service = getResult.left().value();
-
StorageOperationStatus result = StorageOperationStatus.OK;
-
try {
lockComponent(service, "Mark service to delete");
result = markComponentToDelete(service);
@@ -1596,11 +1371,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName());
}
return responseFormat;
-
- }catch (ComponentException e){
+ } catch (ComponentException e) {
result = StorageOperationStatus.GENERAL_ERROR;
return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- }finally {
+ } finally {
if (result == null || result != StorageOperationStatus.OK) {
log.warn("operation failed. do rollback");
BeEcompErrorManager.getInstance().logBeSystemError("Delete Service");
@@ -1617,30 +1391,29 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
String ecompErrorContext = "Get service";
validateUserNotEmpty(user, ecompErrorContext);
validateUserExists(user);
-
Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
if (storageStatus.isRight()) {
log.debug("failed to get service by id {}", serviceId);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceId));
+ return Either.right(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceId));
}
-
- if(!(storageStatus.left().value() instanceof Service)){
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), serviceId));
+ if (!(storageStatus.left().value() instanceof Service)) {
+ return Either
+ .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), serviceId));
}
Service service = storageStatus.left().value();
return Either.left(service);
-
-
-
-
}
public Either<Service, ResponseFormat> getServiceByNameAndVersion(String serviceName, String serviceVersion, String userId) {
validateUserExists(userId);
- Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.SERVICE, serviceName, serviceVersion);
+ Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade
+ .getComponentByNameAndVersion(ComponentTypeEnum.SERVICE, serviceName, serviceVersion);
if (storageStatus.isRight()) {
log.debug("failed to get service by name {} and version {}", serviceName, serviceVersion);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceName));
+ return Either.right(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE),
+ serviceName));
}
Service service = storageStatus.left().value();
return Either.left(service);
@@ -1651,15 +1424,16 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
// create mandatory artifacts
// TODO it must be removed after that artifact uniqueId creation will be
+
// moved to ArtifactOperation
String serviceUniqueId = service.getUniqueId();
Map<String, ArtifactDefinition> artifactMap = service.getArtifacts();
- if (artifactMap == null)
+ if (artifactMap == null) {
artifactMap = new HashMap<>();
-
- Map<String, Object> informationalServiceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalServiceArtifacts();
+ }
+ Map<String, Object> informationalServiceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getInformationalServiceArtifacts();
List<String> exludeServiceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeServiceCategory();
-
String category = service.getCategories().get(0).getName();
boolean isCreateArtifact = true;
if (category != null && exludeServiceCategory != null && !exludeServiceCategory.isEmpty()) {
@@ -1669,26 +1443,23 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
break;
}
}
-
}
-
if (informationalServiceArtifacts != null && isCreateArtifact) {
Set<String> keys = informationalServiceArtifacts.keySet();
for (String informationalServiceArtifactName : keys) {
Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalServiceArtifacts.get(informationalServiceArtifactName);
- ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, informationalServiceArtifactName, artifactInfoMap, user, false);
+ ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, informationalServiceArtifactName, artifactInfoMap,
+ user, false);
artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
-
}
-
service.setArtifacts(artifactMap);
}
}
- private ArtifactDefinition createArtifactDefinition(String serviceId, String logicalName, Map<String, Object> artifactInfoMap, User user, Boolean isServiceApi) {
-
- ArtifactDefinition artifactInfo = artifactsBusinessLogic.createArtifactPlaceHolderInfo(serviceId, logicalName, artifactInfoMap, user, ArtifactGroupTypeEnum.INFORMATIONAL);
-
+ private ArtifactDefinition createArtifactDefinition(String serviceId, String logicalName, Map<String, Object> artifactInfoMap, User user,
+ Boolean isServiceApi) {
+ ArtifactDefinition artifactInfo = artifactsBusinessLogic
+ .createArtifactPlaceHolderInfo(serviceId, logicalName, artifactInfoMap, user, ArtifactGroupTypeEnum.INFORMATIONAL);
if (isServiceApi) {
artifactInfo.setMandatory(false);
artifactInfo.setServiceApi(true);
@@ -1702,21 +1473,21 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return configuredEnvName;
}
- public Either<String, ResponseFormat> activateServiceOnTenantEnvironment(String serviceId, String envId, User modifier, ServiceDistributionReqInfo data) {
-
- Either<ActivationRequestInformation, ResponseFormat> activationRequestInformationEither = serviceDistributionValidation.validateActivateServiceRequest(serviceId, envId, modifier, data);
+ public Either<String, ResponseFormat> activateServiceOnTenantEnvironment(String serviceId, String envId, User modifier,
+ ServiceDistributionReqInfo data) {
+ Either<ActivationRequestInformation, ResponseFormat> activationRequestInformationEither = serviceDistributionValidation
+ .validateActivateServiceRequest(serviceId, envId, modifier, data);
if (activationRequestInformationEither.isRight()) {
return Either.right(activationRequestInformationEither.right().value());
}
-
ActivationRequestInformation activationRequestInformation = activationRequestInformationEither.left().value();
-
String did = ThreadLocalsHolder.getUuid();
Service service = activationRequestInformation.getServiceToActivate();
return buildAndSendServiceNotification(service, envId, did, activationRequestInformation.getWorkloadContext(), modifier);
}
- private Either<String, ResponseFormat> buildAndSendServiceNotification(Service service, String envId, String did, String workloadContext, User modifier) {
+ private Either<String, ResponseFormat> buildAndSendServiceNotification(Service service, String envId, String did, String workloadContext,
+ User modifier) {
String envName = getEnvNameFromConfiguration();
INotificationData notificationData = distributionEngine.buildServiceForDistribution(service, did, workloadContext);
ActionStatus notifyServiceResponse = distributionEngine.notifyService(did, service, notificationData, envId, envName, modifier);
@@ -1731,21 +1502,19 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
public Either<Service, ResponseFormat> activateDistribution(String serviceId, String envName, User modifier, HttpServletRequest request) {
-
User user = validateUserExists(modifier.getUserId());
validateUserRole(user, Collections.singletonList(Role.DESIGNER));
Either<Service, ResponseFormat> result;
ResponseFormat response;
Service updatedService;
String did = ThreadLocalsHolder.getUuid();
- // DE194021
+ // DE194021
String configuredEnvName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0);
if (configuredEnvName != null && !configuredEnvName.equals(envName)) {
log.trace("Update environment name to be {} instead of {}", configuredEnvName, envName);
envName = configuredEnvName;
}
// DE194021
-
ServletContext servletContext = request.getSession().getServletContext();
boolean isDistributionEngineUp = getHealthCheckBL(servletContext).isDistributionEngineUp(); // DE
if (!isDistributionEngineUp) {
@@ -1754,16 +1523,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
return Either.right(response);
}
-
Either<Service, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(serviceId);
if (serviceRes.isRight()) {
log.debug("failed retrieving service");
- response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceRes.right().value(), ComponentTypeEnum.SERVICE), serviceId);
+ response = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(serviceRes.right().value(), ComponentTypeEnum.SERVICE), serviceId);
componentsUtils.auditComponent(response, user, null, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST,
- new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()),
- ResourceVersionInfo.newBuilder()
- .build(),
- did);
+ new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()), ResourceVersionInfo.newBuilder().build(), did);
return Either.right(response);
}
Service service = serviceRes.left().value();
@@ -1773,7 +1539,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
if (service.getLifecycleState() != LifecycleStateEnum.CERTIFIED) {
log.info("service {} is not available for distribution. Should be in certified state", service.getUniqueId());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, service.getVersion(), service.getName());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, service.getVersion(), service.getName());
return Either.right(responseFormat);
}
String dcurrStatus = service.getDistributionStatus().name();
@@ -1783,7 +1550,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
INotificationData notificationData = distributionEngine.buildServiceForDistribution(service, did, null);
ActionStatus notifyServiceResponse = distributionEngine.notifyService(did, service, notificationData, envName, user);
if (notifyServiceResponse == ActionStatus.OK) {
- Either<Service, ResponseFormat> updateStateRes = updateDistributionStatusForActivation(service, user, DistributionStatusEnum.DISTRIBUTED);
+ Either<Service, ResponseFormat> updateStateRes = updateDistributionStatusForActivation(service, user,
+ DistributionStatusEnum.DISTRIBUTED);
if (updateStateRes.isLeft() && updateStateRes.left().value() != null) {
updatedService = updateStateRes.left().value();
updatedStatus = updatedService.getDistributionStatus().name();
@@ -1801,28 +1569,22 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
result = Either.right(response);
}
} else {
- response = componentsUtils.getResponseFormatByDE(componentsUtils.convertFromStorageResponse(readyForDistribution, ComponentTypeEnum.SERVICE), envName);
+ response = componentsUtils
+ .getResponseFormatByDE(componentsUtils.convertFromStorageResponse(readyForDistribution, ComponentTypeEnum.SERVICE), envName);
result = Either.right(response);
}
componentsUtils.auditComponent(response, user, service, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST,
- new ResourceCommonInfo(service.getName(),ComponentTypeEnum.SERVICE.getValue()),
- ResourceVersionInfo.newBuilder()
- .distributionStatus(dcurrStatus)
- .build(),
- ResourceVersionInfo.newBuilder()
- .distributionStatus(updatedStatus)
- .build(),
- null, null, did);
+ new ResourceCommonInfo(service.getName(), ComponentTypeEnum.SERVICE.getValue()),
+ ResourceVersionInfo.newBuilder().distributionStatus(dcurrStatus).build(),
+ ResourceVersionInfo.newBuilder().distributionStatus(updatedStatus).build(), null, null, did);
return result;
}
// convert to private after deletion of temp url
public Either<Service, ResponseFormat> updateDistributionStatusForActivation(Service service, User user, DistributionStatusEnum state) {
-
validateUserExists(user.getUserId());
-
String serviceId = service.getUniqueId();
- lockComponent(serviceId, service, "updateDistributionStatusForActivation");
+ lockComponent(serviceId, service, "updateDistributionStatusForActivation");
try {
Either<Service, StorageOperationStatus> result = toscaOperationFacade.updateDistributionStatus(service, user, state);
if (result.isRight()) {
@@ -1840,38 +1602,33 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
public Either<Service, ResponseFormat> markDistributionAsDeployed(String serviceId, String did, User user) {
-
validateUserExists(user.getUserId());
log.debug("mark distribution deployed");
-
AuditingActionEnum auditAction = AuditingActionEnum.DISTRIBUTION_DEPLOY;
Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(serviceId);
if (getServiceResponse.isRight()) {
- BeEcompErrorManager.getInstance().logBeComponentMissingError("markDistributionAsDeployed", ComponentTypeEnum.SERVICE.getValue(), serviceId);
+ BeEcompErrorManager.getInstance()
+ .logBeComponentMissingError("markDistributionAsDeployed", ComponentTypeEnum.SERVICE.getValue(), serviceId);
log.debug("service {} not found", serviceId);
- ResponseFormat responseFormat = auditDeployError(did, user, auditAction, null, componentsUtils.convertFromStorageResponse(getServiceResponse.right().value(), ComponentTypeEnum.SERVICE), "");
-
+ ResponseFormat responseFormat = auditDeployError(did, user, auditAction, null,
+ componentsUtils.convertFromStorageResponse(getServiceResponse.right().value(), ComponentTypeEnum.SERVICE), "");
return Either.right(responseFormat);
}
-
Service service = getServiceResponse.left().value();
user = validateRoleForDeploy(did, user, auditAction, service);
return checkDistributionAndDeploy(did, user, auditAction, service);
-
}
public Either<Service, ResponseFormat> generateVfModuleArtifacts(Service service, User modifier, boolean shouldLock, boolean inTransaction) {
Function<ComponentInstance, List<ArtifactGenerator<ArtifactDefinition>>> artifactTaskGeneratorCreator = ri ->
- // Only one VF Module Artifact per instance - add it to a list of one
- buildArtifactGenList(service, modifier, shouldLock, inTransaction, ri);
-
+ // Only one VF Module Artifact per instance - add it to a list of one
+ buildArtifactGenList(service, modifier, shouldLock, inTransaction, ri);
return generateDeploymentArtifacts(service, artifactTaskGeneratorCreator);
-
}
- private List<ArtifactGenerator<ArtifactDefinition>> buildArtifactGenList(Service service, User modifier, boolean shouldLock, boolean inTransaction, ComponentInstance ri) {
+ private List<ArtifactGenerator<ArtifactDefinition>> buildArtifactGenList(Service service, User modifier, boolean shouldLock,
+ boolean inTransaction, ComponentInstance ri) {
List<ArtifactGenerator<ArtifactDefinition>> asList = new ArrayList<>();
-
if (ri.getOriginType() == OriginTypeEnum.VF) {
asList = Arrays.asList(new VfModuleArtifactGenerator(modifier, ri, service, shouldLock, inTransaction));
}
@@ -1880,25 +1637,25 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
private List<GroupInstance> collectGroupsInstanceForCompInstance(ComponentInstance currVF) {
Map<String, ArtifactDefinition> deploymentArtifacts = currVF.getDeploymentArtifacts();
- if(currVF.getGroupInstances() != null){
+ if (currVF.getGroupInstances() != null) {
currVF.getGroupInstances().forEach(gi -> gi.alignArtifactsUuid(deploymentArtifacts));
}
return currVF.getGroupInstances();
}
- private ArtifactDefinition getVfModuleInstArtifactForCompInstance(ComponentInstance currVF, Service service, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper) {
+ private ArtifactDefinition getVfModuleInstArtifactForCompInstance(ComponentInstance currVF, Service service, Wrapper<String> payloadWrapper,
+ Wrapper<ResponseFormat> responseWrapper) {
ArtifactDefinition vfModuleAertifact = null;
if (MapUtils.isNotEmpty(currVF.getDeploymentArtifacts())) {
- final Optional<ArtifactDefinition> optionalVfModuleArtifact =
- currVF.getDeploymentArtifacts().values().stream()
- .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.getType()))
- .findAny();
+ final Optional<ArtifactDefinition> optionalVfModuleArtifact = currVF.getDeploymentArtifacts().values().stream()
+ .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.getType())).findAny();
if (optionalVfModuleArtifact.isPresent()) {
vfModuleAertifact = optionalVfModuleArtifact.get();
}
}
if (vfModuleAertifact == null) {
- Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact = createVfModuleArtifact(currVF, service, payloadWrapper.getInnerElement());
+ Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact = createVfModuleArtifact(currVF, service,
+ payloadWrapper.getInnerElement());
if (createVfModuleArtifact.isLeft()) {
vfModuleAertifact = createVfModuleArtifact.left().value();
} else {
@@ -1916,16 +1673,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
vfModulePayloads.add(modulePayload);
}
vfModulePayloads.sort(VfModuleArtifactPayload::compareByGroupName);
-
final Gson gson = new GsonBuilder().setPrettyPrinting().create();
-
String vfModulePayloadString = gson.toJson(vfModulePayloads);
payloadWrapper.setInnerElement(vfModulePayloadString);
}
-
}
- private Either<ArtifactDefinition, ResponseFormat> generateVfModuleInstanceArtifact(User modifier, ComponentInstance currVFInstance, Service service, boolean shouldLock, boolean inTransaction) {
+ private Either<ArtifactDefinition, ResponseFormat> generateVfModuleInstanceArtifact(User modifier, ComponentInstance currVFInstance,
+ Service service, boolean shouldLock, boolean inTransaction) {
ArtifactDefinition vfModuleArtifact = null;
Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
Wrapper<String> payloadWrapper = new Wrapper<>();
@@ -1937,23 +1692,27 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
vfModuleArtifact = getVfModuleInstArtifactForCompInstance(currVFInstance, service, payloadWrapper, responseWrapper);
}
if (responseWrapper.isEmpty() && vfModuleArtifact != null) {
- vfModuleArtifact = fillVfModulePayload(modifier, currVFInstance, vfModuleArtifact, shouldLock, inTransaction, payloadWrapper, responseWrapper, service);
+ vfModuleArtifact = fillVfModulePayload(modifier, currVFInstance, vfModuleArtifact, shouldLock, inTransaction, payloadWrapper,
+ responseWrapper, service);
}
-
Either<ArtifactDefinition, ResponseFormat> result;
if (responseWrapper.isEmpty()) {
result = Either.left(vfModuleArtifact);
} else {
result = Either.right(responseWrapper.getInnerElement());
}
-
return result;
}
- private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleArtifact, boolean shouldLock, boolean inTransaction, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper, Service service) {
+ private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleArtifact, boolean shouldLock,
+ boolean inTransaction, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper,
+ Service service) {
ArtifactDefinition result = null;
- Either<ArtifactDefinition, ResponseFormat> eitherPayload = artifactsBusinessLogic.generateArtifactPayload(vfModuleArtifact, ComponentTypeEnum.RESOURCE_INSTANCE, service, currVF.getName(), modifier, shouldLock, inTransaction, System::currentTimeMillis,
- () -> Either.left(artifactsBusinessLogic.createEsArtifactData(vfModuleArtifact, payloadWrapper.getInnerElement().getBytes(StandardCharsets.UTF_8))), currVF.getUniqueId());
+ Either<ArtifactDefinition, ResponseFormat> eitherPayload = artifactsBusinessLogic
+ .generateArtifactPayload(vfModuleArtifact, ComponentTypeEnum.RESOURCE_INSTANCE, service, currVF.getName(), modifier, shouldLock,
+ inTransaction, System::currentTimeMillis, () -> Either.left(
+ artifactsBusinessLogic.createEsArtifactData(vfModuleArtifact, payloadWrapper.getInnerElement().getBytes(StandardCharsets.UTF_8))),
+ currVF.getUniqueId());
if (eitherPayload.isLeft()) {
result = eitherPayload.left().value();
} else {
@@ -1962,15 +1721,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
if (result == null) {
result = vfModuleArtifact;
}
-
return result;
}
- private Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact(ComponentInstance currVF, Service service, String vfModulePayloadString) {
-
+ private Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact(ComponentInstance currVF, Service service,
+ String vfModulePayloadString) {
ArtifactDefinition vfModuleArtifactDefinition = new ArtifactDefinition();
String newCheckSum = null;
-
vfModuleArtifactDefinition.setDescription("Auto-generated VF Modules information artifact");
vfModuleArtifactDefinition.setArtifactDisplayName("Vf Modules Metadata");
vfModuleArtifactDefinition.setArtifactType(ArtifactTypeEnum.VF_MODULES_METADATA.getType());
@@ -1983,54 +1740,54 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(vfModulePayloadString.getBytes());
}
vfModuleArtifactDefinition.setArtifactChecksum(newCheckSum);
-
- Either<ArtifactDefinition, StorageOperationStatus> addArtifactToComponent = artifactToscaOperation.addArtifactToComponent(
- vfModuleArtifactDefinition, service, NodeTypeEnum.ResourceInstance, true, currVF.getUniqueId());
-
+ Either<ArtifactDefinition, StorageOperationStatus> addArtifactToComponent = artifactToscaOperation
+ .addArtifactToComponent(vfModuleArtifactDefinition, service, NodeTypeEnum.ResourceInstance, true, currVF.getUniqueId());
Either<ArtifactDefinition, ResponseFormat> result;
if (addArtifactToComponent.isLeft()) {
result = Either.left(addArtifactToComponent.left().value());
} else {
- result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtifactToComponent.right().value())));
+ result = Either
+ .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtifactToComponent.right().value())));
}
-
return result;
}
public Either<Service, ResponseFormat> generateHeatEnvArtifacts(Service service, User modifier, boolean shouldLock, boolean inTransaction) {
-
Function<ComponentInstance, List<ArtifactGenerator<ArtifactDefinition>>> artifactTaskGeneratorCreator = resourceInstance ->
- // Get All Deployment Artifacts
- service.getComponentInstances().stream().filter(ri -> ri != null && ri == resourceInstance).filter(ri -> ri.getDeploymentArtifacts() != null).flatMap(ri -> ri.getDeploymentArtifacts().values().stream()).
- // Filter in Only Heat Env
- filter(depArtifact -> ArtifactTypeEnum.HEAT_ENV.getType().equals(depArtifact.getArtifactType())).
- // Create ArtifactGenerator from those Artifacts
- map(depArtifact -> new HeatEnvArtifactGenerator(depArtifact, service, resourceInstance.getName(), modifier, shouldLock, inTransaction, resourceInstance.getUniqueId())).collect(Collectors.toList());
-
+ // Get All Deployment Artifacts
+ service.getComponentInstances().stream().filter(ri -> ri != null && ri == resourceInstance)
+ .filter(ri -> ri.getDeploymentArtifacts() != null).flatMap(ri -> ri.getDeploymentArtifacts().values().stream()).
+ // Filter in Only Heat Env
+ filter(depArtifact -> ArtifactTypeEnum.HEAT_ENV.getType().equals(depArtifact.getArtifactType())).
+ // Create ArtifactGenerator from those Artifacts
+ map(
+ depArtifact -> new HeatEnvArtifactGenerator(depArtifact, service, resourceInstance.getName(), modifier, shouldLock, inTransaction,
+ resourceInstance.getUniqueId())).collect(Collectors.toList());
return generateDeploymentArtifacts(service, artifactTaskGeneratorCreator);
-
}
- private <CallVal> Either<Service, ResponseFormat> generateDeploymentArtifacts(Service service, Function<ComponentInstance, List<ArtifactGenerator<CallVal>>> artifactTaskGeneratorCreator) {
-
+ private <CallVal> Either<Service, ResponseFormat> generateDeploymentArtifacts(Service service,
+ Function<ComponentInstance, List<ArtifactGenerator<CallVal>>> artifactTaskGeneratorCreator) {
// Get Flat List of (Callable) ArtifactGenerator for all the RI in the
+
// service
if (service.getComponentInstances() != null) {
- List<ArtifactGenerator<CallVal>> artifactGenList = service.getComponentInstances().stream().flatMap(ri -> artifactTaskGeneratorCreator.apply(ri).stream()).collect(Collectors.toList());
+ List<ArtifactGenerator<CallVal>> artifactGenList = service.getComponentInstances().stream()
+ .flatMap(ri -> artifactTaskGeneratorCreator.apply(ri).stream()).collect(Collectors.toList());
if (artifactGenList != null && !artifactGenList.isEmpty()) {
Either<Service, ResponseFormat> callRes = checkDeploymentArtifact(artifactGenList);
- if (callRes != null) return callRes;
+ if (callRes != null) {
+ return callRes;
+ }
}
}
Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaFullElement(service.getUniqueId());
if (storageStatus.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""));
+ return Either.right(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""));
}
-
Service currentService = storageStatus.left().value();
-
return Either.left(currentService);
-
}
private <CallVal> Either<Service, ResponseFormat> checkDeploymentArtifact(List<ArtifactGenerator<CallVal>> artifactGenList) {
@@ -2050,61 +1807,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return null;
}
- abstract class ArtifactGenerator<CallVal> implements Callable<Either<CallVal, ResponseFormat>> {
-
- }
-
- @Getter
- class HeatEnvArtifactGenerator extends ArtifactGenerator<ArtifactDefinition> {
- private ArtifactDefinition artifactDefinition;
- private Service service;
- private String resourceInstanceName;
- private User modifier;
- private String instanceId;
- private boolean shouldLock;
- private boolean inTransaction;
-
- HeatEnvArtifactGenerator(ArtifactDefinition artifactDefinition, Service service, String resourceInstanceName, User modifier, boolean shouldLock, boolean inTransaction, String instanceId) {
- this.artifactDefinition = artifactDefinition;
- this.service = service;
- this.resourceInstanceName = resourceInstanceName;
- this.modifier = modifier;
- this.shouldLock = shouldLock;
- this.instanceId = instanceId;
- this.inTransaction = inTransaction;
- }
-
- @Override
- public Either<ArtifactDefinition, ResponseFormat> call() throws Exception {
- return artifactsBusinessLogic.forceGenerateHeatEnvArtifact(artifactDefinition, ComponentTypeEnum.RESOURCE_INSTANCE, service, resourceInstanceName, modifier, shouldLock, inTransaction, instanceId);
- }
-
- }
-
- class VfModuleArtifactGenerator extends ArtifactGenerator<ArtifactDefinition> {
- private User user;
- private ComponentInstance componentInstance;
- private Service service;
- boolean shouldLock;
- boolean inTransaction;
-
- @Override
- public Either<ArtifactDefinition, ResponseFormat> call() throws Exception {
- return generateVfModuleInstanceArtifact(user, componentInstance, service, shouldLock, inTransaction);
- }
-
- private VfModuleArtifactGenerator(User user, ComponentInstance componentInstance, Service service, boolean shouldLock, boolean inTransaction) {
- super();
- this.user = user;
- this.componentInstance = componentInstance;
- this.service = service;
- this.shouldLock = shouldLock;
- this.inTransaction = inTransaction;
- }
-
- }
-
- private synchronized Either<Service, ResponseFormat> checkDistributionAndDeploy(String distributionId, User user, AuditingActionEnum auditAction, Service service) {
+ private synchronized Either<Service, ResponseFormat> checkDistributionAndDeploy(String distributionId, User user, AuditingActionEnum auditAction,
+ Service service) {
boolean isDeployed = isDistributionDeployed(distributionId);
if (isDeployed) {
return Either.left(service);
@@ -2113,15 +1817,16 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
if (distributionSuccess.isRight()) {
return Either.right(distributionSuccess.right().value());
}
-
log.debug("mark distribution {} as deployed - success", distributionId);
- componentsUtils.auditServiceDistributionDeployed(service.getName(), service.getVersion(), service.getUUID(), distributionId, STATUS_DEPLOYED, "OK", user);
+ componentsUtils
+ .auditServiceDistributionDeployed(service.getName(), service.getVersion(), service.getUUID(), distributionId, STATUS_DEPLOYED, "OK",
+ user);
return Either.left(service);
}
private boolean isDistributionDeployed(String distributionId) {
- Either<List<DistributionDeployEvent>, ActionStatus> alreadyDeployed = auditCassandraDao.getDistributionDeployByStatus(distributionId, AuditingActionEnum.DISTRIBUTION_DEPLOY.getName(), STATUS_DEPLOYED);
-
+ Either<List<DistributionDeployEvent>, ActionStatus> alreadyDeployed = auditCassandraDao
+ .getDistributionDeployByStatus(distributionId, AuditingActionEnum.DISTRIBUTION_DEPLOY.getName(), STATUS_DEPLOYED);
boolean isDeployed = false;
if (alreadyDeployed.isLeft() && !alreadyDeployed.left().value().isEmpty()) {
// already deployed
@@ -2132,16 +1837,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
protected Either<Boolean, ResponseFormat> checkDistributionSuccess(String did, User user, AuditingActionEnum auditAction, Service service) {
-
log.trace("checkDistributionSuccess");
// get all "DRequest" records for this distribution
-
- Either<List<ResourceAdminEvent>, ActionStatus> distRequestsResponse = auditCassandraDao.getDistributionRequest(did, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName());
+ Either<List<ResourceAdminEvent>, ActionStatus> distRequestsResponse = auditCassandraDao
+ .getDistributionRequest(did, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName());
if (distRequestsResponse.isRight()) {
ResponseFormat error = auditDeployError(did, user, auditAction, service, distRequestsResponse.right().value());
return Either.right(error);
}
-
List<ResourceAdminEvent> distributionRequests = distRequestsResponse.left().value();
if (distributionRequests.isEmpty()) {
BeEcompErrorManager.getInstance().logBeDistributionMissingError("markDistributionAsDeployed", did);
@@ -2157,14 +1860,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
break;
}
}
-
// get all "DNotify" records for this distribution
- Either<List<DistributionNotificationEvent>, ActionStatus> distNotificationsResponse = auditCassandraDao.getDistributionNotify(did, AuditingActionEnum.DISTRIBUTION_NOTIFY.getName());
+ Either<List<DistributionNotificationEvent>, ActionStatus> distNotificationsResponse = auditCassandraDao
+ .getDistributionNotify(did, AuditingActionEnum.DISTRIBUTION_NOTIFY.getName());
if (distNotificationsResponse.isRight()) {
ResponseFormat error = auditDeployError(did, user, auditAction, service, distNotificationsResponse.right().value());
return Either.right(error);
}
-
List<DistributionNotificationEvent> distributionNotifications = distNotificationsResponse.left().value();
boolean isNotificationsSucceeded = false;
for (DistributionNotificationEvent event : distributionNotifications) {
@@ -2174,10 +1876,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
break;
}
}
-
// if request failed OR there are notifications that failed
if (!(isRequestSucceeded && isNotificationsSucceeded)) {
-
log.info("distribution {} has failed", did);
ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.DISTRIBUTION_REQUESTED_FAILED, did);
auditDeployError(did, user, auditAction, service, ActionStatus.DISTRIBUTION_REQUESTED_FAILED, did);
@@ -2186,17 +1886,18 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.left(true);
}
- private ResponseFormat auditDeployError(String did, User user, AuditingActionEnum auditAction, Service service, ActionStatus status, String... params) {
-
+ private ResponseFormat auditDeployError(String did, User user, AuditingActionEnum auditAction, Service service, ActionStatus status,
+ String... params) {
ResponseFormat error = componentsUtils.getResponseFormat(status, params);
String message = "";
if (error.getMessageId() != null) {
message = error.getMessageId() + ": ";
}
message += error.getFormattedMessage();
-
if (service != null) {
- componentsUtils.auditServiceDistributionDeployed(service.getName(), service.getVersion(), service.getUUID(), did, error.getStatus().toString(), message, user);
+ componentsUtils
+ .auditServiceDistributionDeployed(service.getName(), service.getVersion(), service.getUUID(), did, error.getStatus().toString(),
+ message, user);
} else {
componentsUtils.auditServiceDistributionDeployed("", "", "", did, error.getStatus().toString(), message, user);
}
@@ -2209,9 +1910,9 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
List<Role> roles = new ArrayList<>();
roles.add(Role.ADMIN);
roles.add(Role.DESIGNER);
- try{
+ try {
validateUserRole(user, service, roles, auditAction, null);
- } catch (ByActionStatusComponentException e){
+ } catch (ByActionStatusComponentException e) {
log.info("role {} is not allowed to perform this action", user.getRole());
auditDeployError(did, user, auditAction, service, e.getActionStatus());
throw e;
@@ -2221,28 +1922,27 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
@Override
public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
- if(component instanceof Service){
+ if (component instanceof Service) {
Service service = (Service) component;
Map<String, ArtifactDefinition> artifactMap = service.getDeploymentArtifacts();
if (artifactMap == null) {
artifactMap = new HashMap<>();
}
service.setDeploymentArtifacts(artifactMap);
- }else if(component instanceof Resource){
+ } else if (component instanceof Resource) {
Resource resource = (Resource) component;
Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
if (artifactMap == null) {
artifactMap = new HashMap<>();
}
- Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
- .getConfiguration().getDeploymentResourceArtifacts();
+ Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getDeploymentResourceArtifacts();
if (deploymentResourceArtifacts != null) {
Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
- deploymentResourceArtifacts.forEach((k, v)->processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k,v));
+ deploymentResourceArtifacts.forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v));
}
resource.setDeploymentArtifacts(artifactMap);
}
-
}
private void processDeploymentResourceArtifacts(User user, Resource resource, Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
@@ -2254,15 +1954,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return;
}
} else {
- log.info("resource types for artifact placeholder {} were not defined. default is all resources",
- k);
+ log.info("resource types for artifact placeholder {} were not defined. default is all resources", k);
}
if (artifactsBusinessLogic != null) {
- ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
- resource.getUniqueId(), k, (Map<String, Object>) v,
- user, ArtifactGroupTypeEnum.DEPLOYMENT);
- if (artifactDefinition != null
- && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
+ ArtifactDefinition artifactDefinition = artifactsBusinessLogic
+ .createArtifactPlaceHolderInfo(resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
+ if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
}
}
@@ -2274,7 +1971,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
+ .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
return webApplicationContext.getBean(HealthCheckBusinessLogic.class);
}
@@ -2286,16 +1984,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
@Override
public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, String userId) {
-
validateUserExists(userId);
Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
if (getComponentRes.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentRes.right().value()));
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentRes.right().value()));
return Either.right(responseFormat);
}
-
List<ComponentInstance> componentInstances = getComponentRes.left().value().getComponentInstances();
-
return Either.left(componentInstances);
}
@@ -2305,11 +2001,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
/**
- * updates group instance with new property values in case of successful update of group instance related component instance will be updated with new modification time and related service will be updated with new last update date
- *
+ * updates group instance with new property values in case of successful update of group instance related component instance will be updated with
+ * new modification time and related service will be updated with new last update date
*/
- public Either<List<GroupInstanceProperty>, ResponseFormat> updateGroupInstancePropertyValues(User modifier, String serviceId, String componentInstanceId, String groupInstanceId, List<GroupInstanceProperty> newProperties) {
-
+ public Either<List<GroupInstanceProperty>, ResponseFormat> updateGroupInstancePropertyValues(User modifier, String serviceId,
+ String componentInstanceId, String groupInstanceId,
+ List<GroupInstanceProperty> newProperties) {
Either<List<GroupInstanceProperty>, ResponseFormat> actionResult = null;
Either<ImmutablePair<Component, User>, ResponseFormat> validateUserAndComponentRes;
Component component = null;
@@ -2332,9 +2029,11 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
}
if (actionResult == null) {
- actionResult = validateAndUpdateGroupInstancePropertyValuesAndContainingParents(component, componentInstanceId, groupInstanceId, newProperties);
+ actionResult = validateAndUpdateGroupInstancePropertyValuesAndContainingParents(component, componentInstanceId, groupInstanceId,
+ newProperties);
if (actionResult.isRight()) {
- log.debug("Failed to validate and update group instance {} property values and containing parents. The message is {}. ", groupInstanceId, actionResult.right().value().getFormattedMessage());
+ log.debug("Failed to validate and update group instance {} property values and containing parents. The message is {}. ",
+ groupInstanceId, actionResult.right().value().getFormattedMessage());
}
}
} catch (Exception e) {
@@ -2348,8 +2047,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return actionResult;
}
- private Either<List<GroupInstanceProperty>, ResponseFormat> validateAndUpdateGroupInstancePropertyValuesAndContainingParents(Component component, String componentInstanceId, String groupInstanceId, List<GroupInstanceProperty> newProperties) {
-
+ private Either<List<GroupInstanceProperty>, ResponseFormat> validateAndUpdateGroupInstancePropertyValuesAndContainingParents(Component component,
+ String componentInstanceId,
+ String groupInstanceId,
+ List<GroupInstanceProperty> newProperties) {
Either<List<GroupInstanceProperty>, ResponseFormat> actionResult = null;
Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes;
Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> updateParentsModificationTimeRes;
@@ -2366,18 +2067,23 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
if (actionResult == null) {
oldGroupInstance = findGroupInstanceRes.left().value().getValue();
relatedComponentInstance = findGroupInstanceRes.left().value().getKey();
- updateGroupInstanceResult = groupBusinessLogic.validateAndUpdateGroupInstancePropertyValues(component.getUniqueId(), componentInstanceId, oldGroupInstance, newProperties);
+ updateGroupInstanceResult = groupBusinessLogic
+ .validateAndUpdateGroupInstancePropertyValues(component.getUniqueId(), componentInstanceId, oldGroupInstance, newProperties);
if (updateGroupInstanceResult.isRight()) {
- log.debug("#validateAndUpdateGroupInstancePropertyValuesAndContainingParents - Failed to update group instance {} property values. ", oldGroupInstance.getName());
+ log.debug("#validateAndUpdateGroupInstancePropertyValuesAndContainingParents - Failed to update group instance {} property values. ",
+ oldGroupInstance.getName());
actionResult = Either.right(updateGroupInstanceResult.right().value());
}
}
if (actionResult == null) {
updatedGroupInstance = updateGroupInstanceResult.left().value();
if (!oldGroupInstance.getModificationTime().equals(updatedGroupInstance.getModificationTime())) {
- updateParentsModificationTimeRes = updateParentsModificationTimeAndCustomizationUuid(component, relatedComponentInstance, updatedGroupInstance, inTransaction);
+ updateParentsModificationTimeRes = updateParentsModificationTimeAndCustomizationUuid(component, relatedComponentInstance,
+ updatedGroupInstance, inTransaction);
if (updateParentsModificationTimeRes.isRight()) {
- log.debug("#validateAndUpdateGroupInstancePropertyValuesAndContainingParents - Failed to update modification time for group instance {}. ", oldGroupInstance.getName());
+ log.debug(
+ "#validateAndUpdateGroupInstancePropertyValuesAndContainingParents - Failed to update modification time for group instance {}. ",
+ oldGroupInstance.getName());
actionResult = Either.right(updateParentsModificationTimeRes.right().value());
}
}
@@ -2388,30 +2094,33 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return actionResult;
}
- private Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> updateParentsModificationTimeAndCustomizationUuid(Component component, ComponentInstance relatedComponentInstance, GroupInstance updatedGroupInstance,
- boolean inTranscation) {
-
+ private Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> updateParentsModificationTimeAndCustomizationUuid(
+ Component component, ComponentInstance relatedComponentInstance, GroupInstance updatedGroupInstance, boolean inTranscation) {
Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> actionResult;
Either<ComponentMetadataData, StorageOperationStatus> serviceMetadataUpdateResult;
- Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceRes = componentInstanceBusinessLogic.updateComponentInstanceModificationTimeAndCustomizationUuid(relatedComponentInstance, NodeTypeEnum.ResourceInstance,
+ Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceRes = componentInstanceBusinessLogic
+ .updateComponentInstanceModificationTimeAndCustomizationUuid(relatedComponentInstance, NodeTypeEnum.ResourceInstance,
updatedGroupInstance.getModificationTime(), inTranscation);
if (updateComponentInstanceRes.isRight()) {
- log.debug("Failed to update component instance {} after update of group instance {}. ", relatedComponentInstance.getName(), updatedGroupInstance.getName());
+ log.debug("Failed to update component instance {} after update of group instance {}. ", relatedComponentInstance.getName(),
+ updatedGroupInstance.getName());
actionResult = Either.right(updateComponentInstanceRes.right().value());
} else {
serviceMetadataUpdateResult = toscaOperationFacade.updateComponentLastUpdateDateOnGraph(component);
if (serviceMetadataUpdateResult.isRight()) {
- log.debug("Failed to update service {} after update of component instance {} with new property values of group instance {}. ", component.getName(), relatedComponentInstance.getName(), updatedGroupInstance.getName());
- actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceMetadataUpdateResult.right().value())));
+ log.debug("Failed to update service {} after update of component instance {} with new property values of group instance {}. ",
+ component.getName(), relatedComponentInstance.getName(), updatedGroupInstance.getName());
+ actionResult = Either.right(
+ componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceMetadataUpdateResult.right().value())));
} else {
- actionResult = Either.left(new ImmutablePair<>(serviceMetadataUpdateResult.left().value(), updateComponentInstanceRes.left().value()));
+ actionResult = Either
+ .left(new ImmutablePair<>(serviceMetadataUpdateResult.left().value(), updateComponentInstanceRes.left().value()));
}
}
return actionResult;
}
private Either<ImmutablePair<Component, User>, ResponseFormat> validateUserAndComponent(String serviceId, User modifier) {
-
Either<ImmutablePair<Component, User>, ResponseFormat> result = null;
User currUser = null;
Component component = null;
@@ -2425,7 +2134,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
try {
component = validateComponentExists(serviceId, ComponentTypeEnum.SERVICE, null);
if (!ComponentValidationUtils.canWorkOnComponent(component, currUser.getUserId())) {
- log.info("#validateUserAndComponent - Restricted operation for user: {}, on service: {}", currUser.getUserId(), component.getCreatorUserId());
+ log.info("#validateUserAndComponent - Restricted operation for user: {}, on service: {}", currUser.getUserId(),
+ component.getCreatorUserId());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
} catch (ComponentException e) {
@@ -2433,27 +2143,31 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
result = Either.right(e.getResponseFormat());
}
}
-
if (result == null) {
result = Either.left(new ImmutablePair<>(component, currUser));
}
return result;
}
- private Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceOnRelatedComponentInstance(Component component, String componentInstanceId, String groupInstanceId) {
-
+ private Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceOnRelatedComponentInstance(Component component,
+ String componentInstanceId,
+ String groupInstanceId) {
Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> actionResult = null;
GroupInstance groupInstance = null;
ComponentInstance foundComponentInstance = findRelatedComponentInstance(component, componentInstanceId);
if (foundComponentInstance == null) {
log.debug("Component instance {} not found on service {}. ", componentInstanceId, component.getName());
- actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstanceId, "resource instance", "service", component.getName()));
- }
- else if (isNotEmpty(foundComponentInstance.getGroupInstances())) {
- groupInstance = foundComponentInstance.getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstanceId)).findFirst().orElse(null);
+ actionResult = Either.right(componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstanceId, "resource instance", "service",
+ component.getName()));
+ } else if (isNotEmpty(foundComponentInstance.getGroupInstances())) {
+ groupInstance = foundComponentInstance.getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstanceId)).findFirst()
+ .orElse(null);
if (groupInstance == null) {
log.debug("Group instance {} not found on component instance {}. ", groupInstanceId, foundComponentInstance.getName());
- actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INSTANCE_NOT_FOUND_ON_COMPONENT_INSTANCE, groupInstanceId, foundComponentInstance.getName()));
+ actionResult = Either.right(componentsUtils
+ .getResponseFormat(ActionStatus.GROUP_INSTANCE_NOT_FOUND_ON_COMPONENT_INSTANCE, groupInstanceId,
+ foundComponentInstance.getName()));
}
}
if (actionResult == null) {
@@ -2465,7 +2179,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
private ComponentInstance findRelatedComponentInstance(Component component, String componentInstanceId) {
ComponentInstance componentInstance = null;
if (isNotEmpty(component.getComponentInstances())) {
- componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null);
+ componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst()
+ .orElse(null);
}
return componentInstance;
}
@@ -2479,28 +2194,24 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.left(user);
}
- public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String serviceId, List<String> dataParamsToReturn) {
-
+ public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String serviceId,
+ List<String> dataParamsToReturn) {
ComponentParametersView paramsToReturn = new ComponentParametersView(dataParamsToReturn);
paramsToReturn.setIgnoreComponentInstancesProperties(false);
Either<Service, StorageOperationStatus> serviceResultEither = toscaOperationFacade.getToscaElement(serviceId, paramsToReturn);
-
if (serviceResultEither.isRight()) {
- if(serviceResultEither.right().value() == StorageOperationStatus.NOT_FOUND) {
+ if (serviceResultEither.right().value() == StorageOperationStatus.NOT_FOUND) {
log.debug("#getUiComponentDataTransferByComponentId - Failed to find service with id {} ", serviceId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId));
}
-
log.debug("#getUiComponentDataTransferByComponentId - failed to get service by id {} with filters {}", serviceId, dataParamsToReturn);
- return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(serviceResultEither.right().value()), ""));
+ return Either.right(
+ componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(serviceResultEither.right().value()), ""));
}
-
Service service = serviceResultEither.left().value();
- if (dataParamsToReturn.contains(ComponentFieldsEnum.INPUTS.getValue())) {
- ListUtils.emptyIfNull(service.getInputs())
- .forEach(input -> input.setConstraints(setInputConstraint(input)));
- }
-
+ if (dataParamsToReturn.contains(ComponentFieldsEnum.INPUTS.getValue())) {
+ ListUtils.emptyIfNull(service.getInputs()).forEach(input -> input.setConstraints(setInputConstraint(input)));
+ }
UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromServiceByParams(service, dataParamsToReturn);
return Either.left(dataTransfer);
}
@@ -2514,4 +2225,62 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
Either<Service, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByServiceName(serviceName);
return latestByName.isLeft();
}
+
+ abstract class ArtifactGenerator<CallVal> implements Callable<Either<CallVal, ResponseFormat>> {
+
+ }
+
+ @Getter
+ class HeatEnvArtifactGenerator extends ArtifactGenerator<ArtifactDefinition> {
+
+ private ArtifactDefinition artifactDefinition;
+ private Service service;
+ private String resourceInstanceName;
+ private User modifier;
+ private String instanceId;
+ private boolean shouldLock;
+ private boolean inTransaction;
+
+ HeatEnvArtifactGenerator(ArtifactDefinition artifactDefinition, Service service, String resourceInstanceName, User modifier,
+ boolean shouldLock, boolean inTransaction, String instanceId) {
+ this.artifactDefinition = artifactDefinition;
+ this.service = service;
+ this.resourceInstanceName = resourceInstanceName;
+ this.modifier = modifier;
+ this.shouldLock = shouldLock;
+ this.instanceId = instanceId;
+ this.inTransaction = inTransaction;
+ }
+
+ @Override
+ public Either<ArtifactDefinition, ResponseFormat> call() throws Exception {
+ return artifactsBusinessLogic
+ .forceGenerateHeatEnvArtifact(artifactDefinition, ComponentTypeEnum.RESOURCE_INSTANCE, service, resourceInstanceName, modifier,
+ shouldLock, inTransaction, instanceId);
+ }
+ }
+
+ class VfModuleArtifactGenerator extends ArtifactGenerator<ArtifactDefinition> {
+
+ boolean shouldLock;
+ boolean inTransaction;
+ private User user;
+ private ComponentInstance componentInstance;
+ private Service service;
+
+ private VfModuleArtifactGenerator(User user, ComponentInstance componentInstance, Service service, boolean shouldLock,
+ boolean inTransaction) {
+ super();
+ this.user = user;
+ this.componentInstance = componentInstance;
+ this.service = service;
+ this.shouldLock = shouldLock;
+ this.inTransaction = inTransaction;
+ }
+
+ @Override
+ public Either<ArtifactDefinition, ResponseFormat> call() throws Exception {
+ return generateVfModuleInstanceArtifact(user, componentInstance, service, shouldLock, inTransaction);
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogic.java
index 0ffceda8e8..2956abfe1b 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogic.java
@@ -15,7 +15,26 @@
*/
package org.openecomp.sdc.be.components.impl;
+import static java.util.stream.Collectors.joining;
+import static java.util.stream.Collectors.toList;
+import static java.util.stream.Collectors.toMap;
+import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
+import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement;
+import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
+import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
+
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.regex.Pattern;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections.CollectionUtils;
@@ -117,32 +136,11 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.yaml.snakeyaml.Yaml;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-import java.util.regex.Pattern;
-
-import static java.util.stream.Collectors.joining;
-import static java.util.stream.Collectors.toList;
-import static java.util.stream.Collectors.toMap;
-import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
-import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement;
-import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
-import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
-
@Getter
@Setter
@org.springframework.stereotype.Component("serviceImportBusinessLogic")
public class ServiceImportBusinessLogic {
- private final UiComponentDataConverter uiComponentDataConverter;
private static final String INITIAL_VERSION = "0.1";
private static final String CREATE_RESOURCE = "Create Resource";
private static final String IN_RESOURCE = " in resource {} ";
@@ -153,25 +151,18 @@ public class ServiceImportBusinessLogic {
private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
-
- @Autowired
- private ServiceBusinessLogic serviceBusinessLogic;
-
- public ServiceBusinessLogic getServiceBusinessLogic() {
- return serviceBusinessLogic;
- }
-
- public void setServiceBusinessLogic(ServiceBusinessLogic serviceBusinessLogic) {
- this.serviceBusinessLogic = serviceBusinessLogic;
- }
-
- @Autowired
- private CsarBusinessLogic csarBusinessLogic;
+ private static final Logger log = Logger.getLogger(ServiceImportBusinessLogic.class);
+ private final UiComponentDataConverter uiComponentDataConverter;
+ private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
@Autowired
protected ComponentsUtils componentsUtils;
@Autowired
protected ToscaOperationFacade toscaOperationFacade;
@Autowired
+ private ServiceBusinessLogic serviceBusinessLogic;
+ @Autowired
+ private CsarBusinessLogic csarBusinessLogic;
+ @Autowired
private CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
@Autowired
private LifecycleBusinessLogic lifecycleBusinessLogic;
@@ -182,33 +173,30 @@ public class ServiceImportBusinessLogic {
@Autowired
private ServiceImportParseLogic serviceImportParseLogic;
- private static final Logger log = Logger.getLogger(ServiceImportBusinessLogic.class);
-
@Autowired
- public ServiceImportBusinessLogic(IElementOperation elementDao,
- IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation,
- IGroupTypeOperation groupTypeOperation,
- GroupBusinessLogic groupBusinessLogic,
- InterfaceOperation interfaceOperation,
- InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
- ArtifactsBusinessLogic artifactsBusinessLogic,
- IDistributionEngine distributionEngine, ComponentInstanceBusinessLogic componentInstanceBusinessLogic,
+ public ServiceImportBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+ IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic,
+ InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+ ArtifactsBusinessLogic artifactsBusinessLogic, IDistributionEngine distributionEngine,
+ ComponentInstanceBusinessLogic componentInstanceBusinessLogic,
ServiceDistributionValidation serviceDistributionValidation, ForwardingPathValidator forwardingPathValidator,
UiComponentDataConverter uiComponentDataConverter, NodeFilterOperation serviceFilterOperation,
NodeFilterValidator serviceFilterValidator, ArtifactsOperations artifactToscaOperation,
- ComponentContactIdValidator componentContactIdValidator,
- ComponentNameValidator componentNameValidator,
- ComponentTagsValidator componentTagsValidator,
- ComponentValidator componentValidator,
- ComponentIconValidator componentIconValidator,
- ComponentProjectCodeValidator componentProjectCodeValidator,
+ ComponentContactIdValidator componentContactIdValidator, ComponentNameValidator componentNameValidator,
+ ComponentTagsValidator componentTagsValidator, ComponentValidator componentValidator,
+ ComponentIconValidator componentIconValidator, ComponentProjectCodeValidator componentProjectCodeValidator,
ComponentDescriptionValidator componentDescriptionValidator) {
this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
this.uiComponentDataConverter = uiComponentDataConverter;
}
- private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
+ public ServiceBusinessLogic getServiceBusinessLogic() {
+ return serviceBusinessLogic;
+ }
+
+ public void setServiceBusinessLogic(ServiceBusinessLogic serviceBusinessLogic) {
+ this.serviceBusinessLogic = serviceBusinessLogic;
+ }
public Service createService(Service service, AuditingActionEnum auditingAction, User user, Map<String, byte[]> csarUIPayload,
String payloadName) {
@@ -221,13 +209,10 @@ public class ServiceImportBusinessLogic {
service.setInstantiationType("A-la-carte");
service.setEnvironmentContext("General_Revenue-Bearing");
service.setEcompGeneratedNaming(true);
-
try {
serviceBusinessLogic.validateServiceBeforeCreate(service, user, auditingAction);
-
log.debug("enter createService,validateServiceBeforeCreate success");
String csarUUID = payloadName == null ? service.getCsarUUID() : payloadName;
-
log.debug("enter createService,get csarUUID:{}", csarUUID);
csarBusinessLogic.validateCsarBeforeCreate(service, csarUUID);
log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
@@ -242,36 +227,30 @@ public class ServiceImportBusinessLogic {
log.trace("************* created successfully from YAML, resource TOSCA ");
try {
CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(service, null, user, csarUIPayload, csarUUID);
-
Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = serviceImportParseLogic
- .findNodeTypesArtifactsToHandle(
- nodeTypesInfo, csarInfo, service);
+ .findNodeTypesArtifactsToHandle(nodeTypesInfo, csarInfo, service);
if (findNodeTypesArtifactsToHandleRes.isRight()) {
- log.debug("failed to find node types for update with artifacts during import csar {}. ",
- csarInfo.getCsarUUID());
+ log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID());
throw new ComponentException(findNodeTypesArtifactsToHandleRes.right().value());
}
- return createServiceFromYaml(service, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(),
- nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false,
- null);
+ return createServiceFromYaml(service, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(), nodeTypesInfo, csarInfo,
+ findNodeTypesArtifactsToHandleRes.left().value(), true, false, null);
} catch (Exception e) {
log.debug("Exception occured when createServiceFromCsar,error is:{}", e.getMessage(), e);
throw new ComponentException(ActionStatus.GENERAL_ERROR);
}
}
- protected Service createServiceFromYaml(Service service, String topologyTemplateYaml,
- String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
+ protected Service createServiceFromYaml(Service service, String topologyTemplateYaml, String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo,
+ CsarInfo csarInfo,
Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
boolean shouldLock, boolean inTransaction, String nodeName) {
-
List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
Service createdService;
CreateServiceFromYamlParameter csfyp = new CreateServiceFromYamlParameter();
try {
- ParsedToscaYamlInfo
- parsedToscaYamlInfo = csarBusinessLogic
+ ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic
.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, service);
if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances())) {
throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
@@ -284,7 +263,6 @@ public class ServiceImportBusinessLogic {
csfyp.setNodeTypesInfo(nodeTypesInfo);
csfyp.setCsarInfo(csarInfo);
csfyp.setNodeName(nodeName);
-
createdService = createServiceAndRIsFromYaml(service, false, nodeTypesArtifactsToCreate, shouldLock, inTransaction, csfyp);
log.debug("#createResourceFromYaml - The resource {} has been created ", service.getName());
} catch (ComponentException e) {
@@ -300,7 +278,6 @@ public class ServiceImportBusinessLogic {
protected Service createServiceAndRIsFromYaml(Service service, boolean isNormative,
Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
boolean shouldLock, boolean inTransaction, CreateServiceFromYamlParameter csfyp) {
-
List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
String yamlName = csfyp.getYamlName();
ParsedToscaYamlInfo parsedToscaYamlInfo = csfyp.getParsedToscaYamlInfo();
@@ -309,7 +286,6 @@ public class ServiceImportBusinessLogic {
Map<String, NodeTypeInfo> nodeTypesInfo = csfyp.getNodeTypesInfo();
CsarInfo csarInfo = csfyp.getCsarInfo();
String nodeName = csfyp.getNodeName();
-
if (shouldLock) {
Either<Boolean, ResponseFormat> lockResult = serviceBusinessLogic.lockComponentByName(service.getSystemName(), service, CREATE_RESOURCE);
if (lockResult.isRight()) {
@@ -322,18 +298,13 @@ public class ServiceImportBusinessLogic {
log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
service = serviceImportParseLogic.createServiceTransaction(service, csarInfo.getModifier(), isNormative);
log.trace("************* Going to add inputs from yaml {}", yamlName);
-
Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
service = serviceImportParseLogic.createInputsOnService(service, inputs);
log.trace("************* Finish to add inputs from yaml {}", yamlName);
-
- Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
- .getInstances();
+ Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
-
- service = createRIAndRelationsFromYaml(yamlName, service, uploadComponentInstanceInfoMap,
- topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
- nodeTypesArtifactsToCreate, nodeName);
+ service = createRIAndRelationsFromYaml(yamlName, service, uploadComponentInstanceInfoMap, topologyTemplateYaml,
+ nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName);
log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = serviceBusinessLogic.groupBusinessLogic
.validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), service.getSystemName());
@@ -343,13 +314,11 @@ public class ServiceImportBusinessLogic {
}
Map<String, GroupDefinition> groups;
log.trace("************* Going to add groups from yaml {}", yamlName);
-
if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
groups = validateUpdateVfGroupNamesRes.left().value();
} else {
groups = parsedToscaYamlInfo.getGroups();
}
-
Either<Service, ResponseFormat> createGroupsOnResource = createGroupsOnResource(service, groups);
if (createGroupsOnResource.isRight()) {
serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
@@ -357,13 +326,9 @@ public class ServiceImportBusinessLogic {
}
service = createGroupsOnResource.left().value();
log.trace("************* Going to add artifacts from yaml {}", yamlName);
-
- NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
- nodeTypesArtifactsToCreate);
-
- Either<Service, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(
- ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, createdArtifacts, yamlName,
- csarInfo, service, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
+ NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
+ Either<Service, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE,
+ createdArtifacts, yamlName, csarInfo, service, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
if (createArtifactsEither.isRight()) {
serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
throw new ComponentException(createArtifactsEither.right().value());
@@ -379,27 +344,24 @@ public class ServiceImportBusinessLogic {
serviceBusinessLogic.janusGraphDao.commit();
}
if (shouldLock) {
- serviceBusinessLogic.graphLockOperation.unlockComponentByName(service.getSystemName(), service.getUniqueId(),
- NodeTypeEnum.Resource);
+ serviceBusinessLogic.graphLockOperation.unlockComponentByName(service.getSystemName(), service.getUniqueId(), NodeTypeEnum.Resource);
}
}
}
- protected Either<Resource, ResponseFormat> createOrUpdateArtifacts(
- ArtifactsBusinessLogic.ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
- String yamlFileName, CsarInfo csarInfo, Resource preparedResource,
- NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) {
-
+ protected Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum operation,
+ List<ArtifactDefinition> createdArtifacts, String yamlFileName,
+ CsarInfo csarInfo, Resource preparedResource,
+ NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts,
+ boolean inTransaction, boolean shouldLock) {
String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
Resource resource = preparedResource;
-
Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
.getNodeTypesArtifactsToHandle();
if (preparedResource.getResourceType() == ResourceTypeEnum.VF) {
if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) {
- Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
- handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(),
- inTransaction, true);
+ Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = handleNodeTypeArtifacts(preparedResource,
+ nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
if (handleNodeTypeArtifactsRes.isRight()) {
return Either.right(handleNodeTypeArtifactsRes.right().value());
}
@@ -416,28 +378,25 @@ public class ServiceImportBusinessLogic {
return Either.left(resource);
}
- protected Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo,
- List<ArtifactDefinition> createdArtifacts,
+ protected Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo, List<ArtifactDefinition> createdArtifacts,
ArtifactOperationInfo artifactOperation, boolean shouldLock,
boolean inTransaction) {
if (csarInfo.getCsar() != null) {
createOrUpdateSingleNonMetaArtifactToComstants(resource, csarInfo, artifactOperation, shouldLock, inTransaction);
-
- Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource,
- createdArtifacts, shouldLock, inTransaction, artifactOperation);
+ Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, createdArtifacts, shouldLock,
+ inTransaction, artifactOperation);
if (eitherCreateResult.isRight()) {
return Either.right(eitherCreateResult.right().value());
}
Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
if (eitherGerResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
return Either.right(responseFormat);
}
resource = eitherGerResource.left().value();
Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
-
if (artifacsMetaCsarStatus.isLeft()) {
return getResourceResponseFormatEither(resource, csarInfo, createdArtifacts, artifactOperation, shouldLock, inTransaction,
artifacsMetaCsarStatus);
@@ -465,17 +424,13 @@ public class ServiceImportBusinessLogic {
}
}
}
- createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
- CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
- ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
- Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
- Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true, shouldLock,
- inTransaction);
- createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
- CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
- ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
- Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
+ createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL,
+ Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
+ Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId,
artifactOperation, null, true, shouldLock, inTransaction);
+ createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
+ ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL, Constants.VF_LICENSE_DISPLAY_NAME,
+ Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, true, shouldLock, inTransaction);
}
protected Either<Resource, ResponseFormat> getResourceResponseFormatEither(Resource resource, CsarInfo csarInfo,
@@ -489,12 +444,11 @@ public class ServiceImportBusinessLogic {
Either<Resource, ResponseFormat> createArtifactsFromCsar;
if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic
- .createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName,
- createdArtifacts);
+ .createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts);
} else {
Either<Component, ResponseFormat> result = csarArtifactsAndGroupsBusinessLogic
- .updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName,
- createdArtifacts, shouldLock, inTransaction);
+ .updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock,
+ inTransaction);
if ((result.left().value() instanceof Resource) && result.isLeft()) {
Resource service1 = (Resource) result.left().value();
createArtifactsFromCsar = Either.left(service1);
@@ -522,11 +476,10 @@ public class ServiceImportBusinessLogic {
try {
Either<List<CsarUtils.NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages);
if (artifactPathAndNameList.isRight()) {
- return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
- ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value()));
+ return Either.right(
+ getComponentsUtils().getResponseFormatByArtifactId(ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value()));
}
EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
-
if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
vfCsarArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value());
@@ -558,30 +511,21 @@ public class ServiceImportBusinessLogic {
protected Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
- boolean inTransaction,
- ArtifactOperationInfo artifactOperation) {
+ boolean inTransaction, ArtifactOperationInfo artifactOperation) {
return createOrUpdateNonMetaArtifactsComp(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation);
}
protected <T extends Component> Either<T, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Component comp,
List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
- boolean inTransaction,
- Either<T, ResponseFormat> resStatus,
+ boolean inTransaction, Either<T, ResponseFormat> resStatus,
EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
for (Map.Entry<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
.entrySet()) {
- Optional<ResponseFormat> optionalCreateInDBError =
- currArtifactOperationPair.getValue().stream()
- .map(e -> createOrUpdateSingleNonMetaArtifact(comp, csarInfo, e.getPath(),
- e.getArtifactName(), e.getArtifactType(),
- e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
- CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
- new ArtifactOperationInfo(false, false,
- currArtifactOperationPair.getKey()),
- createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
- .filter(Either::isRight).
- map(e -> e.right().value()).
- findAny();
+ Optional<ResponseFormat> optionalCreateInDBError = currArtifactOperationPair.getValue().stream().map(
+ e -> createOrUpdateSingleNonMetaArtifact(comp, csarInfo, e.getPath(), e.getArtifactName(), e.getArtifactType(),
+ e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
+ new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts, e.isFromCsar(), shouldLock,
+ inTransaction)).filter(Either::isRight).map(e -> e.right().value()).findAny();
if (optionalCreateInDBError.isPresent()) {
resStatus = Either.right(optionalCreateInDBError.get());
break;
@@ -590,17 +534,14 @@ public class ServiceImportBusinessLogic {
return resStatus;
}
- protected Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Component component, CsarInfo csarInfo,
- String artifactPath, String artifactFileName, String artifactType,
- ArtifactGroupTypeEnum artifactGroupType,
- String artifactLabel, String artifactDisplayName,
- String artifactDescription, String artifactId,
- ArtifactOperationInfo operation,
+ protected Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Component component, CsarInfo csarInfo, String artifactPath,
+ String artifactFileName, String artifactType,
+ ArtifactGroupTypeEnum artifactGroupType, String artifactLabel,
+ String artifactDisplayName, String artifactDescription,
+ String artifactId, ArtifactOperationInfo operation,
List<ArtifactDefinition> createdArtifacts, boolean isFromCsar,
- boolean shouldLock,
- boolean inTransaction) {
+ boolean shouldLock, boolean inTransaction) {
byte[] artifactFileBytes = null;
-
if (csarInfo.getCsar().containsKey(artifactPath)) {
artifactFileBytes = csarInfo.getCsar().get(artifactPath);
}
@@ -609,33 +550,27 @@ public class ServiceImportBusinessLogic {
|| operation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE) {
if (serviceImportParseLogic.isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
Either<ArtifactDefinition, ResponseFormat> handleDelete = serviceBusinessLogic.artifactsBusinessLogic
- .handleDelete(component.getUniqueId(), artifactId, csarInfo.getModifier(), component,
- shouldLock, inTransaction);
+ .handleDelete(component.getUniqueId(), artifactId, csarInfo.getModifier(), component, shouldLock, inTransaction);
if (handleDelete.isRight()) {
result = Either.right(handleDelete.right().value());
}
return result;
}
if (org.apache.commons.lang.StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
- operation = new ArtifactOperationInfo(false, false,
- ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE);
+ operation = new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE);
}
}
if (artifactFileBytes != null) {
Map<String, Object> vendorLicenseModelJson = ArtifactUtils
- .buildJsonForUpdateArtifact(artifactId, artifactFileName,
- artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription,
- artifactFileBytes, null, isFromCsar);
+ .buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName,
+ artifactDescription, artifactFileBytes, null, isFromCsar);
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic
- .createOrUpdateCsarArtifactFromJson(
- component, csarInfo.getModifier(), vendorLicenseModelJson, operation);
- serviceImportParseLogic
- .addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
+ .createOrUpdateCsarArtifactFromJson(component, csarInfo.getModifier(), vendorLicenseModelJson, operation);
+ serviceImportParseLogic.addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
if (eitherNonMetaArtifacts.isRight()) {
- BeEcompErrorManager.getInstance()
- .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: "
- + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
- BeEcompErrorManager.ErrorSeverity.WARNING);
+ BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact",
+ "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
+ BeEcompErrorManager.ErrorSeverity.WARNING);
return Either.right(eitherNonMetaArtifacts.right().value());
}
}
@@ -655,7 +590,6 @@ public class ServiceImportBusinessLogic {
return Either.right(changeStateResponse.right().value());
}
nodeTypeResource = changeStateResponse.left().value();
-
List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
for (Map.Entry<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
@@ -663,13 +597,10 @@ public class ServiceImportBusinessLogic {
ArtifactsBusinessLogic.ArtifactOperationEnum curOperation = curOperationEntry.getKey();
List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
- log.debug("************* Going to {} artifact to vfc {}", curOperation.name(),
- nodeTypeResource.getName());
+ log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), nodeTypeResource.getName());
handleNodeTypeArtifactsRequestRes = serviceBusinessLogic.artifactsBusinessLogic
- .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user,
- createdArtifacts, new ArtifactOperationInfo(false,
- ignoreLifecycleState, curOperation),
- false, inTransaction);
+ .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, createdArtifacts,
+ new ArtifactOperationInfo(false, ignoreLifecycleState, curOperation), false, inTransaction);
if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(curOperation)) {
createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
}
@@ -692,11 +623,10 @@ public class ServiceImportBusinessLogic {
try {
if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState()
.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
- Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(
- resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
- new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
- LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR),
- inTransaction, true);
+ Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic
+ .changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
+ new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
+ LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR), inTransaction, true);
if (checkoutRes.isRight()) {
checkoutResourceRes = Either.right(checkoutRes.right().value());
} else {
@@ -708,32 +638,27 @@ public class ServiceImportBusinessLogic {
} catch (Exception e) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
checkoutResourceRes = Either.right(responseFormat);
- log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(),
- e);
+ log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), e);
}
return checkoutResourceRes;
}
- protected Either<Service, ResponseFormat> createOrUpdateArtifacts(
- ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
- String yamlFileName, CsarInfo csarInfo, Service preparedService,
- NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) {
-
+ protected Either<Service, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
+ String yamlFileName, CsarInfo csarInfo, Service preparedService,
+ NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts,
+ boolean inTransaction, boolean shouldLock) {
Either<Service, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedService, csarInfo, createdArtifacts,
new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
if (createdCsarArtifactsEither.isRight()) {
return createdCsarArtifactsEither;
}
-
return Either.left(createdCsarArtifactsEither.left().value());
}
- protected Either<Service, ResponseFormat> handleVfCsarArtifacts(Service service, CsarInfo csarInfo,
- List<ArtifactDefinition> createdArtifacts,
+ protected Either<Service, ResponseFormat> handleVfCsarArtifacts(Service service, CsarInfo csarInfo, List<ArtifactDefinition> createdArtifacts,
ArtifactOperationInfo artifactOperation, boolean shouldLock,
boolean inTransaction) {
-
if (csarInfo.getCsar() != null) {
String vendorLicenseModelId = null;
String vfLicenseModelId = null;
@@ -750,34 +675,29 @@ public class ServiceImportBusinessLogic {
}
}
}
- createOrUpdateSingleNonMetaArtifact(service, csarInfo,
- CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
- ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
- Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
- Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true, shouldLock,
- inTransaction);
- createOrUpdateSingleNonMetaArtifact(service, csarInfo,
- CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
- ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
- Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
+ createOrUpdateSingleNonMetaArtifact(service, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL,
+ Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
+ Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId,
artifactOperation, null, true, shouldLock, inTransaction);
-
- Either<Service, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, service,
- createdArtifacts, shouldLock, inTransaction, artifactOperation);
+ createOrUpdateSingleNonMetaArtifact(service, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
+ ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
+ Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, true, shouldLock,
+ inTransaction);
+ Either<Service, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, service, createdArtifacts, shouldLock,
+ inTransaction, artifactOperation);
if (eitherCreateResult.isRight()) {
return Either.right(eitherCreateResult.right().value());
}
- Either<Service, StorageOperationStatus> eitherGerResource = toscaOperationFacade
- .getToscaElement(service.getUniqueId());
+ Either<Service, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
if (eitherGerResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(
- componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), service, ComponentTypeEnum.SERVICE);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), service,
+ ComponentTypeEnum.SERVICE);
return Either.right(responseFormat);
}
service = eitherGerResource.left().value();
Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
-
if (artifacsMetaCsarStatus.isLeft()) {
String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
@@ -810,8 +730,7 @@ public class ServiceImportBusinessLogic {
protected Either<Service, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Service resource,
List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
- boolean inTransaction,
- ArtifactOperationInfo artifactOperation) {
+ boolean inTransaction, ArtifactOperationInfo artifactOperation) {
return createOrUpdateNonMetaArtifactsComp(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation);
}
@@ -825,7 +744,6 @@ public class ServiceImportBusinessLogic {
existingArtifacts.addAll(component.getArtifacts().values());
}
existingArtifacts = existingArtifacts.stream().filter(this::isNonMetaArtifact).collect(toList());
-
List<String> artifactsToIgnore = new ArrayList<>();
if (component.getGroups() != null) {
component.getGroups().forEach(g -> {
@@ -834,8 +752,7 @@ public class ServiceImportBusinessLogic {
}
});
}
- existingArtifacts = existingArtifacts.stream()
- .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList());
+ existingArtifacts = existingArtifacts.stream().filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList());
return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, component, user);
}
@@ -849,8 +766,7 @@ public class ServiceImportBusinessLogic {
private boolean isValidArtifactType(ArtifactDefinition artifact) {
boolean result = true;
- if (artifact.getArtifactType() == null
- || ArtifactTypeEnum.findType(artifact.getArtifactType()).equals(ArtifactTypeEnum.VENDOR_LICENSE)
+ if (artifact.getArtifactType() == null || ArtifactTypeEnum.findType(artifact.getArtifactType()).equals(ArtifactTypeEnum.VENDOR_LICENSE)
|| ArtifactTypeEnum.findType(artifact.getArtifactType()).equals(ArtifactTypeEnum.VF_LICENSE)) {
result = false;
}
@@ -858,8 +774,8 @@ public class ServiceImportBusinessLogic {
}
protected Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
- List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
- Component component, User user) {
+ List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle, Component component,
+ User user) {
EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
ArtifactsBusinessLogic.ArtifactOperationEnum.class);
Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
@@ -871,14 +787,11 @@ public class ServiceImportBusinessLogic {
List<CsarUtils.NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
for (CsarUtils.NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
ArtifactDefinition foundArtifact;
-
if (!existingArtifactsToHandle.isEmpty()) {
- foundArtifact = existingArtifactsToHandle.stream()
- .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst()
- .orElse(null);
+ foundArtifact = existingArtifactsToHandle.stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName()))
+ .findFirst().orElse(null);
if (foundArtifact != null) {
- if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()).equals(currNewArtifact
- .getArtifactType())) {
+ if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()).equals(currNewArtifact.getArtifactType())) {
if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
artifactsToUpdate.add(currNewArtifact);
@@ -886,18 +799,16 @@ public class ServiceImportBusinessLogic {
existingArtifactsToHandle.remove(foundArtifact);
artifactsToUpload.remove(currNewArtifact);
} else {
- log.debug("Can't upload two artifact with the same name {}.",
- currNewArtifact.getArtifactName());
- ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(
- ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
- currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
- foundArtifact.getArtifactType());
+ log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
+ ResponseFormat responseFormat = ResponseFormatManager.getInstance()
+ .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
+ currNewArtifact.getArtifactType(), foundArtifact.getArtifactType());
AuditingActionEnum auditingAction = serviceBusinessLogic.artifactsBusinessLogic
- .detectAuditingType(new ArtifactOperationInfo(false, false,
- ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
- serviceBusinessLogic.artifactsBusinessLogic.handleAuditing(auditingAction, component, component.getUniqueId(),
- user, null, null, foundArtifact.getUniqueId(), responseFormat,
- component.getComponentType(), null);
+ .detectAuditingType(new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE),
+ foundArtifact.getArtifactChecksum());
+ serviceBusinessLogic.artifactsBusinessLogic
+ .handleAuditing(auditingAction, component, component.getUniqueId(), user, null, null, foundArtifact.getUniqueId(),
+ responseFormat, component.getComponentType(), null);
responseWrapper.setInnerElement(responseFormat);
break;
}
@@ -940,7 +851,6 @@ public class ServiceImportBusinessLogic {
return nodeTypeArtifactsToHandleRes;
}
-
public ComponentsUtils getComponentsUtils() {
return this.componentsUtils;
}
@@ -951,15 +861,10 @@ public class ServiceImportBusinessLogic {
protected Either<List<CsarUtils.NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo,
Map<String, Set<List<String>>> collectedWarningMessages) {
- List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList =
- csarInfo.getCsar().entrySet().stream()
- .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey())
- .matches())
- .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(),
- collectedWarningMessages))
- .filter(Either::isLeft)
- .map(e -> e.left().value())
- .collect(toList());
+ List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList = csarInfo.getCsar().entrySet().stream()
+ .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
+ .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages)).filter(Either::isLeft)
+ .map(e -> e.left().value()).collect(toList());
Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
for (CsarUtils.NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
@@ -969,25 +874,24 @@ public class ServiceImportBusinessLogic {
return Either.left(artifactPathAndNameList);
}
- protected Either<Service, ResponseFormat> createGroupsOnResource(Service service,
- Map<String, GroupDefinition> groups) {
+ protected Either<Service, ResponseFormat> createGroupsOnResource(Service service, Map<String, GroupDefinition> groups) {
if (groups != null && !groups.isEmpty()) {
List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, service);
serviceImportParseLogic.handleGroupsProperties(service, groups);
serviceImportParseLogic.fillGroupsFinalFields(groupsAsList);
- Either<List<GroupDefinition>, ResponseFormat> createGroups = serviceBusinessLogic.groupBusinessLogic.createGroups(service,
- groupsAsList, true);
+ Either<List<GroupDefinition>, ResponseFormat> createGroups = serviceBusinessLogic.groupBusinessLogic
+ .createGroups(service, groupsAsList, true);
if (createGroups.isRight()) {
return Either.right(createGroups.right().value());
}
} else {
return Either.left(service);
}
- Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade
- .getToscaElement(service.getUniqueId());
+ Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
if (updatedResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(
- componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service, ComponentTypeEnum.SERVICE);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
+ ComponentTypeEnum.SERVICE);
return Either.right(responseFormat);
}
return Either.left(updatedResource.left().value());
@@ -1008,8 +912,7 @@ public class ServiceImportBusinessLogic {
updatedGroupDefinition.setMembers(null);
Map<String, String> members = groupDefinition.getMembers();
if (members != null) {
- serviceImportParseLogic
- .updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
+ serviceImportParseLogic.updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
}
result.add(updatedGroupDefinition);
}
@@ -1017,7 +920,6 @@ public class ServiceImportBusinessLogic {
return result;
}
-
protected Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
@@ -1026,11 +928,10 @@ public class ServiceImportBusinessLogic {
String nodeName) {
try {
log.debug("************* Going to create all nodes {}", yamlName);
- handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts,
- nodeTypesInfo, csarInfo, nodeName);
+ handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, nodeTypesInfo,
+ csarInfo, nodeName);
log.debug("************* Going to create all resource instances {}", yamlName);
- resource = createResourceInstances(yamlName, resource,
- uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes());
+ resource = createResourceInstances(yamlName, resource, uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes());
log.debug("************* Finished to create all resource instances {}", yamlName);
resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap);
log.debug("************* Going to create positions {}", yamlName);
@@ -1043,64 +944,61 @@ public class ServiceImportBusinessLogic {
}
protected Resource createResourceInstancesRelations(User user, String yamlName, Resource resource,
- Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
- log.debug("#createResourceInstancesRelations - Going to create relations ");
-
- List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
- if (((MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) &&
- resource.getResourceType() != ResourceTypeEnum.PNF)) { // PNF can have no resource instances
- log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", resource.getUniqueId(), yamlName);
- BeEcompErrorManager.getInstance().logInternalDataError("createResourceInstancesRelations", "No instances found in a resource or nn yaml template. ", BeEcompErrorManager.ErrorSeverity.ERROR);
- throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
- }
- Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
- Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
- Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
- Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
- Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
- Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
- Map<String, Resource> originCompMap = new HashMap<>();
- List<RequirementCapabilityRelDef> relations = new ArrayList<>();
- Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
-
- log.debug("enter ServiceImportBusinessLogic createResourceInstancesRelations#createResourceInstancesRelations - Before get all datatypes. ");
- if(serviceBusinessLogic.dataTypeCache!=null){
- Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = serviceBusinessLogic.dataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- JanusGraphOperationStatus status = allDataTypes.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance",
- "Failed to update property value on instance. Status is " + status, BeEcompErrorManager.ErrorSeverity.ERROR);
- throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
- DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName));
- }
- Resource finalResource = resource;
- uploadResInstancesMap
- .values()
- .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
- instProperties, instCapabilities, instRequirements, instDeploymentArtifacts,
- instArtifacts, instAttributes, originCompMap, instInputs, i));
- }
- serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
- serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
- serviceImportParseLogic
- .associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
- serviceImportParseLogic.associateArtifactsToInstances(yamlName, resource, instArtifacts);
- serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
- serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
- resource = serviceImportParseLogic.getResourceAfterCreateRelations(resource);
-
- serviceImportParseLogic
- .addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
- serviceImportParseLogic.associateResourceInstances(yamlName, resource, relations);
- handleSubstitutionMappings(resource, uploadResInstancesMap);
- log.debug("************* in create relations, getResource start");
- Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
- log.debug("************* in create relations, getResource end");
- if (eitherGetResource.isRight()) {
- throw new ComponentException(componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource));
- }
- return eitherGetResource.left().value();
+ Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
+ log.debug("#createResourceInstancesRelations - Going to create relations ");
+ List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
+ if (((MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) &&
+ resource.getResourceType() != ResourceTypeEnum.PNF)) { // PNF can have no resource instances
+ log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
+ resource.getUniqueId(), yamlName);
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError("createResourceInstancesRelations", "No instances found in a resource or nn yaml template. ",
+ BeEcompErrorManager.ErrorSeverity.ERROR);
+ throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
+ }
+ Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
+ Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
+ Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
+ Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
+ Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
+ Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
+ Map<String, Resource> originCompMap = new HashMap<>();
+ List<RequirementCapabilityRelDef> relations = new ArrayList<>();
+ Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
+ log.debug("enter ServiceImportBusinessLogic createResourceInstancesRelations#createResourceInstancesRelations - Before get all datatypes. ");
+ if (serviceBusinessLogic.dataTypeCache != null) {
+ Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = serviceBusinessLogic.dataTypeCache.getAll();
+ if (allDataTypes.isRight()) {
+ JanusGraphOperationStatus status = allDataTypes.right().value();
+ BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance",
+ "Failed to update property value on instance. Status is " + status, BeEcompErrorManager.ErrorSeverity.ERROR);
+ throw new ComponentException(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)),
+ yamlName));
+ }
+ Resource finalResource = resource;
+ uploadResInstancesMap.values().forEach(
+ i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes, instProperties, instCapabilities,
+ instRequirements, instDeploymentArtifacts, instArtifacts, instAttributes, originCompMap, instInputs, i));
+ }
+ serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
+ serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
+ serviceImportParseLogic.associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
+ serviceImportParseLogic.associateArtifactsToInstances(yamlName, resource, instArtifacts);
+ serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
+ serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
+ resource = serviceImportParseLogic.getResourceAfterCreateRelations(resource);
+ serviceImportParseLogic.addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
+ serviceImportParseLogic.associateResourceInstances(yamlName, resource, relations);
+ handleSubstitutionMappings(resource, uploadResInstancesMap);
+ log.debug("************* in create relations, getResource start");
+ Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
+ log.debug("************* in create relations, getResource end");
+ if (eitherGetResource.isRight()) {
+ throw new ComponentException(
+ componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource));
+ }
+ return eitherGetResource.left().value();
}
protected void processProperty(Resource resource, ComponentInstance currentCompInstance, Map<String, DataTypeDefinition> allDataTypes,
@@ -1109,8 +1007,7 @@ public class ServiceImportBusinessLogic {
UploadPropInfo propertyInfo = propertyList.get(0);
String propName = propertyInfo.getName();
if (!currPropertiesMap.containsKey(propName)) {
- throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
- propName));
+ throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName));
}
processProperty(allDataTypes, currPropertiesMap, instPropList, propertyInfo, propName, resource.getInputs());
}
@@ -1120,7 +1017,6 @@ public class ServiceImportBusinessLogic {
List<InputDefinition> inputs2) {
InputDefinition curPropertyDef = currPropertiesMap.get(propName);
ComponentInstanceInput property = null;
-
String value = null;
List<GetInputValueDataDefinition> getInputs = null;
boolean isValidate = true;
@@ -1128,17 +1024,14 @@ public class ServiceImportBusinessLogic {
getInputs = propertyInfo.getGet_input();
isValidate = getInputs == null || getInputs.isEmpty();
if (isValidate) {
- value = getPropertyJsonStringValue(propertyInfo.getValue(),
- curPropertyDef.getType());
+ value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
} else {
- value = getPropertyJsonStringValue(propertyInfo.getValue(),
- TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
+ value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
}
}
property = new ComponentInstanceInput(curPropertyDef, value, null);
String validPropertyVAlue = serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
property.setValue(validPropertyVAlue);
-
if (isNotEmpty(getInputs)) {
List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
for (GetInputValueDataDefinition getInput : getInputs) {
@@ -1146,16 +1039,13 @@ public class ServiceImportBusinessLogic {
if (CollectionUtils.isEmpty(inputs)) {
throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
-
- Optional<InputDefinition> optional = inputs.stream()
- .filter(p -> p.getName().equals(getInput.getInputName())).findAny();
+ Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
if (!optional.isPresent()) {
throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
InputDefinition input = optional.get();
getInput.setInputId(input.getUniqueId());
getInputValues.add(getInput);
-
GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
processGetInput(getInputValues, inputs, getInputIndex);
}
@@ -1169,22 +1059,20 @@ public class ServiceImportBusinessLogic {
if (resource.getResourceType() == ResourceTypeEnum.VF) {
Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaFullElement(resource.getUniqueId());
if (getResourceRes.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
throw new ComponentException(responseFormat);
}
- getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(),
- uploadResInstancesMap);
+ getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(), uploadResInstancesMap);
if (getResourceRes.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
throw new ComponentException(responseFormat);
}
}
}
- protected Resource createResourceInstances(String yamlName, Resource resource,
- Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
+ protected Resource createResourceInstances(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
Map<String, Resource> nodeNamespaceMap) {
Either<Resource, ResponseFormat> eitherResource = null;
log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
@@ -1197,14 +1085,11 @@ public class ServiceImportBusinessLogic {
nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
}
Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
- uploadResInstancesMap
- .values()
+ uploadResInstancesMap.values()
.forEach(i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
-
if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
try {
- toscaOperationFacade.associateComponentInstancesToComponent(resource,
- resourcesInstancesMap, false, false);
+ toscaOperationFacade.associateComponentInstancesToComponent(resource, resourcesInstancesMap, false, false);
} catch (StorageException exp) {
if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
log.debug("Failed to add component instances to container component {}", resource.getName());
@@ -1220,37 +1105,34 @@ public class ServiceImportBusinessLogic {
.getToscaElement(resource.getUniqueId(), serviceImportParseLogic.getComponentWithInstancesFilter());
log.debug("*************finished to get resource {}", resource.getUniqueId());
if (eitherGetResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
throw new ComponentException(responseFormat);
}
if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances()) &&
resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
log.debug("Error when create resource instance from csar. ComponentInstances list empty");
- BeEcompErrorManager.getInstance().logBeDaoSystemError(
- "Error when create resource instance from csar. ComponentInstances list empty");
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource instance from csar. ComponentInstances list empty");
throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
}
return eitherGetResource.left().value();
}
- protected void handleNodeTypes(String yamlName, Resource resource,
- String topologyTemplateYaml, boolean needLock,
+ protected void handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
- List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
- CsarInfo csarInfo, String nodeName) {
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
+ String nodeName) {
try {
for (Map.Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
if (nodeTypeEntry.getValue().isNested()) {
-
- handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
- nodeTypesInfo, csarInfo, nodeTypeEntry.getKey());
+ handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
+ nodeTypeEntry.getKey());
log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
}
}
Map<String, Object> mappedToscaTemplate = null;
- if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo)
- && nodeTypesInfo.containsKey(nodeName)) {
+ if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) && nodeTypesInfo
+ .containsKey(nodeName)) {
mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
}
if (MapUtils.isEmpty(mappedToscaTemplate)) {
@@ -1259,8 +1141,8 @@ public class ServiceImportBusinessLogic {
createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
} catch (ComponentException e) {
- ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
- : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
+ ResponseFormat responseFormat =
+ e.getResponseFormat() != null ? e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
throw e;
} catch (StorageException e) {
@@ -1281,8 +1163,8 @@ public class ServiceImportBusinessLogic {
try {
String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
- createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false,
- nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo);
+ createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
+ csarInfo);
log.debug("************* Finished to create node types from yaml {}", yamlName);
if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
@@ -1301,15 +1183,12 @@ public class ServiceImportBusinessLogic {
String nodeName) {
String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
-
log.debug("************* Going to create node types from yaml {}", yamlName);
- createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false,
- nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo);
-
+ createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
+ csarInfo);
if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
- resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
- csarInfo, nodeName, yamlName);
+ resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
}
return resource;
}
@@ -1324,29 +1203,27 @@ public class ServiceImportBusinessLogic {
.getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
- serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(),
- nodeName).getRight());
+ serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName).getRight());
}
if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
throw new ComponentException(ActionStatus.GENERAL_ERROR);
} else if (oldComplexVfcRes.isLeft()) {
log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
- Either<Boolean, ResponseFormat> eitherValidation = serviceImportParseLogic.validateNestedDerivedFromDuringUpdate(
- oldComplexVfcRes.left().value(), newComplexVfc,
- ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
+ Either<Boolean, ResponseFormat> eitherValidation = serviceImportParseLogic
+ .validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(), newComplexVfc,
+ ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
if (eitherValidation.isLeft()) {
oldComplexVfc = oldComplexVfcRes.left().value();
}
}
- newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName,
- oldComplexVfc, newComplexVfc);
+ newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc,
+ newComplexVfc);
csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
- LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(
- CERTIFICATION_ON_IMPORT, LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
+ LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
+ LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
final Resource result = serviceImportParseLogic
- .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false,
- true);
+ .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true);
csarInfo.getCreatedNodes().put(nodeName, result);
csarInfo.removeNodeFromQueue();
return result;
@@ -1356,8 +1233,7 @@ public class ServiceImportBusinessLogic {
boolean needLock,
Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
- Map<String, NodeTypeInfo> nodeTypesInfo,
- CsarInfo csarInfo) {
+ Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
Either<String, ImportUtils.ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
if (toscaVersion.isRight()) {
@@ -1379,28 +1255,21 @@ public class ServiceImportBusinessLogic {
Resource vfcCreated = null;
while (nodesNameValueIter.hasNext()) {
Map.Entry<String, Object> nodeType = nodesNameValueIter.next();
- Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
- || nodeTypesArtifactsToHandle.isEmpty() ? null
- : nodeTypesArtifactsToHandle.get(nodeType.getKey());
-
+ Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle =
+ nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
if (nodeTypesInfo.containsKey(nodeType.getKey())) {
log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
- vfcCreated = handleNestedVfc(resource,
- nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
+ vfcCreated = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
nodeType.getKey());
log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
- } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
- && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) {
+ } else if (csarInfo.getCreatedNodesToscaResourceNames() != null && !csarInfo.getCreatedNodesToscaResourceNames()
+ .containsKey(nodeType.getKey())) {
log.trace("************* Going to create node {}", nodeType.getKey());
ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(),
- mapToConvert,
- resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true,
- csarInfo, true);
+ mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true);
log.debug("************* Finished to create node {}", nodeType.getKey());
-
vfcCreated = resourceCreated.getLeft();
- csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),
- vfcCreated.getToscaResourceName());
+ csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(), vfcCreated.getToscaResourceName());
}
if (vfcCreated != null) {
csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
@@ -1409,21 +1278,18 @@ public class ServiceImportBusinessLogic {
}
}
- protected ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(
- String yamlName, Map.Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert,
- Resource resourceVf, boolean needLock,
- Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
- List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
- boolean isNested) {
- UploadResourceInfo resourceMetaData = serviceImportParseLogic
- .fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
-
- String singleVfcYaml = serviceImportParseLogic.buildNodeTypeYaml(nodeNameValue, mapToConvert,
- resourceMetaData.getResourceType(), csarInfo);
+ protected ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(String yamlName, Map.Entry<String, Object> nodeNameValue,
+ User user, Map<String, Object> mapToConvert, Resource resourceVf,
+ boolean needLock,
+ Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
+ boolean forceCertificationAllowed, CsarInfo csarInfo,
+ boolean isNested) {
+ UploadResourceInfo resourceMetaData = serviceImportParseLogic.fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
+ String singleVfcYaml = serviceImportParseLogic.buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
user = serviceBusinessLogic.validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
- return serviceImportParseLogic.createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock,
- nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
- nodeNameValue.getKey(), isNested);
+ return serviceImportParseLogic.createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, nodeTypeArtifactsToHandle,
+ nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested);
}
protected Service createRIAndRelationsFromYaml(String yamlName, Service service,
@@ -1447,110 +1313,97 @@ public class ServiceImportBusinessLogic {
protected Service createServiceInstancesRelations(User user, String yamlName, Service service,
Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
-
- log.debug("#createResourceInstancesRelations - Going to create relations ");
- List<ComponentInstance> componentInstancesList = service.getComponentInstances();
- if (((MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)))) { // PNF can have no resource instances
- log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
+ log.debug("#createResourceInstancesRelations - Going to create relations ");
+ List<ComponentInstance> componentInstancesList = service.getComponentInstances();
+ if (((MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)))) { // PNF can have no resource instances
+ log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
service.getUniqueId(), yamlName);
- BeEcompErrorManager.getInstance()
+ BeEcompErrorManager.getInstance()
.logInternalDataError("createResourceInstancesRelations", "No instances found in a component or nn yaml template. ",
BeEcompErrorManager.ErrorSeverity.ERROR);
- throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
- }
- Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
- Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
- Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
- Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
- Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
- Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
- Map<String, Resource> originCompMap = new HashMap<>();
- List<RequirementCapabilityRelDef> relations = new ArrayList<>();
- Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
-
- log.debug("enter ServiceImportBusinessLogic createServiceInstancesRelations#createResourceInstancesRelations - Before get all datatypes. ");
- if(serviceBusinessLogic.dataTypeCache!=null){
- Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = serviceBusinessLogic.dataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- JanusGraphOperationStatus status = allDataTypes.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance",
- "Failed to update property value on instance. Status is " + status, BeEcompErrorManager.ErrorSeverity.ERROR);
- throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
- DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName));
- }
- Service finalResource = service;
- uploadResInstancesMap
- .values()
- .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
- instProperties, instCapabilities, instRequirements, instDeploymentArtifacts,
- instArtifacts, instAttributes, originCompMap, instInputs, i));
-
- }
- serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, service, instProperties);
- serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, service, instInputs);
- serviceImportParseLogic.associateDeploymentArtifactsToInstances(user, yamlName, service, instDeploymentArtifacts);
- serviceImportParseLogic.associateArtifactsToInstances(yamlName, service, instArtifacts);
- serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, service, instCapabilities, instRequirements);
- log.debug("enter createServiceInstancesRelations test,instRequirements:{},instCapabilities:{}",
- instRequirements, instCapabilities);
- serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, service, instAttributes);
- ToscaElement serviceTemplate = ModelConverter.convertToToscaElement(service);
- Map<String, ListCapabilityDataDefinition> capabilities = serviceTemplate.getCapabilities();
- Map<String, ListRequirementDataDefinition> requirements = serviceTemplate.getRequirements();
-
- serviceImportParseLogic.associateCapabilitiesToService(yamlName, service, capabilities);
- serviceImportParseLogic.associateRequirementsToService(yamlName, service, requirements);
- service = getResourceAfterCreateRelations(service);
-
- addRelationsToRI(yamlName, service, uploadResInstancesMap, componentInstancesList, relations);
- serviceImportParseLogic.associateResourceInstances(yamlName, service, relations);
- handleSubstitutionMappings(service, uploadResInstancesMap);
- log.debug("************* in create relations, getResource start");
- Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
- log.debug("************* in create relations, getResource end");
- if (eitherGetResource.isRight()) {
- throw new ComponentException(componentsUtils.getResponseFormatByComponent(
- componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service, service.getComponentType()));
- }
- return eitherGetResource.left().value();
- }
-
- protected void processComponentInstance(String yamlName, Component component,
- List<ComponentInstance> componentInstancesList,
+ throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
+ }
+ Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
+ Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
+ Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
+ Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
+ Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
+ Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
+ Map<String, Resource> originCompMap = new HashMap<>();
+ List<RequirementCapabilityRelDef> relations = new ArrayList<>();
+ Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
+ log.debug("enter ServiceImportBusinessLogic createServiceInstancesRelations#createResourceInstancesRelations - Before get all datatypes. ");
+ if (serviceBusinessLogic.dataTypeCache != null) {
+ Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = serviceBusinessLogic.dataTypeCache.getAll();
+ if (allDataTypes.isRight()) {
+ JanusGraphOperationStatus status = allDataTypes.right().value();
+ BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance",
+ "Failed to update property value on instance. Status is " + status, BeEcompErrorManager.ErrorSeverity.ERROR);
+ throw new ComponentException(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)),
+ yamlName));
+ }
+ Service finalResource = service;
+ uploadResInstancesMap.values().forEach(
+ i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes, instProperties, instCapabilities,
+ instRequirements, instDeploymentArtifacts, instArtifacts, instAttributes, originCompMap, instInputs, i));
+ }
+ serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, service, instProperties);
+ serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, service, instInputs);
+ serviceImportParseLogic.associateDeploymentArtifactsToInstances(user, yamlName, service, instDeploymentArtifacts);
+ serviceImportParseLogic.associateArtifactsToInstances(yamlName, service, instArtifacts);
+ serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, service, instCapabilities, instRequirements);
+ log.debug("enter createServiceInstancesRelations test,instRequirements:{},instCapabilities:{}", instRequirements, instCapabilities);
+ serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, service, instAttributes);
+ ToscaElement serviceTemplate = ModelConverter.convertToToscaElement(service);
+ Map<String, ListCapabilityDataDefinition> capabilities = serviceTemplate.getCapabilities();
+ Map<String, ListRequirementDataDefinition> requirements = serviceTemplate.getRequirements();
+ serviceImportParseLogic.associateCapabilitiesToService(yamlName, service, capabilities);
+ serviceImportParseLogic.associateRequirementsToService(yamlName, service, requirements);
+ service = getResourceAfterCreateRelations(service);
+ addRelationsToRI(yamlName, service, uploadResInstancesMap, componentInstancesList, relations);
+ serviceImportParseLogic.associateResourceInstances(yamlName, service, relations);
+ handleSubstitutionMappings(service, uploadResInstancesMap);
+ log.debug("************* in create relations, getResource start");
+ Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
+ log.debug("************* in create relations, getResource end");
+ if (eitherGetResource.isRight()) {
+ throw new ComponentException(componentsUtils
+ .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service,
+ service.getComponentType()));
+ }
+ return eitherGetResource.left().value();
+ }
+
+ protected void processComponentInstance(String yamlName, Component component, List<ComponentInstance> componentInstancesList,
Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
Map<String, List<ComponentInstanceProperty>> instProperties,
Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
Map<String, Map<String, ArtifactDefinition>> instArtifacts,
- Map<String, List<AttributeDefinition>> instAttributes,
- Map<String, Resource> originCompMap,
+ Map<String, List<AttributeDefinition>> instAttributes, Map<String, Resource> originCompMap,
Map<String, List<ComponentInstanceInput>> instInputs,
UploadComponentInstanceInfo uploadComponentInstanceInfo) {
log.debug("enter ServiceImportBusinessLogic processComponentInstance");
Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
- .filter(i -> i.getName().equals(uploadComponentInstanceInfo.getName()))
- .findFirst();
+ .filter(i -> i.getName().equals(uploadComponentInstanceInfo.getName())).findFirst();
if (!currentCompInstanceOpt.isPresent()) {
- log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
- component.getUniqueId());
- BeEcompErrorManager.getInstance().logInternalDataError(
- COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
- component.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), component.getUniqueId());
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, component.getUniqueId(),
+ BeEcompErrorManager.ErrorSeverity.ERROR);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
throw new ComponentException(responseFormat);
}
ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
String resourceInstanceId = currentCompInstance.getUniqueId();
Resource originResource = getOriginResource(yamlName, originCompMap, currentCompInstance);
-
if (MapUtils.isNotEmpty(originResource.getRequirements())) {
instRequirements.put(currentCompInstance, originResource.getRequirements());
}
if (MapUtils.isNotEmpty(originResource.getCapabilities())) {
- processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo,
- currentCompInstance, originResource);
+ processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo, currentCompInstance, originResource);
}
if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) {
instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
@@ -1562,27 +1415,24 @@ public class ServiceImportBusinessLogic {
instAttributes.put(resourceInstanceId, originResource.getAttributes());
}
if (originResource.getResourceType() != ResourceTypeEnum.VF) {
- ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, component,
- originResource, currentCompInstance, instProperties, allDataTypes.left().value());
+ ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, component, originResource,
+ currentCompInstance, instProperties, allDataTypes.left().value());
if (addPropertiesValueToRiRes.getStatus() != 200) {
throw new ComponentException(addPropertiesValueToRiRes);
}
} else {
- addInputsValuesToRi(uploadComponentInstanceInfo, component,
- originResource, currentCompInstance, instInputs, allDataTypes.left().value());
+ addInputsValuesToRi(uploadComponentInstanceInfo, component, originResource, currentCompInstance, instInputs, allDataTypes.left().value());
}
}
-
- protected void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
- Component component, Resource originResource, ComponentInstance currentCompInstance,
- Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
+ protected void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Component component, Resource originResource,
+ ComponentInstance currentCompInstance, Map<String, List<ComponentInstanceInput>> instInputs,
+ Map<String, DataTypeDefinition> allDataTypes) {
Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
try {
if (MapUtils.isNotEmpty(propMap)) {
Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
List<ComponentInstanceInput> instPropList = new ArrayList<>();
-
if (CollectionUtils.isEmpty(originResource.getInputs())) {
log.debug("failed to find properties ");
throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND));
@@ -1607,8 +1457,7 @@ public class ServiceImportBusinessLogic {
String propName = propertyInfo.getName();
if (!currPropertiesMap.containsKey(propName)) {
log.debug("failed to find property {} ", propName);
- throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
- propName));
+ throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName));
}
processProperty(allDataTypes, currPropertiesMap, instPropList, propertyInfo, propName, component.getInputs());
}
@@ -1617,8 +1466,7 @@ public class ServiceImportBusinessLogic {
GetInputValueDataDefinition getInputIndex) {
Optional<InputDefinition> optional;
if (getInputIndex != null) {
- optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName()))
- .findAny();
+ optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
if (!optional.isPresent()) {
log.debug("Failed to find input {} ", getInputIndex.getInputName());
throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
@@ -1629,13 +1477,12 @@ public class ServiceImportBusinessLogic {
}
}
- protected ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
- Component component, Resource originResource, ComponentInstance currentCompInstance,
+ protected ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Component component,
+ Resource originResource, ComponentInstance currentCompInstance,
Map<String, List<ComponentInstanceProperty>> instProperties,
Map<String, DataTypeDefinition> allDataTypes) {
Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
-
List<PropertyDefinition> listFromMap = originResource.getProperties();
if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
log.debug("failed to find properties ");
@@ -1657,12 +1504,10 @@ public class ServiceImportBusinessLogic {
String propName = propertyInfo.getName();
if (!currPropertiesMap.containsKey(propName)) {
log.debug("failed to find property {} ", propName);
- return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
- propName);
+ return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
}
PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
ComponentInstanceProperty property = null;
-
String value = null;
List<GetInputValueDataDefinition> getInputs = null;
boolean isValidate = true;
@@ -1670,33 +1515,26 @@ public class ServiceImportBusinessLogic {
getInputs = propertyInfo.getGet_input();
isValidate = getInputs == null || getInputs.isEmpty();
if (isValidate) {
- value = getPropertyJsonStringValue(propertyInfo.getValue(),
- curPropertyDef.getType());
+ value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
} else {
- value = getPropertyJsonStringValue(propertyInfo.getValue(),
- TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
+ value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
}
}
property = new ComponentInstanceProperty(curPropertyDef, value, null);
-
String validatePropValue = serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
property.setValue(validatePropValue);
-
if (getInputs != null && !getInputs.isEmpty()) {
List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
for (GetInputValueDataDefinition getInput : getInputs) {
List<InputDefinition> inputs = component.getInputs();
if (inputs == null || inputs.isEmpty()) {
log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
- serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
- .stream()
- .map(GetInputValueDataDefinition::getInputName)
- .collect(toList()).toString());
+ serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND,
+ property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
}
InputDefinition input = serviceImportParseLogic.findInputByName(inputs, getInput);
getInput.setInputId(input.getUniqueId());
getInputValues.add(getInput);
-
GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
if (getInputIndex != null) {
input = serviceImportParseLogic.findInputByName(inputs, getInputIndex);
@@ -1728,10 +1566,9 @@ public class ServiceImportBusinessLogic {
if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
originCapabilities = new HashMap<>();
Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
- originResource.getCapabilities().forEach((k, v) -> serviceImportParseLogic
- .addCapabilities(originCapabilities, k, v));
- uploadComponentInstanceInfo.getCapabilities().values().forEach(l -> serviceImportParseLogic
- .addCapabilitiesProperties(newPropertiesMap, l));
+ originResource.getCapabilities().forEach((k, v) -> serviceImportParseLogic.addCapabilities(originCapabilities, k, v));
+ uploadComponentInstanceInfo.getCapabilities().values()
+ .forEach(l -> serviceImportParseLogic.addCapabilitiesProperties(newPropertiesMap, l));
updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
} else {
originCapabilities = originResource.getCapabilities();
@@ -1742,9 +1579,7 @@ public class ServiceImportBusinessLogic {
protected void updateCapabilityPropertiesValues(Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
Map<String, List<CapabilityDefinition>> originCapabilities,
Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
- originCapabilities.values().stream()
- .flatMap(Collection::stream)
- .filter(c -> newPropertiesMap.containsKey(c.getName()))
+ originCapabilities.values().stream().flatMap(Collection::stream).filter(c -> newPropertiesMap.containsKey(c.getName()))
.forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes.left().value()));
}
@@ -1764,8 +1599,7 @@ public class ServiceImportBusinessLogic {
if (isValidate) {
value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
} else {
- value = getPropertyJsonStringValue(propertyInfo.getValue(),
- TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
+ value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
}
}
property.setValue(value);
@@ -1779,8 +1613,8 @@ public class ServiceImportBusinessLogic {
Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
.getToscaFullElement(currentCompInstance.getComponentUid());
if (getOriginResourceRes.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
throw new ComponentException(responseFormat);
}
originResource = getOriginResourceRes.left().value();
@@ -1795,15 +1629,16 @@ public class ServiceImportBusinessLogic {
if (false) {
Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaFullElement(service.getUniqueId());
if (getResourceRes.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(
- componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), service, ComponentTypeEnum.SERVICE);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), service,
+ ComponentTypeEnum.SERVICE);
throw new ComponentException(responseFormat);
}
- getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(),
- uploadResInstancesMap);
+ getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(), uploadResInstancesMap);
if (getResourceRes.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(
- componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), service, ComponentTypeEnum.SERVICE);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), service,
+ ComponentTypeEnum.SERVICE);
throw new ComponentException(responseFormat);
}
}
@@ -1814,19 +1649,16 @@ public class ServiceImportBusinessLogic {
Either<Resource, StorageOperationStatus> updateRes = null;
Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
- StorageOperationStatus status = toscaOperationFacade
- .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
+ StorageOperationStatus status = toscaOperationFacade.deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
- log.debug(
- "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
+ log.debug("Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
resource.getUniqueId(), status);
updateRes = Either.right(status);
}
if (updateRes == null) {
- fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap,
- updatedInstCapabilities, updatedInstRequirements);
- status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements,
- resource);
+ fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap, updatedInstCapabilities,
+ updatedInstRequirements);
+ status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, resource);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
updateRes = Either.right(status);
}
@@ -1842,30 +1674,25 @@ public class ServiceImportBusinessLogic {
Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
componentInstances.stream().forEach(i -> {
- fillUpdatedInstCapabilities(updatedInstCapabilities, i,
- uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
- fillUpdatedInstRequirements(updatedInstRequirements, i,
- uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
+ fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
+ fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
});
}
- protected void fillUpdatedInstCapabilities(
- Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
- ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
+ protected void fillUpdatedInstCapabilities(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
+ ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
Set<String> updatedCapNames = new HashSet<>();
if (MapUtils.isNotEmpty(capabilitiesNamesToUpdate)) {
for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
- updatedCapabilities.put(requirements.getKey(),
- requirements.getValue().stream()
- .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
- && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
- .map(c -> {
- c.setParentName(c.getName());
- c.setName(capabilitiesNamesToUpdate.get(c.getName()));
- updatedCapNames.add(c.getName());
- return c;
- }).collect(toList()));
+ updatedCapabilities.put(requirements.getKey(), requirements.getValue().stream().filter(
+ c -> capabilitiesNamesToUpdate.containsKey(c.getName()) && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
+ .map(c -> {
+ c.setParentName(c.getName());
+ c.setName(capabilitiesNamesToUpdate.get(c.getName()));
+ updatedCapNames.add(c.getName());
+ return c;
+ }).collect(toList()));
}
}
if (MapUtils.isNotEmpty(updatedCapabilities)) {
@@ -1873,23 +1700,20 @@ public class ServiceImportBusinessLogic {
}
}
- protected void fillUpdatedInstRequirements(
- Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
- ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
+ protected void fillUpdatedInstRequirements(Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
+ ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
Set<String> updatedReqNames = new HashSet<>();
if (MapUtils.isNotEmpty(requirementsNamesToUpdate)) {
for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
- updatedRequirements.put(requirements.getKey(),
- requirements.getValue().stream()
- .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
- && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
- .map(r -> {
- r.setParentName(r.getName());
- r.setName(requirementsNamesToUpdate.get(r.getName()));
- updatedReqNames.add(r.getName());
- return r;
- }).collect(toList()));
+ updatedRequirements.put(requirements.getKey(), requirements.getValue().stream().filter(
+ r -> requirementsNamesToUpdate.containsKey(r.getName()) && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
+ .map(r -> {
+ r.setParentName(r.getName());
+ r.setName(requirementsNamesToUpdate.get(r.getName()));
+ updatedReqNames.add(r.getName());
+ return r;
+ }).collect(toList()));
}
}
if (MapUtils.isNotEmpty(updatedRequirements)) {
@@ -1909,16 +1733,13 @@ public class ServiceImportBusinessLogic {
}
}
if (currentCompInstance == null) {
- log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
- service.getUniqueId());
- BeEcompErrorManager.getInstance().logInternalDataError(
- COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
- service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), service.getUniqueId());
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, service.getUniqueId(),
+ BeEcompErrorManager.ErrorSeverity.ERROR);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
throw new ComponentException(responseFormat);
}
-
ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, service, entry.getValue(), relations);
if (addRelationToRiRes.getStatus() != 200) {
throw new ComponentException(addRelationToRiRes);
@@ -1926,8 +1747,8 @@ public class ServiceImportBusinessLogic {
}
}
- protected ResponseFormat addRelationToRI(String yamlName, Service service,
- UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
+ protected ResponseFormat addRelationToRI(String yamlName, Service service, UploadComponentInstanceInfo nodesInfoValue,
+ List<RequirementCapabilityRelDef> relations) {
List<ComponentInstance> componentInstancesList = service.getComponentInstances();
ComponentInstance currentCompInstance = null;
for (ComponentInstance compInstance : componentInstancesList) {
@@ -1937,17 +1758,14 @@ public class ServiceImportBusinessLogic {
}
}
if (currentCompInstance == null) {
- log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(),
- service.getUniqueId());
- BeEcompErrorManager.getInstance().logInternalDataError(
- COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
- service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
- return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
- yamlName);
+ log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), service.getUniqueId());
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, service.getUniqueId(),
+ BeEcompErrorManager.ErrorSeverity.ERROR);
+ return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
}
String resourceInstanceId = currentCompInstance.getUniqueId();
Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
-
if (regMap != null) {
Iterator<Map.Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
while (nodesRegValue.hasNext()) {
@@ -1959,18 +1777,14 @@ public class ServiceImportBusinessLogic {
RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
regCapRelDef.setFromNode(resourceInstanceId);
log.debug("try to find available requirement {} ", regName);
- Either<RequirementDefinition, ResponseFormat> eitherReqStatus = serviceImportParseLogic.findAviableRequiremen(regName,
- yamlName, nodesInfoValue, currentCompInstance,
- uploadRegInfo.getCapabilityName());
+ Either<RequirementDefinition, ResponseFormat> eitherReqStatus = serviceImportParseLogic
+ .findAviableRequiremen(regName, yamlName, nodesInfoValue, currentCompInstance, uploadRegInfo.getCapabilityName());
if (eitherReqStatus.isRight()) {
- log.debug("failed to find available requirement {} status is {}", regName,
- eitherReqStatus.right().value());
+ log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
return eitherReqStatus.right().value();
}
-
RequirementDefinition validReq = eitherReqStatus.left().value();
- List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
- .getRelationships();
+ List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef.getRelationships();
if (reqAndRelationshipPairList == null) {
reqAndRelationshipPairList = new ArrayList<>();
}
@@ -1981,7 +1795,6 @@ public class ServiceImportBusinessLogic {
RelationshipImpl relationship = new RelationshipImpl();
relationship.setType(validReq.getCapability());
reqAndRelationshipPair.setRelationships(relationship);
-
ComponentInstance currentCapCompInstance = null;
for (ComponentInstance compInstance : componentInstancesList) {
if (compInstance.getName().equals(uploadRegInfo.getNode())) {
@@ -1990,28 +1803,24 @@ public class ServiceImportBusinessLogic {
}
}
if (currentCapCompInstance == null) {
- log.debug("The component instance with name {} not found on resource {} ",
- uploadRegInfo.getNode(), service.getUniqueId());
- BeEcompErrorManager.getInstance().logInternalDataError(
- COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
- service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
- return componentsUtils
- .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ log.debug("The component instance with name {} not found on resource {} ", uploadRegInfo.getNode(), service.getUniqueId());
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, service.getUniqueId(),
+ BeEcompErrorManager.ErrorSeverity.ERROR);
+ return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
}
regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
log.debug("try to find aviable Capability req name is {} ", validReq.getName());
- CapabilityDefinition aviableCapForRel = serviceImportParseLogic.findAvailableCapabilityByTypeOrName(validReq,
- currentCapCompInstance, uploadRegInfo);
+ CapabilityDefinition aviableCapForRel = serviceImportParseLogic
+ .findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
if (aviableCapForRel == null) {
BeEcompErrorManager.getInstance().logInternalDataError(
- "aviable capability was not found. req name is " + validReq.getName()
- + " component instance is " + currentCapCompInstance.getUniqueId(),
- service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
- return componentsUtils
- .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ "aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance
+ .getUniqueId(), service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
+ return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
}
CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
capReqRel.setRelation(reqAndRelationshipPair);
@@ -2026,16 +1835,14 @@ public class ServiceImportBusinessLogic {
protected Service getResourceAfterCreateRelations(Service service) {
ComponentParametersView parametersView = serviceImportParseLogic.getComponentFilterAfterCreateRelations();
- Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade
- .getToscaElement(service.getUniqueId(), parametersView);
+ Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(service.getUniqueId(), parametersView);
if (eitherGetResource.isRight()) {
serviceImportParseLogic.throwComponentExceptionByResource(eitherGetResource.right().value(), service);
}
return eitherGetResource.left().value();
}
- protected Service createServiceInstances(String yamlName, Service service,
- Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
+ protected Service createServiceInstances(String yamlName, Service service, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
Map<String, Resource> nodeNamespaceMap) {
Either<Resource, ResponseFormat> eitherResource = null;
log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
@@ -2048,14 +1855,11 @@ public class ServiceImportBusinessLogic {
nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
}
Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
- uploadResInstancesMap
- .values()
+ uploadResInstancesMap.values()
.forEach(i -> createAndAddResourceInstance(i, yamlName, service, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
-
if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
try {
- toscaOperationFacade.associateComponentInstancesToComponent(service,
- resourcesInstancesMap, false, false);
+ toscaOperationFacade.associateComponentInstancesToComponent(service, resourcesInstancesMap, false, false);
} catch (StorageException exp) {
if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
log.debug("Failed to add component instances to container component {}", service.getName());
@@ -2070,31 +1874,28 @@ public class ServiceImportBusinessLogic {
.getToscaElement(service.getUniqueId(), serviceImportParseLogic.getComponentWithInstancesFilter());
log.debug("*************finished to get resource {}", service.getUniqueId());
if (eitherGetResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(
- componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service, ComponentTypeEnum.SERVICE);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service,
+ ComponentTypeEnum.SERVICE);
throw new ComponentException(responseFormat);
}
if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances())) { // PNF can have no resource instances
log.debug("Error when create resource instance from csar. ComponentInstances list empty");
- BeEcompErrorManager.getInstance().logBeDaoSystemError(
- "Error when create resource instance from csar. ComponentInstances list empty");
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource instance from csar. ComponentInstances list empty");
throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
}
return eitherGetResource.left().value();
}
- protected void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName,
- Component component, Map<String, Resource> nodeNamespaceMap,
- Map<String, Resource> existingnodeTypeMap, Map<ComponentInstance, Resource> resourcesInstancesMap) {
+ protected void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName, Component component,
+ Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap,
+ Map<ComponentInstance, Resource> resourcesInstancesMap) {
log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
try {
if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
- uploadComponentInstanceInfo
- .setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
+ uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
}
- Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
- existingnodeTypeMap);
-
+ Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, existingnodeTypeMap);
ComponentInstance componentInstance = new ComponentInstance();
componentInstance.setComponentUid(refResource.getUniqueId());
Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
@@ -2103,25 +1904,23 @@ public class ServiceImportBusinessLogic {
}
UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
if (uploadNodeFilterInfo != null) {
- componentInstance.setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo,
- componentInstance.getUniqueId()));
+ componentInstance
+ .setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo, componentInstance.getUniqueId()));
}
-
ComponentTypeEnum containerComponentType = component.getComponentType();
NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
- if (containerNodeType.equals(NodeTypeEnum.Resource)
- && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
- && MapUtils.isNotEmpty(refResource.getCapabilities())) {
+ if (containerNodeType.equals(NodeTypeEnum.Resource) && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) && MapUtils
+ .isNotEmpty(refResource.getCapabilities())) {
serviceImportParseLogic.setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = serviceImportParseLogic
- .getValidComponentInstanceCapabilities(
- refResource.getUniqueId(), refResource.getCapabilities(),
+ .getValidComponentInstanceCapabilities(refResource.getUniqueId(), refResource.getCapabilities(),
uploadComponentInstanceInfo.getCapabilities());
componentInstance.setCapabilities(validComponentInstanceCapabilities);
}
if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
- yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
+ uploadComponentInstanceInfo.getType());
throw new ComponentException(responseFormat);
}
Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
@@ -2143,8 +1942,8 @@ public class ServiceImportBusinessLogic {
Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
.getLatestResourceByToscaResourceName(uploadComponentInstanceInfo.getType());
if (findResourceEither.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
throw new ComponentException(responseFormat);
}
refResource = findResourceEither.left().value();
@@ -2152,14 +1951,16 @@ public class ServiceImportBusinessLogic {
}
String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE,
- refResource.getComponentType().getValue(), refResource.getName(), componentState);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(), refResource.getName(),
+ componentState);
throw new ComponentException(responseFormat);
}
if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.VF) {
log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
- yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
+ uploadComponentInstanceInfo.getType());
throw new ComponentException(responseFormat);
}
return refResource;
@@ -2168,8 +1969,7 @@ public class ServiceImportBusinessLogic {
}
}
- protected void handleServiceNodeTypes(String yamlName, Service service,
- String topologyTemplateYaml, boolean needLock,
+ protected void handleServiceNodeTypes(String yamlName, Service service, String topologyTemplateYaml, boolean needLock,
Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
CsarInfo csarInfo, String nodeName) {
@@ -2177,14 +1977,14 @@ public class ServiceImportBusinessLogic {
for (Map.Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
boolean isResourceNotExisted = validateResourceNotExisted(nodeTypeEntry.getKey());
if (nodeTypeEntry.getValue().isNested() && isResourceNotExisted) {
- handleNestedVF(service, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
- nodeTypesInfo, csarInfo, nodeTypeEntry.getKey());
+ handleNestedVF(service, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
+ nodeTypeEntry.getKey());
log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
}
}
Map<String, Object> mappedToscaTemplate = null;
- if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo)
- && nodeTypesInfo.containsKey(nodeName)) {
+ if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) && nodeTypesInfo
+ .containsKey(nodeName)) {
mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
}
if (MapUtils.isEmpty(mappedToscaTemplate)) {
@@ -2217,11 +2017,9 @@ public class ServiceImportBusinessLogic {
try {
String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
-
createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
csarInfo);
log.debug("************* Finished to create node types from yaml {}", yamlName);
-
if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
return handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
@@ -2235,8 +2033,7 @@ public class ServiceImportBusinessLogic {
protected Resource handleComplexVfc(
Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
- List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
- String nodeName, String yamlName) {
+ List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName, String yamlName) {
try {
Resource oldComplexVfc = null;
Resource newComplexVfc = serviceImportParseLogic.buildValidComplexVfc(csarInfo, nodeName, nodesInfo);
@@ -2244,31 +2041,30 @@ public class ServiceImportBusinessLogic {
.getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
- serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(),
- nodeName).getRight());
+ serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName)
+ .getRight());
}
if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
- log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ",
- newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
+ log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", newComplexVfc.getToscaResourceName(),
+ oldComplexVfcRes.right().value());
throw new ComponentException(ActionStatus.GENERAL_ERROR);
} else if (oldComplexVfcRes.isLeft()) {
log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
- Either<Boolean, ResponseFormat> eitherValidation = serviceImportParseLogic.validateNestedDerivedFromDuringUpdate(
- oldComplexVfcRes.left().value(), newComplexVfc,
- ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
+ Either<Boolean, ResponseFormat> eitherValidation = serviceImportParseLogic
+ .validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(), newComplexVfc,
+ ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
if (eitherValidation.isLeft()) {
oldComplexVfc = oldComplexVfcRes.left().value();
}
}
- newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName,
- oldComplexVfc, newComplexVfc);
+ newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc,
+ newComplexVfc);
csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
- LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(
- CERTIFICATION_ON_IMPORT, LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
+ LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
+ LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
final Resource result = serviceImportParseLogic
- .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false,
- true);
+ .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true);
csarInfo.getCreatedNodes().put(nodeName, result);
csarInfo.removeNodeFromQueue();
return result;
@@ -2280,8 +2076,8 @@ public class ServiceImportBusinessLogic {
protected Resource handleComplexVfc(
Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
- List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
- String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
+ List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName, String yamlName,
+ Resource oldComplexVfc, Resource newComplexVfc) {
Resource handleComplexVfcRes;
try {
Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
@@ -2290,12 +2086,11 @@ public class ServiceImportBusinessLogic {
.collect(toMap(Map.Entry::getKey, e -> e.getValue().getUnmarkedCopy()));
CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
if (oldComplexVfc == null) {
- handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo,
- csarInfo, nodesArtifactsToHandle, false, true, nodeName);
+ handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, csarInfo, nodesArtifactsToHandle,
+ false, true, nodeName);
} else {
- handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc,
- AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo,
- newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
+ handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, AuditingActionEnum.UPDATE_RESOURCE_METADATA,
+ createdArtifacts, yamlContent, yamlName, csarInfo, newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
}
return handleComplexVfcRes;
} catch (Exception e) {
@@ -2304,9 +2099,9 @@ public class ServiceImportBusinessLogic {
}
}
- protected Resource updateResourceFromYaml(Resource oldRresource, Resource newRresource,
- AuditingActionEnum actionEnum, List<ArtifactDefinition> createdArtifacts,
- String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
+ protected Resource updateResourceFromYaml(Resource oldRresource, Resource newRresource, AuditingActionEnum actionEnum,
+ List<ArtifactDefinition> createdArtifacts, String yamlFileName, String yamlFileContent,
+ CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
String nodeName, boolean isNested) {
boolean inTransaction = true;
@@ -2320,14 +2115,13 @@ public class ServiceImportBusinessLogic {
if (MapUtils.isEmpty(instances) && newRresource.getResourceType() != ResourceTypeEnum.PNF) {
throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
}
- preparedResource = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(),
- inTransaction, shouldLock, isNested).left;
+ preparedResource = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(), inTransaction, shouldLock,
+ isNested).left;
log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
serviceImportParseLogic.handleResourceGenericType(preparedResource);
- handleNodeTypes(yamlFileName, preparedResource, yamlFileContent,
- shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
- preparedResource = serviceImportParseLogic
- .createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
+ handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo,
+ csarInfo, nodeName);
+ preparedResource = serviceImportParseLogic.createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
preparedResource = createResourceInstances(yamlFileName, preparedResource, instances, csarInfo.getCreatedNodes());
preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances);
} catch (ComponentException e) {
@@ -2346,8 +2140,7 @@ public class ServiceImportBusinessLogic {
throw e;
}
Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = serviceBusinessLogic.groupBusinessLogic
- .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(),
- preparedResource.getSystemName());
+ .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(), preparedResource.getSystemName());
if (validateUpdateVfGroupNamesRes.isRight()) {
throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
}
@@ -2359,30 +2152,25 @@ public class ServiceImportBusinessLogic {
}
serviceImportParseLogic.handleGroupsProperties(preparedResource, groups);
preparedResource = serviceImportParseLogic.updateGroupsOnResource(preparedResource, groups);
- NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
- nodeTypesArtifactsToHandle);
-
- Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(
- ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE, createdArtifacts, yamlFileName,
- csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
+ NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToHandle);
+ Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE,
+ createdArtifacts, yamlFileName, csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
if (updateArtifactsEither.isRight()) {
log.debug("failed to update artifacts {}", updateArtifactsEither.right().value());
throw new ComponentException(updateArtifactsEither.right().value());
}
preparedResource = serviceImportParseLogic.getResourceWithGroups(updateArtifactsEither.left().value().getUniqueId());
-
ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldRresource, preparedResource);
if (mergingPropsAndInputsStatus != ActionStatus.OK) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus,
- preparedResource);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus, preparedResource);
throw new ComponentException(responseFormat);
}
compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
return preparedResource;
}
- protected Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml,
- String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
+ protected Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName,
+ Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
boolean shouldLock, boolean inTransaction, String nodeName) {
List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
@@ -2394,9 +2182,8 @@ public class ServiceImportBusinessLogic {
throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
}
log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
- createdResource = createResourceAndRIsFromYaml(yamlName, resource,
- parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml,
- nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
+ createdResource = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false,
+ createdArtifacts, topologyTemplateYaml, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
} catch (ComponentException e) {
ResponseFormat responseFormat =
@@ -2412,16 +2199,15 @@ public class ServiceImportBusinessLogic {
return createdResource;
}
- protected Resource createResourceAndRIsFromYaml(String yamlName, Resource resource,
- ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative,
- List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml,
- Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
+ protected Resource createResourceAndRIsFromYaml(String yamlName, Resource resource, ParsedToscaYamlInfo parsedToscaYamlInfo,
+ AuditingActionEnum actionEnum, boolean isNormative, List<ArtifactDefinition> createdArtifacts,
+ String topologyTemplateYaml, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
boolean shouldLock, boolean inTransaction, String nodeName) {
List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
if (shouldLock) {
- Either<Boolean, ResponseFormat> lockResult = serviceBusinessLogic.lockComponentByName(resource.getSystemName(), resource,
- CREATE_RESOURCE);
+ Either<Boolean, ResponseFormat> lockResult = serviceBusinessLogic
+ .lockComponentByName(resource.getSystemName(), resource, CREATE_RESOURCE);
if (lockResult.isRight()) {
serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
throw new ComponentException(lockResult.right().value());
@@ -2431,10 +2217,8 @@ public class ServiceImportBusinessLogic {
try {
log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
Resource genericResource = serviceBusinessLogic.fetchAndSetDerivedFromGenericType(resource);
- resource = createResourceTransaction(resource,
- csarInfo.getModifier(), isNormative);
+ resource = createResourceTransaction(resource, csarInfo.getModifier(), isNormative);
log.trace("************* Going to add inputs from yaml {}", yamlName);
-
Map<String, Object> yamlMap = ImportUtils.loadYamlAsStrictMap(csarInfo.getMainTemplateContent());
Map<String, Object> metadata = (Map<String, Object>) yamlMap.get("metadata");
String type = (String) metadata.get("type");
@@ -2443,11 +2227,9 @@ public class ServiceImportBusinessLogic {
}
Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
resource = serviceImportParseLogic.createInputsOnResource(resource, inputs);
- Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
- .getInstances();
- resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap,
- topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
- nodeTypesArtifactsToCreate, nodeName);
+ Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
+ resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, topologyTemplateYaml,
+ nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName);
log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
// validate update vf module group names
Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = serviceBusinessLogic.groupBusinessLogic
@@ -2458,32 +2240,25 @@ public class ServiceImportBusinessLogic {
}
Map<String, GroupDefinition> groups;
log.trace("************* Going to add groups from yaml {}", yamlName);
-
if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
groups = validateUpdateVfGroupNamesRes.left().value();
} else {
groups = parsedToscaYamlInfo.getGroups();
}
-
- Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource,
- groups);
+ Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, groups);
if (createGroupsOnResource.isRight()) {
serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
throw new ComponentException(createGroupsOnResource.right().value());
}
resource = createGroupsOnResource.left().value();
log.trace("************* Going to add artifacts from yaml {}", yamlName);
-
NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
-
- Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(
- ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, createdArtifacts, yamlName,
- csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
+ Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE,
+ createdArtifacts, yamlName, csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
if (createArtifactsEither.isRight()) {
serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
throw new ComponentException(createArtifactsEither.right().value());
}
-
resource = serviceImportParseLogic.getResourceWithGroups(createArtifactsEither.left().value().getUniqueId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
@@ -2503,26 +2278,23 @@ public class ServiceImportBusinessLogic {
}
}
- protected Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource,
- Map<String, GroupDefinition> groups) {
+ protected Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
if (groups != null && !groups.isEmpty()) {
- List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(
- groups, resource);
+ List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
serviceImportParseLogic.handleGroupsProperties(resource, groups);
serviceImportParseLogic.fillGroupsFinalFields(groupsAsList);
- Either<List<GroupDefinition>, ResponseFormat> createGroups = serviceBusinessLogic.groupBusinessLogic.createGroups(resource,
- groupsAsList, true);
+ Either<List<GroupDefinition>, ResponseFormat> createGroups = serviceBusinessLogic.groupBusinessLogic
+ .createGroups(resource, groupsAsList, true);
if (createGroups.isRight()) {
return Either.right(createGroups.right().value());
}
} else {
return Either.left(resource);
}
- Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
- .getToscaElement(resource.getUniqueId());
+ Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
if (updatedResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
return Either.right(responseFormat);
}
return Either.left(updatedResource.left().value());
@@ -2531,7 +2303,6 @@ public class ServiceImportBusinessLogic {
protected List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
List<GroupDefinition> result = new ArrayList<>();
List<ComponentInstance> componentInstances = component.getComponentInstances();
-
if (groups != null) {
Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = serviceImportParseLogic.validateCyclicGroupsDependencies(groups);
if (validateCyclicGroupsDependencies.isRight()) {
@@ -2557,19 +2328,16 @@ public class ServiceImportBusinessLogic {
Set<String> compInstancesNames = members.keySet();
if (CollectionUtils.isEmpty(componentInstances)) {
String membersAstString = compInstancesNames.stream().collect(joining(","));
- log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
- membersAstString, groupName, component.getNormalizedName());
- throw new ComponentException(componentsUtils.getResponseFormat(
- ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
- component.getNormalizedName(), serviceImportParseLogic.getComponentTypeForResponse(component)));
- }
- Map<String, String> memberNames = componentInstances.stream()
- .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
+ log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString,
+ groupName, component.getNormalizedName());
+ throw new ComponentException(componentsUtils
+ .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
+ serviceImportParseLogic.getComponentTypeForResponse(component)));
+ }
+ Map<String, String> memberNames = componentInstances.stream().collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
- Map<String, String> relevantInstances = memberNames.entrySet().stream()
- .filter(n -> compInstancesNames.contains(n.getKey()))
+ Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey()))
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
-
if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
List<String> foundMembers = new ArrayList<>();
if (relevantInstances != null) {
@@ -2577,17 +2345,16 @@ public class ServiceImportBusinessLogic {
}
compInstancesNames.removeAll(foundMembers);
String membersAstString = compInstancesNames.stream().collect(joining(","));
- throw new ComponentException(componentsUtils.getResponseFormat(
- ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
- component.getNormalizedName(), serviceImportParseLogic.getComponentTypeForResponse(component)));
+ throw new ComponentException(componentsUtils
+ .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
+ serviceImportParseLogic.getComponentTypeForResponse(component)));
}
updatedGroupDefinition.setMembers(relevantInstances);
}
- protected Resource createResourceTransaction(Resource resource, User user,
- boolean isNormative) {
- Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
- resource.getName(), resource.getResourceType(), resource.getComponentType());
+ protected Resource createResourceTransaction(Resource resource, User user, boolean isNormative) {
+ Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade
+ .validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
if (eitherValidation.isRight()) {
ResponseFormat errorResponse = componentsUtils
.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
@@ -2595,8 +2362,8 @@ public class ServiceImportBusinessLogic {
}
if (eitherValidation.left().value()) {
log.debug("resource with name: {}, already exists", resource.getName());
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
- ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
+ ResponseFormat errorResponse = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
throw new ComponentException(errorResponse);
}
log.debug("send resource {} to dao for create", resource.getName());
@@ -2610,38 +2377,31 @@ public class ServiceImportBusinessLogic {
resource.setAbstract(false);
}
}
- return toscaOperationFacade.createToscaComponent(resource)
- .left()
+ return toscaOperationFacade.createToscaComponent(resource).left()
.on(r -> serviceImportParseLogic.throwComponentExceptionByResource(r, resource));
}
- protected ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(
- Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock,
- boolean isNested) {
+ protected ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(Resource newResource, Resource oldResource, User user,
+ boolean inTransaction, boolean needLock, boolean isNested) {
String lockedResourceId = oldResource.getUniqueId();
- log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId,
- oldResource.getVersion(), oldResource.getLifecycleState());
+ log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, oldResource.getVersion(),
+ oldResource.getLifecycleState());
ImmutablePair<Resource, ActionStatus> resourcePair = null;
try {
serviceBusinessLogic.lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
- oldResource = serviceImportParseLogic
- .prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
+ oldResource = serviceImportParseLogic.prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
serviceImportParseLogic.mergeOldResourceMetadataWithNew(oldResource, newResource);
serviceImportParseLogic.validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
- serviceImportParseLogic
- .validateCapabilityTypesCreate(user, serviceImportParseLogic.getCapabilityTypeOperation(), newResource,
- AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
+ serviceImportParseLogic.validateCapabilityTypesCreate(user, serviceImportParseLogic.getCapabilityTypeOperation(), newResource,
+ AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
createNewResourceToOldResource(newResource, oldResource, user);
-
- Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade
- .overrideComponent(newResource, oldResource);
+ Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
if (overrideResource.isRight()) {
ResponseFormat responseFormat = new ResponseFormat();
serviceBusinessLogic.throwComponentException(responseFormat);
}
log.debug("Resource updated successfully!!!");
- resourcePair = new ImmutablePair<>(overrideResource.left().value(),
- ActionStatus.OK);
+ resourcePair = new ImmutablePair<>(overrideResource.left().value(), ActionStatus.OK);
return resourcePair;
} finally {
if (resourcePair == null) {
@@ -2697,8 +2457,7 @@ public class ServiceImportBusinessLogic {
boolean needLock,
Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
- Map<String, NodeTypeInfo> nodeTypesInfo,
- CsarInfo csarInfo) {
+ Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
try {
Either<String, ImportUtils.ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
@@ -2725,26 +2484,20 @@ public class ServiceImportBusinessLogic {
Resource vfcCreated = null;
while (nodesNameValueIter.hasNext()) {
Map.Entry<String, Object> nodeType = nodesNameValueIter.next();
- Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
- || nodeTypesArtifactsToHandle.isEmpty() ? null
- : nodeTypesArtifactsToHandle.get(nodeType.getKey());
-
+ Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle =
+ nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
if (nodeTypesInfo.containsKey(nodeType.getKey())) {
- vfcCreated = handleNestedVfc(service,
- nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
+ vfcCreated = handleNestedVfc(service, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
nodeType.getKey());
log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
- } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
- && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) {
+ } else if (csarInfo.getCreatedNodesToscaResourceNames() != null && !csarInfo.getCreatedNodesToscaResourceNames()
+ .containsKey(nodeType.getKey())) {
ImmutablePair<Resource, ActionStatus> resourceCreated = serviceImportParseLogic
- .createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert,
- service, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true,
- csarInfo, true);
+ .createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, service, needLock,
+ nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true);
log.debug("************* Finished to create node {}", nodeType.getKey());
-
vfcCreated = resourceCreated.getLeft();
- csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),
- vfcCreated.getName());
+ csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(), vfcCreated.getName());
}
if (vfcCreated != null) {
csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
@@ -2752,5 +2505,4 @@ public class ServiceImportBusinessLogic {
mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
}
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportManager.java
index fa079d2f65..9fba1c7164 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportManager.java
@@ -17,10 +17,8 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
-
import javax.servlet.ServletContext;
import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
@@ -30,79 +28,72 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
-
//upload Service model by Shiyong1989@hotmail.com
@Component("ServiceImportManager")
public class ServiceImportManager {
- private ServletContext servletContext;
-
- private ResponseFormatManager responseFormatManager;
-
- @Autowired
- private ServiceBusinessLogic serviceBusinessLogic;
-
- public ServiceImportBusinessLogic getServiceImportBusinessLogic() {
- return serviceImportBusinessLogic;
- }
-
- public void setServiceImportBusinessLogic(
- ServiceImportBusinessLogic serviceImportBusinessLogic) {
- this.serviceImportBusinessLogic = serviceImportBusinessLogic;
- }
+ private ServletContext servletContext;
+ private ResponseFormatManager responseFormatManager;
+ @Autowired
+ private ServiceBusinessLogic serviceBusinessLogic;
+ @Autowired
+ private ServiceImportBusinessLogic serviceImportBusinessLogic;
- @Autowired
- private ServiceImportBusinessLogic serviceImportBusinessLogic;
-
- public boolean isServiceExist(String serviceName) {
- return serviceBusinessLogic.isServiceExist(serviceName);
- }
+ public ServiceImportBusinessLogic getServiceImportBusinessLogic() {
+ return serviceImportBusinessLogic;
+ }
+ public void setServiceImportBusinessLogic(ServiceImportBusinessLogic serviceImportBusinessLogic) {
+ this.serviceImportBusinessLogic = serviceImportBusinessLogic;
+ }
- public ServiceBusinessLogic getServiceBusinessLogic() {
- return serviceBusinessLogic;
- }
+ public boolean isServiceExist(String serviceName) {
+ return serviceBusinessLogic.isServiceExist(serviceName);
+ }
- public void setServiceBusinessLogic(
- ServiceBusinessLogic serviceBusinessLogic) {
- this.serviceBusinessLogic = serviceBusinessLogic;
- }
+ public ServiceBusinessLogic getServiceBusinessLogic() {
+ return serviceBusinessLogic;
+ }
+ public void setServiceBusinessLogic(ServiceBusinessLogic serviceBusinessLogic) {
+ this.serviceBusinessLogic = serviceBusinessLogic;
+ }
- public void populateServiceMetadata(UploadServiceInfo serviceMetaData, Service service) {
- if (service != null && serviceMetaData != null) {
- service.setDescription(serviceMetaData.getDescription());
- service.setTags(serviceMetaData.getTags());
- service.setCategories(serviceMetaData.getCategories());
- service.setContactId(serviceMetaData.getContactId());
- service.setName(serviceMetaData.getName());
- service.setIcon(serviceMetaData.getServiceIconPath());
- service.setServiceVendorModelNumber(serviceMetaData.getServiceVendorModelNumber());
- ServiceMetadataDataDefinition serviceMetadataDataDefinition = (ServiceMetadataDataDefinition) service
- .getComponentMetadataDefinition().getMetadataDataDefinition();
- serviceMetadataDataDefinition.getServiceVendorModelNumber();
- service.setServiceType("");
- service.setProjectCode(serviceMetaData.getProjectCode());
- if (serviceMetaData.getVendorName() != null) {
- service.setVendorName(serviceMetaData.getVendorName());
- }
- if (serviceMetaData.getVendorRelease() != null) {
- service.setVendorRelease(serviceMetaData.getVendorRelease());
- }
+ public void populateServiceMetadata(UploadServiceInfo serviceMetaData, Service service) {
+ if (service != null && serviceMetaData != null) {
+ service.setDescription(serviceMetaData.getDescription());
+ service.setTags(serviceMetaData.getTags());
+ service.setCategories(serviceMetaData.getCategories());
+ service.setContactId(serviceMetaData.getContactId());
+ service.setName(serviceMetaData.getName());
+ service.setIcon(serviceMetaData.getServiceIconPath());
+ service.setServiceVendorModelNumber(serviceMetaData.getServiceVendorModelNumber());
+ ServiceMetadataDataDefinition serviceMetadataDataDefinition = (ServiceMetadataDataDefinition) service.getComponentMetadataDefinition()
+ .getMetadataDataDefinition();
+ serviceMetadataDataDefinition.getServiceVendorModelNumber();
+ service.setServiceType("");
+ service.setProjectCode(serviceMetaData.getProjectCode());
+ if (serviceMetaData.getVendorName() != null) {
+ service.setVendorName(serviceMetaData.getVendorName());
+ }
+ if (serviceMetaData.getVendorRelease() != null) {
+ service.setVendorRelease(serviceMetaData.getVendorRelease());
+ }
+ }
}
- }
- public synchronized void init(ServletContext servletContext) {
- if (this.servletContext == null) {
- this.servletContext = servletContext;
- responseFormatManager = ResponseFormatManager.getInstance();
- serviceBusinessLogic = getServiceBL(servletContext);
+ public synchronized void init(ServletContext servletContext) {
+ if (this.servletContext == null) {
+ this.servletContext = servletContext;
+ responseFormatManager = ResponseFormatManager.getInstance();
+ serviceBusinessLogic = getServiceBL(servletContext);
+ }
}
- }
- private ServiceBusinessLogic getServiceBL(ServletContext context) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(org.openecomp.sdc.common.api.Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- return webApplicationContext.getBean(ServiceBusinessLogic.class);
- }
+ private ServiceBusinessLogic getServiceBL(ServletContext context) {
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
+ .getAttribute(org.openecomp.sdc.common.api.Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ return webApplicationContext.getBean(ServiceBusinessLogic.class);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogic.java
index 6a5e5314f0..3404323c9d 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogic.java
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.openecomp.sdc.be.components.impl;
import static java.util.stream.Collectors.joining;
@@ -151,21 +150,17 @@ public class ServiceImportParseLogic {
public Either<Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Service oldResource) {
-
Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
- Either<Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes
- = Either.left(nodeTypesArtifactsToHandle);
-
+ Either<Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes = Either
+ .left(nodeTypesArtifactsToHandle);
try {
Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
- Map<String, ImmutablePair<String, String>> extractedVfcToscaNames =
- extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo);
- log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ",
- oldResource.getName(), csarInfo.getCsarUUID());
- extractedVfcToscaNames
- .forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
- extractedVfcsArtifacts,
- namespace, vfcToscaNames));
+ Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo);
+ log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(),
+ csarInfo.getCsarUUID());
+ extractedVfcToscaNames.forEach(
+ (namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
+ extractedVfcsArtifacts, namespace, vfcToscaNames));
} catch (Exception e) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
@@ -174,45 +169,41 @@ public class ServiceImportParseLogic {
return nodeTypesArtifactsToHandleRes;
}
- private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo,
- String vfResourceName, CsarInfo csarInfo) {
+ private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo, String vfResourceName,
+ CsarInfo csarInfo) {
Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
-
Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
if (!nodes.isEmpty()) {
Iterator<Map.Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
while (nodesNameEntry.hasNext()) {
Map.Entry<String, Object> nodeType = nodesNameEntry.next();
- ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(
- ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
+ ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), vfResourceName,
+ nodeType.getKey());
vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
}
}
for (NodeTypeInfo cvfc : nodeTypesInfo.values()) {
- vfcToscaNames.put(cvfc.getType(),
- buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), vfResourceName, cvfc.getType()));
+ vfcToscaNames.put(cvfc.getType(), buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), vfResourceName, cvfc.getType()));
}
return vfcToscaNames;
}
- public String buildNodeTypeYaml(Map.Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert,
- String nodeResourceType, CsarInfo csarInfo) {
+ public String buildNodeTypeYaml(Map.Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert, String nodeResourceType,
+ CsarInfo csarInfo) {
// We need to create a Yaml from each node_types in order to create
+
// resource from each node type using import normative flow.
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(options);
-
Map<String, Object> node = new HashMap<>();
- node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey())
- .getLeft(), nodeNameValue.getValue());
+ node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey()).getLeft(),
+ nodeNameValue.getValue());
mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
-
return yaml.dumpAsMap(mapToConvert);
}
- ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName,
- String nodeTypeFullName) {
+ ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, String nodeTypeFullName) {
String actualType;
String actualVfName;
if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) {
@@ -228,24 +219,19 @@ public class ServiceImportParseLogic {
if (!nodeTypeFullName.contains(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
nameWithouNamespacePrefix = nodeTypeFullName;
} else {
- nameWithouNamespacePrefix = nodeTypeFullName
- .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
+ nameWithouNamespacePrefix = nodeTypeFullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
}
String[] findTypes = nameWithouNamespacePrefix.split("\\.");
String resourceType = findTypes[0];
String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
-
if (actualName.startsWith(Constants.ABSTRACT)) {
- toscaResourceName.append(resourceType.toLowerCase()).append('.')
- .append(ValidationUtils.convertToSystemName(actualVfName));
+ toscaResourceName.append(resourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
} else {
toscaResourceName.append(actualType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
}
StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
- previousToscaResourceName
- .append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase())
- .toString());
+ previousToscaResourceName.append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase()).toString());
} catch (Exception e) {
componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
@@ -274,7 +260,6 @@ public class ServiceImportParseLogic {
Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
Service resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace,
ImmutablePair<String, String> vfcToscaNames) {
-
EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), null);
@@ -286,19 +271,19 @@ public class ServiceImportParseLogic {
curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
} else if (curNodeType != null) {
// delete all artifacts if have not received artifacts from
+
// csar
try {
curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
// delete all informational artifacts
- artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream()
- .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
- .collect(toList()));
+ artifactsToDelete.addAll(
+ curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
+ .collect(toList()));
// delete all deployment artifacts
artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
if (!artifactsToDelete.isEmpty()) {
- curNodeTypeArtifactsToHandle
- .put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete);
+ curNodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete);
}
} catch (Exception e) {
componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
@@ -311,10 +296,8 @@ public class ServiceImportParseLogic {
}
}
- protected void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts,
- List<ArtifactDefinition> artifactsToAdd) {
- List<String> vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName)
- .collect(toList());
+ protected void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts, List<ArtifactDefinition> artifactsToAdd) {
+ List<String> vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName).collect(toList());
artifactsToAdd.stream().forEach(a -> {
if (!vfcArtifactNames.contains(a.getArtifactName())) {
vfcArtifacts.add(a);
@@ -330,16 +313,14 @@ public class ServiceImportParseLogic {
log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, status);
throw new ComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
} else if (org.apache.commons.lang.StringUtils.isNotEmpty(currVfcToscaName)) {
- return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName)
- .left()
+ return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName).left()
.on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
}
return null;
}
- protected EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(
- Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) {
-
+ protected EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(Resource curNodeType,
+ List<ArtifactDefinition> extractedArtifacts) {
EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
try {
List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
@@ -364,10 +345,8 @@ public class ServiceImportParseLogic {
existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
}
if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
- existingArtifacts
- .putAll(curNodeType.getArtifacts().entrySet()
- .stream()
- .filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
+ existingArtifacts.putAll(
+ curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
}
return existingArtifacts;
@@ -396,23 +375,19 @@ public class ServiceImportParseLogic {
Map<String, ArtifactDefinition> existingArtifacts) {
try {
if (!existingArtifacts.isEmpty()) {
- extractedArtifacts.stream()
- .forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
+ extractedArtifacts.stream().forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
artifactsToDelete.addAll(existingArtifacts.values());
}
} catch (Exception e) {
log.debug("Exception occured when processExistingNodeTypeArtifacts, error is:{}", e.getMessage(), e);
throw new ComponentException(ActionStatus.GENERAL_ERROR);
}
-
}
protected void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
Map<String, ArtifactDefinition> existingArtifacts, ArtifactDefinition currNewArtifact) {
- Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values()
- .stream()
- .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName()))
- .findFirst();
+ Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values().stream()
+ .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst();
if (foundArtifact.isPresent()) {
if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) {
updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
@@ -420,9 +395,8 @@ public class ServiceImportParseLogic {
artifactsToUpload.remove(currNewArtifact);
} else {
log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
- throw new ComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
- currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
- foundArtifact.get().getArtifactType());
+ throw new ComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
+ currNewArtifact.getArtifactType(), foundArtifact.get().getArtifactType());
}
}
}
@@ -431,16 +405,13 @@ public class ServiceImportParseLogic {
ArtifactDefinition foundArtifact) {
if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
foundArtifact.setPayload(currNewArtifact.getPayloadData());
- foundArtifact.setPayloadData(
- Base64.encodeBase64String(currNewArtifact.getPayloadData()));
- foundArtifact.setArtifactChecksum(GeneralUtility
- .calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
+ foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
+ foundArtifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
artifactsToUpdate.add(foundArtifact);
}
}
- public void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation,
- List<ArtifactDefinition> createdArtifacts,
+ public void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts,
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null
&& eitherNonMetaArtifacts.isLeft()) {
@@ -472,7 +443,6 @@ public class ServiceImportParseLogic {
protected boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
Set<String> allGroupMembers) {
-
boolean stop = false;
// In Case Not Group Stop
if (!allGroups.containsKey(groupName)) {
@@ -482,7 +452,6 @@ public class ServiceImportParseLogic {
if (!stop) {
GroupDefinition groupDefinition = allGroups.get(groupName);
stop = MapUtils.isEmpty(groupDefinition.getMembers());
-
}
// In Case all group members already contained stop
if (!stop) {
@@ -497,19 +466,15 @@ public class ServiceImportParseLogic {
return stop;
}
- public Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName,
- Map<String, NodeTypeInfo> nodesInfo) {
-
+ public Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
csarInfo.addNodeToQueue(nodeName);
- return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(),
- AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
+ return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
}
public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction,
CsarInfo csarInfo) {
-
validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
validateLifecycleTypesCreate(user, resource, actionEnum);
@@ -524,21 +489,20 @@ public class ServiceImportParseLogic {
} else {
resourceSystemName = resource.getSystemName();
}
- resource.setToscaResourceName(CommonBeUtils
- .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
+ resource
+ .setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
}
-
// Generate invariant UUID - must be here and not in operation since it
+
// should stay constant during clone
+
// TODO
String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
resource.setInvariantUUID(invariantUUID);
-
return resource;
}
- protected Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
- AuditingActionEnum actionEnum) {
+ protected Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource, AuditingActionEnum actionEnum) {
Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
if (resource.getResourceType() == null) {
log.debug("Invalid resource type for resource");
@@ -549,8 +513,7 @@ public class ServiceImportParseLogic {
return eitherResult;
}
- protected Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource,
- AuditingActionEnum actionEnum) {
+ protected Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource, AuditingActionEnum actionEnum) {
Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
log.debug("validate interface lifecycle Types Exist");
@@ -558,21 +521,16 @@ public class ServiceImportParseLogic {
while (intItr.hasNext() && eitherResult.isLeft()) {
InterfaceDefinition interfaceDefinition = intItr.next();
String intType = interfaceDefinition.getUniqueId();
- Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation
- .getInterface(intType);
+ Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation.getInterface(intType);
if (eitherCapTypeFound.isRight()) {
if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
- "Create Resource - validateLifecycleTypesCreate", "Interface", intType);
- log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB",
- intType, resource.getName());
BeEcompErrorManager.getInstance()
- .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
- log.debug("request to data model failed with error: {}",
- eitherCapTypeFound.right().value().name());
+ .logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType);
+ log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", intType, resource.getName());
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
+ log.debug("request to data model failed with error: {}", eitherCapTypeFound.right().value().name());
}
- ResponseFormat errorResponse = componentsUtils
- .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
eitherResult = Either.right(errorResponse);
componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
}
@@ -581,19 +539,14 @@ public class ServiceImportParseLogic {
return eitherResult;
}
- public Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user,
- ICapabilityTypeOperation capabilityTypeOperation, Resource resource,
- AuditingActionEnum actionEnum,
- boolean inTransaction) {
-
+ public Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user, ICapabilityTypeOperation capabilityTypeOperation,
+ Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
log.debug("validate capability Types Exist - capabilities section");
-
for (Map.Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
-
- eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum,
- eitherResult, typeEntry, inTransaction);
+ eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry,
+ inTransaction);
if (eitherResult.isRight()) {
return Either.right(eitherResult.right().value());
}
@@ -602,8 +555,8 @@ public class ServiceImportParseLogic {
if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
log.debug("validate capability Types Exist - requirements section");
for (String type : resource.getRequirements().keySet()) {
- eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource,
- resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction);
+ eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type), actionEnum,
+ eitherResult, type, inTransaction);
if (eitherResult.isRight()) {
return Either.right(eitherResult.right().value());
}
@@ -612,9 +565,8 @@ public class ServiceImportParseLogic {
return eitherResult;
}
- protected Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
- ICapabilityTypeOperation capabilityTypeOperation, Resource resource,
- AuditingActionEnum actionEnum,
+ protected Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation,
+ Resource resource, AuditingActionEnum actionEnum,
Either<Boolean, ResponseFormat> eitherResult,
Map.Entry<String, List<CapabilityDefinition>> typeEntry,
boolean inTransaction) {
@@ -622,17 +574,13 @@ public class ServiceImportParseLogic {
.getCapabilityType(typeEntry.getKey(), inTransaction);
if (eitherCapTypeFound.isRight()) {
if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
- CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
- log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB",
- typeEntry.getKey(), resource.getName());
BeEcompErrorManager.getInstance()
- .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
+ .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
+ log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName());
+ BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
}
- log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
- eitherCapTypeFound.right().value().name());
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
- typeEntry.getKey());
+ log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), eitherCapTypeFound.right().value().name());
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, typeEntry.getKey());
eitherResult = Either.right(errorResponse);
componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
return Either.right(eitherResult.right().value());
@@ -668,9 +616,8 @@ public class ServiceImportParseLogic {
return eitherResult;
}
- protected Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
- ICapabilityTypeOperation capabilityTypeOperation, Resource resource,
- List<?> validationObjects,
+ protected Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation,
+ Resource resource, List<?> validationObjects,
AuditingActionEnum actionEnum,
Either<Boolean, ResponseFormat> eitherResult, String type,
boolean inTransaction) {
@@ -679,26 +626,21 @@ public class ServiceImportParseLogic {
.getCapabilityType(type, inTransaction);
if (eitherCapTypeFound.isRight()) {
if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
- CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
- log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
- resource.getName());
BeEcompErrorManager.getInstance()
- .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
+ .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
+ log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, resource.getName());
+ BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
}
- log.debug("Trying to get capability type {} failed with error: {}", type,
- eitherCapTypeFound.right().value().name());
+ log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right().value().name());
ResponseFormat errorResponse = null;
if (type != null) {
errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
} else {
- errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
- validationObjects);
+ errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, validationObjects);
}
eitherResult = Either.right(errorResponse);
componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
}
-
} catch (Exception e) {
log.debug("Exception occured when validateCapabilityTypeExists, error is:{}", e.getMessage(), e);
throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, resource.getName());
@@ -706,8 +648,8 @@ public class ServiceImportParseLogic {
return eitherResult;
}
- protected Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource,
- AuditingActionEnum actionEnum, boolean inTransaction) {
+ protected Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum,
+ boolean inTransaction) {
serviceBusinessLogic.validateComponentFieldsBeforeCreate(user, resource, actionEnum);
// validate category
log.debug("validate category");
@@ -736,22 +678,18 @@ public class ServiceImportParseLogic {
if (currentCreatorFullName != null) {
log.debug("Resource Creator fullname is automatically set and cannot be updated");
}
-
String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
if (currentLastUpdaterFullName != null) {
log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
}
-
Long currentLastUpdateDate = resource.getLastUpdateDate();
if (currentLastUpdateDate != null) {
log.debug("Resource last update date is automatically set and cannot be updated");
}
-
Boolean currentAbstract = resource.isAbstract();
if (currentAbstract != null) {
log.debug("Resource abstract is automatically set and cannot be updated");
}
-
return Either.left(true);
}
@@ -760,8 +698,7 @@ public class ServiceImportParseLogic {
return;
}
String templateName = resource.getDerivedFrom().get(0);
- Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
- .validateToscaResourceNameExists(templateName);
+ Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExists(templateName);
if (dataModelResponse.isRight()) {
StorageOperationStatus storageStatus = dataModelResponse.right().value();
BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
@@ -779,13 +716,11 @@ public class ServiceImportParseLogic {
}
}
- protected void validateLicenseType(User user, Resource resource,
- AuditingActionEnum actionEnum) {
+ protected void validateLicenseType(User user, Resource resource, AuditingActionEnum actionEnum) {
log.debug("validate licenseType");
String licenseType = resource.getLicenseType();
if (licenseType != null) {
- List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
- .getLicenseTypes();
+ List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getLicenseTypes();
if (!licenseTypes.contains(licenseType)) {
log.debug("License type {} isn't configured", licenseType);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
@@ -813,19 +748,18 @@ public class ServiceImportParseLogic {
if (org.apache.commons.lang.StringUtils.isNotEmpty(resourceVendorModelNumber)) {
if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
log.info("resource vendor model number exceeds limit.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(
- ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
"" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
throw new ComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
"" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
}
// resource vendor model number is currently validated as vendor
+
// name
if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
log.info("resource vendor model number is not valid.");
- ResponseFormat errorResponse = componentsUtils
- .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
throw new ComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
}
@@ -841,7 +775,6 @@ public class ServiceImportParseLogic {
componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
throw new ComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
}
-
validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
}
@@ -849,12 +782,11 @@ public class ServiceImportParseLogic {
if (vendorRelease != null) {
if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
log.info("vendor release exceds limit.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(
- ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
+ ResponseFormat errorResponse = componentsUtils
+ .getResponseFormat(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
throw new ComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
}
-
if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
log.info("vendor release is not valid.");
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
@@ -864,17 +796,14 @@ public class ServiceImportParseLogic {
}
}
- protected void validateCategory(User user, Resource resource,
- AuditingActionEnum actionEnum, boolean inTransaction) {
-
+ protected void validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
List<CategoryDefinition> categories = resource.getCategories();
if (CollectionUtils.isEmpty(categories)) {
log.debug(CATEGORY_IS_EMPTY);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
- ComponentTypeEnum.RESOURCE.getValue());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
- throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
- ComponentTypeEnum.RESOURCE.getValue());
+ throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
}
if (categories.size() > 1) {
log.debug("Must be only one category for resource");
@@ -890,30 +819,26 @@ public class ServiceImportParseLogic {
log.debug("Must be only one sub category for resource");
throw new ComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
}
-
SubCategoryDefinition subcategory = subcategories.get(0);
-
if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
log.debug(CATEGORY_IS_EMPTY);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
- ComponentTypeEnum.RESOURCE.getValue());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
- throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
- ComponentTypeEnum.RESOURCE.getValue());
+ throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
}
if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
log.debug(CATEGORY_IS_EMPTY);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(
- ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
}
-
validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
}
- protected void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory,
- User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
+ protected void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, User user, Resource resource,
+ AuditingActionEnum actionEnum, boolean inTransaction) {
ResponseFormat responseFormat;
if (category != null && subcategory != null) {
try {
@@ -927,24 +852,17 @@ public class ServiceImportParseLogic {
throw new ComponentException(categories.right().value());
}
List<CategoryDefinition> categoryList = categories.left().value();
- Optional<CategoryDefinition> foundCategory = categoryList.stream()
- .filter(cat -> cat.getName().equals(category.getName()))
+ Optional<CategoryDefinition> foundCategory = categoryList.stream().filter(cat -> cat.getName().equals(category.getName()))
.findFirst();
if (!foundCategory.isPresent()) {
- log.debug(
- "Category {} is not part of resource category group. Resource category valid values are {}",
- category, categoryList);
+ log.debug("Category {} is not part of resource category group. Resource category valid values are {}", category, categoryList);
failOnInvalidCategory(user, resource, actionEnum);
}
- Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get()
- .getSubcategories()
- .stream()
- .filter(subcat -> subcat.getName().equals(subcategory.getName()))
- .findFirst();
+ Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get().getSubcategories().stream()
+ .filter(subcat -> subcat.getName().equals(subcategory.getName())).findFirst();
if (!foundSubcategory.isPresent()) {
- log.debug(
- "SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
- subcategory, foundCategory.get().getSubcategories());
+ log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", subcategory,
+ foundCategory.get().getSubcategories());
failOnInvalidCategory(user, resource, actionEnum);
}
} catch (Exception e) {
@@ -956,15 +874,12 @@ public class ServiceImportParseLogic {
protected void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
ResponseFormat responseFormat;
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
- ComponentTypeEnum.RESOURCE.getValue());
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
- throw new ComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY,
- ComponentTypeEnum.RESOURCE.getValue());
+ throw new ComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
}
- protected void validateVendorName(User user, Resource resource,
- AuditingActionEnum actionEnum) {
+ protected void validateVendorName(User user, Resource resource, AuditingActionEnum actionEnum) {
String vendorName = resource.getVendorName();
if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
log.info("vendor name is missing.");
@@ -975,18 +890,15 @@ public class ServiceImportParseLogic {
validateVendorName(vendorName, user, resource, actionEnum);
}
- protected void validateVendorName(String vendorName, User user, Resource resource,
- AuditingActionEnum actionEnum) {
+ protected void validateVendorName(String vendorName, User user, Resource resource, AuditingActionEnum actionEnum) {
if (vendorName != null) {
if (!ValidationUtils.validateVendorNameLength(vendorName)) {
log.info("vendor name exceds limit.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
- "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
+ ResponseFormat errorResponse = componentsUtils
+ .getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
- throw new ComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
- "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
+ throw new ComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
}
-
if (!ValidationUtils.validateVendorName(vendorName)) {
log.info("vendor name is not valid.");
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
@@ -996,8 +908,7 @@ public class ServiceImportParseLogic {
}
}
- private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName,
- Map<String, NodeTypeInfo> nodesInfo) {
+ private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
Resource cvfc = new Resource();
NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
@@ -1013,15 +924,11 @@ public class ServiceImportParseLogic {
cvfc.setVendorName(resourceVf.getVendorName());
cvfc.setVendorRelease(resourceVf.getVendorRelease());
cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
- cvfc.setToscaResourceName(
- buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName)
- .getLeft());
+ cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
-
List<String> tags = new ArrayList<>();
tags.add(cvfc.getName());
cvfc.setTags(tags);
-
CategoryDefinition category = new CategoryDefinition();
category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
SubCategoryDefinition subCategory = new SubCategoryDefinition();
@@ -1030,17 +937,14 @@ public class ServiceImportParseLogic {
List<CategoryDefinition> categories = new ArrayList<>();
categories.add(category);
cvfc.setCategories(categories);
-
cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
-
return cvfc;
}
private String buildCvfcName(String resourceVfName, String nodeName) {
- String nameWithouNamespacePrefix = nodeName
- .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
+ String nameWithouNamespacePrefix = nodeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
String[] findTypes = nameWithouNamespacePrefix.split("\\.");
String resourceType = findTypes[0];
String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
@@ -1051,54 +955,43 @@ public class ServiceImportParseLogic {
return resourceName + "VF";
}
- public UploadResourceInfo fillResourceMetadata(String yamlName, Resource resourceVf,
- String nodeName, User user) {
+ public UploadResourceInfo fillResourceMetadata(String yamlName, Resource resourceVf, String nodeName, User user) {
UploadResourceInfo resourceMetaData = new UploadResourceInfo();
-
// validate nodetype name prefix
if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
- log.debug("invalid nodeName:{} does not start with {}.", nodeName,
- Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
- throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
- yamlName, resourceMetaData.getName(), nodeName);
+ log.debug("invalid nodeName:{} does not start with {}.", nodeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
+ throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
}
-
String actualName = this.getNodeTypeActualName(nodeName);
String namePrefix = nodeName.replace(actualName, "");
String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
-
// if we import from csar, the node_type name can be
+
// org.openecomp.resource.abstract.node_name - in this case we always
+
// create a vfc
if (resourceType.equals(Constants.ABSTRACT)) {
resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
}
// validating type
if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
- log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(),
- ResourceTypeEnum.values());
- throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
- yamlName, resourceMetaData.getName(), nodeName);
+ log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values());
+ throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
}
-
// Setting name
resourceMetaData.setName(resourceVf.getSystemName() + actualName);
-
// Setting type from name
String type = resourceType.toUpperCase();
resourceMetaData.setResourceType(type);
-
resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
resourceMetaData.setContactId(user.getUserId());
resourceMetaData.setVendorName(resourceVf.getVendorName());
resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
-
// Setting tag
List<String> tags = new ArrayList<>();
tags.add(resourceMetaData.getName());
resourceMetaData.setTags(tags);
-
// Setting category
CategoryDefinition category = new CategoryDefinition();
category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
@@ -1108,13 +1001,11 @@ public class ServiceImportParseLogic {
List<CategoryDefinition> categories = new ArrayList<>();
categories.add(category);
resourceMetaData.setCategories(categories);
-
return resourceMetaData;
}
protected String getNodeTypeActualName(String fullName) {
- String nameWithouNamespacePrefix = fullName
- .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
+ String nameWithouNamespacePrefix = fullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
String[] findTypes = nameWithouNamespacePrefix.split("\\.");
String resourceType = findTypes[0];
return nameWithouNamespacePrefix.substring(resourceType.length());
@@ -1129,8 +1020,7 @@ public class ServiceImportParseLogic {
public Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
UploadComponentInstanceInfo uploadComponentInstanceInfo,
- ComponentInstance currentCompInstance,
- String capName) {
+ ComponentInstance currentCompInstance, String capName) {
Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
List<RequirementDefinition> list = comInstRegDefMap.get(capName);
RequirementDefinition validRegDef = null;
@@ -1138,8 +1028,7 @@ public class ServiceImportParseLogic {
for (Map.Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
for (RequirementDefinition reqDef : entry.getValue()) {
if (reqDef.getName().equals(regName)) {
- if (reqDef.getMaxOccurrences() != null
- && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
+ if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
String leftOccurrences = reqDef.getLeftOccurrences();
if (leftOccurrences == null) {
leftOccurrences = reqDef.getMaxOccurrences();
@@ -1157,7 +1046,6 @@ public class ServiceImportParseLogic {
validRegDef = reqDef;
break;
}
-
}
}
if (validRegDef != null) {
@@ -1167,8 +1055,7 @@ public class ServiceImportParseLogic {
} else {
for (RequirementDefinition reqDef : list) {
if (reqDef.getName().equals(regName)) {
- if (reqDef.getMaxOccurrences() != null
- && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
+ if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
String leftOccurrences = reqDef.getLeftOccurrences();
if (leftOccurrences == null) {
leftOccurrences = reqDef.getMaxOccurrences();
@@ -1190,18 +1077,18 @@ public class ServiceImportParseLogic {
}
}
if (validRegDef == null) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
- yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
+ uploadComponentInstanceInfo.getType());
return Either.right(responseFormat);
}
return Either.left(validRegDef);
}
- public CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq,
- ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
+ public CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, ComponentInstance currentCapCompInstance,
+ UploadReqInfo uploadReqInfo) {
try {
- if (null == uploadReqInfo.getCapabilityName()
- || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {
+ if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {
// get by capability type
return findAvailableCapability(validReq, currentCapCompInstance);
}
@@ -1216,11 +1103,9 @@ public class ServiceImportParseLogic {
Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
if (capMap.containsKey(validReq.getCapability())) {
List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
-
for (CapabilityDefinition cap : capList) {
if (isBoundedByOccurrences(cap)) {
- String leftOccurrences = cap.getLeftOccurrences() != null ?
- cap.getLeftOccurrences() : cap.getMaxOccurrences();
+ String leftOccurrences = cap.getLeftOccurrences() != null ? cap.getLeftOccurrences() : cap.getMaxOccurrences();
int left = Integer.parseInt(leftOccurrences);
if (left > 0) {
--left;
@@ -1235,8 +1120,8 @@ public class ServiceImportParseLogic {
return null;
}
- protected CapabilityDefinition findAvailableCapability(RequirementDefinition validReq,
- ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
+ protected CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance,
+ UploadReqInfo uploadReqInfo) {
CapabilityDefinition cap = null;
Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
if (!capMap.containsKey(validReq.getCapability())) {
@@ -1248,16 +1133,13 @@ public class ServiceImportParseLogic {
return null;
}
cap = capByName.get();
-
if (isBoundedByOccurrences(cap)) {
String leftOccurrences = cap.getLeftOccurrences();
int left = Integer.parseInt(leftOccurrences);
if (left > 0) {
--left;
cap.setLeftOccurrences(String.valueOf(left));
-
}
-
}
return cap;
}
@@ -1283,6 +1165,7 @@ public class ServiceImportParseLogic {
parametersView.setIgnoreComponentInstances(false);
parametersView.setIgnoreInputs(false);
// inputs are read when creating
+
// property values on instances
parametersView.setIgnoreUsers(false);
return parametersView;
@@ -1309,13 +1192,10 @@ public class ServiceImportParseLogic {
if (isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) {
defaultCapability = defaultCapabilities.get(capabilityType).get(0);
} else {
- Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
- .getToscaFullElement(resourceId);
+ Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade.getToscaFullElement(resourceId);
if (getFullComponentRes.isRight()) {
- log.debug("Failed to get full component {}. Status is {}. ", resourceId,
- getFullComponentRes.right().value());
- throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND,
- resourceId));
+ log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right().value());
+ throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, resourceId));
}
defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
}
@@ -1323,33 +1203,27 @@ public class ServiceImportParseLogic {
}
protected void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId, CapabilityDefinition defaultCapability) {
- if (CollectionUtils.isEmpty(defaultCapability.getProperties())
- && isNotEmpty(capabilities.get(0).getProperties())) {
- log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
- defaultCapability.getName(), resourceId);
- log.debug(
- "Failed to update capability property values. Property list of fetched capability {} is empty. ",
- defaultCapability.getName());
+ if (CollectionUtils.isEmpty(defaultCapability.getProperties()) && isNotEmpty(capabilities.get(0).getProperties())) {
+ log.debug("Failed to validate capability {} of component {}. Property list is empty. ", defaultCapability.getName(), resourceId);
+ log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ", defaultCapability.getName());
throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId));
} else if (isNotEmpty(capabilities.get(0).getProperties())) {
validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
}
}
- protected void validateUniquenessUpdateUploadedComponentInstanceCapability(
- CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) {
+ protected void validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability,
+ UploadCapInfo uploadedCapability) {
List<ComponentInstanceProperty> validProperties = new ArrayList<>();
Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream()
- .collect(toMap(PropertyDefinition::getName, Function
- .identity()));
+ .collect(toMap(PropertyDefinition::getName, Function.identity()));
List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
for (UploadPropInfo property : uploadedProperties) {
String propertyName = property.getName().toLowerCase();
String propertyType = property.getType();
ComponentInstanceProperty validProperty;
if (defaultProperties.containsKey(propertyName) && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
- throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS,
- propertyName));
+ throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, propertyName));
}
validProperty = new ComponentInstanceProperty();
validProperty.setName(propertyName);
@@ -1381,15 +1255,14 @@ public class ServiceImportParseLogic {
if (artifactMap == null) {
artifactMap = new HashMap<>();
}
- Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
- .getConfiguration().getDeploymentResourceArtifacts();
+ Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getDeploymentResourceArtifacts();
if (deploymentResourceArtifacts != null) {
Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
deploymentResourceArtifacts.forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v));
}
resource.setDeploymentArtifacts(artifactMap);
}
-
}
protected void processDeploymentResourceArtifacts(User user, Resource resource, Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
@@ -1402,16 +1275,13 @@ public class ServiceImportParseLogic {
return;
}
} else {
- log.info("resource types for artifact placeholder {} were not defined. default is all resources",
- k);
+ log.info("resource types for artifact placeholder {} were not defined. default is all resources", k);
}
if (shouldCreateArtifact) {
if (serviceBusinessLogic.artifactsBusinessLogic != null) {
- ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic.createArtifactPlaceHolderInfo(
- resource.getUniqueId(), k, (Map<String, Object>) v,
- user, ArtifactGroupTypeEnum.DEPLOYMENT);
- if (artifactDefinition != null
- && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
+ ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
+ .createArtifactPlaceHolderInfo(resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
+ if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
}
}
@@ -1419,25 +1289,19 @@ public class ServiceImportParseLogic {
}
public void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
-
if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
newResource.setTags(oldResource.getTags());
}
-
if (newResource.getDescription() == null) {
newResource.setDescription(oldResource.getDescription());
}
-
if (newResource.getContactId() == null) {
newResource.setContactId(oldResource.getContactId());
}
-
newResource.setCategories(oldResource.getCategories());
-
}
- protected Resource buildComplexVfcMetadata(CsarInfo csarInfo, String nodeName,
- Map<String, NodeTypeInfo> nodesInfo) {
+ protected Resource buildComplexVfcMetadata(CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
Resource cvfc = new Resource();
NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
@@ -1453,15 +1317,11 @@ public class ServiceImportParseLogic {
cvfc.setVendorName("cmri");
cvfc.setVendorRelease("1.0");
cvfc.setResourceVendorModelNumber("");
- cvfc.setToscaResourceName(
- buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName)
- .getLeft());
+ cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
-
List<String> tags = new ArrayList<>();
tags.add(cvfc.getName());
cvfc.setTags(tags);
-
CategoryDefinition category = new CategoryDefinition();
category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
SubCategoryDefinition subCategory = new SubCategoryDefinition();
@@ -1470,11 +1330,9 @@ public class ServiceImportParseLogic {
List<CategoryDefinition> categories = new ArrayList<>();
categories.add(category);
cvfc.setCategories(categories);
-
cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
-
return cvfc;
}
@@ -1485,13 +1343,11 @@ public class ServiceImportParseLogic {
private void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
log.debug("validate resource derivedFrom field");
- if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty())
- || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) {
+ if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) || (resource.getDerivedFrom().get(0)) == null || (resource
+ .getDerivedFrom().get(0).trim().isEmpty())) {
log.info("derived from (template) field is missing for the resource");
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
-
throw new ComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
}
}
@@ -1499,46 +1355,40 @@ public class ServiceImportParseLogic {
public Service createInputsOnService(Service service, Map<String, InputDefinition> inputs) {
List<InputDefinition> resourceProperties = service.getInputs();
if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
-
- Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
- service);
+ Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, service);
if (createInputs.isRight()) {
throw new ComponentException(createInputs.right().value());
}
} else {
return service;
}
- Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade
- .getToscaElement(service.getUniqueId());
+ Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
if (updatedResource.isRight()) {
- throw new ComponentException(componentsUtils.getResponseFormatByComponent(
- componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service, ComponentTypeEnum.SERVICE));
+ throw new ComponentException(componentsUtils
+ .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
+ ComponentTypeEnum.SERVICE));
}
return updatedResource.left().value();
}
-
public Service createServiceTransaction(Service service, User user, boolean isNormative) {
// validate resource name uniqueness
log.debug("validate resource name");
- Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
- service.getName(), null, service.getComponentType());
+ Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade
+ .validateComponentNameExists(service.getName(), null, service.getComponentType());
if (eitherValidation.isRight()) {
- log.debug("Failed to validate component name {}. Status is {}. ", service.getName(),
- eitherValidation.right().value());
+ log.debug("Failed to validate component name {}. Status is {}. ", service.getName(), eitherValidation.right().value());
ResponseFormat errorResponse = componentsUtils
.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
throw new ComponentException(errorResponse);
}
if (eitherValidation.left().value()) {
log.debug("resource with name: {}, already exists", service.getName());
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
- ComponentTypeEnum.RESOURCE.getValue(), service.getName());
+ ResponseFormat errorResponse = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), service.getName());
throw new ComponentException(errorResponse);
}
-
log.debug("send resource {} to dao for create", service.getName());
-
createArtifactsPlaceHolderData(service, user);
// enrich object
if (!isNormative) {
@@ -1547,18 +1397,15 @@ public class ServiceImportParseLogic {
service.setVersion(INITIAL_VERSION);
service.setHighestVersion(true);
}
- return toscaOperationFacade.createToscaComponent(service)
- .left()
- .on(r -> throwComponentExceptionByResource(r, service));
+ return toscaOperationFacade.createToscaComponent(service).left().on(r -> throwComponentExceptionByResource(r, service));
}
public Service throwComponentExceptionByResource(StorageOperationStatus status, Service service) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(
- componentsUtils.convertFromStorageResponse(status), service, ComponentTypeEnum.SERVICE);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(status), service, ComponentTypeEnum.SERVICE);
throw new ComponentException(responseFormat);
}
-
protected void createArtifactsPlaceHolderData(Service service, User user) {
setInformationalArtifactsPlaceHolder(service, user);
serviceBusinessLogic.setDeploymentArtifactsPlaceHolder(service, user);
@@ -1567,40 +1414,34 @@ public class ServiceImportParseLogic {
@SuppressWarnings("unchecked")
protected void setInformationalArtifactsPlaceHolder(Service service, User user) {
-
Map<String, ArtifactDefinition> artifactMap = service.getArtifacts();
if (artifactMap == null) {
artifactMap = new HashMap<>();
}
String resourceUniqueId = service.getUniqueId();
- List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration()
- .getExcludeResourceCategory();
- List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration()
- .getExcludeResourceType();
- Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
- .getConfiguration().getInformationalResourceArtifacts();
+ List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
+ List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
+ Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getInformationalResourceArtifacts();
List<CategoryDefinition> categories = service.getCategories();
boolean isCreateArtifact = true;
if (exludeResourceCategory != null) {
String category = categories.get(0).getName();
isCreateArtifact = exludeResourceCategory.stream().noneMatch(e -> e.equalsIgnoreCase(category));
}
-
if (informationalResourceArtifacts != null && isCreateArtifact) {
Set<String> keys = informationalResourceArtifacts.keySet();
for (String informationalResourceArtifactName : keys) {
- Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
- .get(informationalResourceArtifactName);
+ Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
if (serviceBusinessLogic.artifactsBusinessLogic != null) {
- ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic.createArtifactPlaceHolderInfo(
- resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
- ArtifactGroupTypeEnum.INFORMATIONAL);
+ ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
+ .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
+ ArtifactGroupTypeEnum.INFORMATIONAL);
artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
}
}
}
service.setArtifacts(artifactMap);
-
}
public void rollback(boolean inTransaction, Service service, List<ArtifactDefinition> createdArtifacts,
@@ -1615,48 +1456,40 @@ public class ServiceImportParseLogic {
}
public Map<String, Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
- return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES)
- .left().orValue(HashMap::new);
+ return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES).left().orValue(HashMap::new);
}
- private Resource nodeForceCertification(Resource resource, User user,
- LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
- return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction,
- needLock);
+ private Resource nodeForceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
+ boolean needLock) {
+ return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
}
- private Resource nodeFullCertification(String uniqueId, User user,
- LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
+ private Resource nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
+ boolean needLock) {
Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic
- .changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo,
- inTransaction, needLock);
+ .changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
if (resourceResponse.isRight()) {
throw new ByResponseFormatComponentException(resourceResponse.right().value());
}
return resourceResponse.left().value();
}
- public Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
- Resource updateInfoResource, boolean hasBeenCertified) {
-
+ public Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource,
+ boolean hasBeenCertified) {
List<String> currentDerivedFrom = currentResource.getDerivedFrom();
List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
- if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
- || updatedDerivedFrom.isEmpty()) {
+ if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) {
log.trace("Update normative types");
return Either.left(true);
}
-
String derivedFromCurrent = currentDerivedFrom.get(0);
String derivedFromUpdated = updatedDerivedFrom.get(0);
-
if (!derivedFromCurrent.equals(derivedFromUpdated)) {
if (!hasBeenCertified) {
validateDerivedFromExist(null, updateInfoResource, null);
} else {
- Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
- currentResource, updateInfoResource, null);
-
+ Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource,
+ null);
if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
return validateDerivedFromExtending;
@@ -1666,45 +1499,35 @@ public class ServiceImportParseLogic {
return Either.left(true);
}
- protected Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
- Resource updateInfoResource, AuditingActionEnum actionEnum) {
+ protected Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource,
+ AuditingActionEnum actionEnum) {
String currentTemplateName = currentResource.getDerivedFrom().get(0);
String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
-
Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
.validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
if (dataModelResponse.isRight()) {
StorageOperationStatus storageStatus = dataModelResponse.right().value();
- BeEcompErrorManager.getInstance()
- .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
log.trace("audit before sending response");
componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
return Either.right(responseFormat);
}
-
if (!dataModelResponse.left().value()) {
- log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
- currentTemplateName);
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
+ log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, currentTemplateName);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
-
return Either.right(responseFormat);
-
}
return Either.left(true);
}
- public void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource,
- boolean inTransaction, boolean isNested) {
+ public void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
validateFields(currentResource, updateInfoResource, inTransaction, isNested);
}
-
private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
-
boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
log.debug("validate resource name before update");
validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
@@ -1726,12 +1549,9 @@ public class ServiceImportParseLogic {
}
log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
log.debug("validate category before update");
-
}
-
- protected void validateResourceName(Resource currentResource, Resource updateInfoResource,
- boolean hasBeenCertified, boolean isNested) {
+ protected void validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean isNested) {
String resourceNameUpdated = updateInfoResource.getName();
if (!isResourceNameEquals(currentResource, updateInfoResource)) {
if (isNested || !hasBeenCertified) {
@@ -1739,10 +1559,8 @@ public class ServiceImportParseLogic {
currentResource.setName(resourceNameUpdated);
currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
-
} else {
- log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
- resourceNameUpdated);
+ log.info("Resource name: {}, cannot be updated once the resource has been certified once.", resourceNameUpdated);
throw new ComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
}
}
@@ -1754,34 +1572,25 @@ public class ServiceImportParseLogic {
if (resourceNameCurrent.equals(resourceNameUpdated)) {
return true;
}
- return currentResource.getResourceType().equals(ResourceTypeEnum.VF) &&
- resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
+ return currentResource.getResourceType().equals(ResourceTypeEnum.VF) && resourceNameUpdated
+ .equals(addCvfcSuffixToResourceName(resourceNameCurrent));
}
- public Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user,
- boolean inTransaction, boolean needLock) {
-
+ public Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user, boolean inTransaction, boolean needLock) {
if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
// checkout
- return lifecycleBusinessLogic.changeState(
- oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
- new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock)
- .left()
- .on(response -> failOnChangeState(response, user, oldResource, newResource));
+ return lifecycleBusinessLogic
+ .changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"),
+ inTransaction, needLock).left().on(response -> failOnChangeState(response, user, oldResource, newResource));
}
return oldResource;
}
protected Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
if (response.getRequestError() != null) {
- log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(),
- response.getFormattedMessage());
-
+ log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage());
componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
- ResourceVersionInfo.newBuilder()
- .state(oldResource.getLifecycleState().name())
- .version(oldResource.getVersion())
- .build());
+ ResourceVersionInfo.newBuilder().state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build());
}
throw new ComponentException(response);
}
@@ -1797,20 +1606,17 @@ public class ServiceImportParseLogic {
public Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
List<InputDefinition> resourceProperties = resource.getInputs();
if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
-
- Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
- resource);
+ Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource);
if (createInputs.isRight()) {
throw new ComponentException(createInputs.right().value());
}
} else {
return resource;
}
- Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
- .getToscaElement(resource.getUniqueId());
+ Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
if (updatedResource.isRight()) {
- throw new ComponentException(componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
+ throw new ComponentException(
+ componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
}
return updatedResource.left().value();
}
@@ -1830,25 +1636,18 @@ public class ServiceImportParseLogic {
if (isNotEmpty(groupsToCreate)) {
fillGroupsFinalFields(groupsToCreate);
if (isNotEmpty(groupsFromResource)) {
- serviceBusinessLogic.groupBusinessLogic.addGroups(resource,
- groupsToCreate, true)
- .left()
+ serviceBusinessLogic.groupBusinessLogic.addGroups(resource, groupsToCreate, true).left()
.on(serviceBusinessLogic::throwComponentException);
} else {
- serviceBusinessLogic.groupBusinessLogic.createGroups(resource,
- groupsToCreate, true)
- .left()
+ serviceBusinessLogic.groupBusinessLogic.createGroups(resource, groupsToCreate, true).left()
.on(serviceBusinessLogic::throwComponentException);
}
}
if (isNotEmpty(groupsToDelete)) {
- serviceBusinessLogic.groupBusinessLogic.deleteGroups(resource, groupsToDelete)
- .left()
- .on(serviceBusinessLogic::throwComponentException);
+ serviceBusinessLogic.groupBusinessLogic.deleteGroups(resource, groupsToDelete).left().on(serviceBusinessLogic::throwComponentException);
}
if (isNotEmpty(groupsToUpdate)) {
- serviceBusinessLogic.groupBusinessLogic.updateGroups(resource, groupsToUpdate, true)
- .left()
+ serviceBusinessLogic.groupBusinessLogic.updateGroups(resource, groupsToUpdate, true).left()
.on(serviceBusinessLogic::throwComponentException);
}
}
@@ -1856,8 +1655,8 @@ public class ServiceImportParseLogic {
protected void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
for (GroupDefinition group : groupsAsList) {
- Optional<GroupDefinition> op = groupsFromResource.stream()
- .filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName())).findAny();
+ Optional<GroupDefinition> op = groupsFromResource.stream().filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName()))
+ .findAny();
if (op.isPresent()) {
GroupDefinition groupToUpdate = op.get();
groupToUpdate.setMembers(group.getMembers());
@@ -1873,8 +1672,7 @@ public class ServiceImportParseLogic {
protected void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
List<GroupDefinition> groupsToDelete) {
for (GroupDefinition group : groupsFromResource) {
- Optional<GroupDefinition> op = groupsAsList.stream()
- .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
+ Optional<GroupDefinition> op = groupsAsList.stream().filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
groupsToDelete.add(group);
}
@@ -1882,10 +1680,8 @@ public class ServiceImportParseLogic {
}
protected List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Service component) {
-
List<GroupDefinition> result = new ArrayList<>();
List<ComponentInstance> componentInstances = component.getComponentInstances();
-
if (groups != null) {
Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
if (validateCyclicGroupsDependencies.isRight()) {
@@ -1909,42 +1705,35 @@ public class ServiceImportParseLogic {
public void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Service component,
List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
Set<String> compInstancesNames = members.keySet();
-
if (CollectionUtils.isEmpty(componentInstances)) {
String membersAstString = compInstancesNames.stream().collect(joining(","));
- log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
- membersAstString, groupName, component.getNormalizedName());
- throw new ComponentException(componentsUtils.getResponseFormat(
- ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
- component.getNormalizedName(), getComponentTypeForResponse(component)));
+ log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString,
+ groupName, component.getNormalizedName());
+ throw new ComponentException(componentsUtils
+ .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
+ getComponentTypeForResponse(component)));
}
// Find all component instances with the member names
- Map<String, String> memberNames = componentInstances.stream()
- .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
+ Map<String, String> memberNames = componentInstances.stream().collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
- Map<String, String> relevantInstances = memberNames.entrySet().stream()
- .filter(n -> compInstancesNames.contains(n.getKey()))
+ Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey()))
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
-
if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
-
List<String> foundMembers = new ArrayList<>();
if (relevantInstances != null) {
foundMembers = relevantInstances.keySet().stream().collect(toList());
}
compInstancesNames.removeAll(foundMembers);
String membersAstString = compInstancesNames.stream().collect(joining(","));
- log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString,
- groupName, component.getNormalizedName());
- throw new ComponentException(componentsUtils.getResponseFormat(
- ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
- component.getNormalizedName(), getComponentTypeForResponse(component)));
+ log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName());
+ throw new ComponentException(componentsUtils
+ .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
+ getComponentTypeForResponse(component)));
}
updatedGroupDefinition.setMembers(relevantInstances);
}
public Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
-
Either<Boolean, ResponseFormat> result = Either.left(true);
try {
Iterator<Map.Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
@@ -1957,8 +1746,7 @@ public class ServiceImportParseLogic {
fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
// If A is a group member of itself found cyclic dependency
if (allGroupAMembersNames.contains(groupAName)) {
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
result = Either.right(responseFormat);
}
}
@@ -1970,9 +1758,7 @@ public class ServiceImportParseLogic {
return result;
}
- protected void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups,
- Set<String> allGroupMembers) {
-
+ protected void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups, Set<String> allGroupMembers) {
// Found Cyclic dependency
if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
return;
@@ -1981,6 +1767,7 @@ public class ServiceImportParseLogic {
// All Members Of Current Group Resource Instances & Other Groups
Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
// Filtered Members Of Current Group containing only members which
+
// are groups
List<String> currGroupFilteredMembers = currGroupMembers.stream().
// Keep Only Elements of type group and not Resource Instances
@@ -1989,7 +1776,6 @@ public class ServiceImportParseLogic {
peek(allGroupMembers::add).
// Collect results
collect(toList());
-
// Recursively call the method for all the filtered group members
for (String innerGroupName : currGroupFilteredMembers) {
fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
@@ -2000,83 +1786,65 @@ public class ServiceImportParseLogic {
boolean isInTransaction, boolean needLock,
Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
- boolean forceCertificationAllowed, CsarInfo csarInfo,
- String nodeName, boolean isNested) {
-
+ boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName,
+ boolean isNested) {
LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
-
- Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(
- resource, creator);
-
- return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
- lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle,
- nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
- }
-
- public ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(
- String yamlName, Map.Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert,
- Service resourceVf, boolean needLock,
- Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
- List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
- boolean isNested) {
-
+ Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(resource, creator);
+ return resourceImportManager
+ .importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock,
+ nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
+ }
+
+ public ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(String yamlName, Map.Entry<String, Object> nodeNameValue, User user,
+ Map<String, Object> mapToConvert, Service resourceVf,
+ boolean needLock,
+ Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
+ boolean forceCertificationAllowed, CsarInfo csarInfo,
+ boolean isNested) {
UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
-
- String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert,
- resourceMetaData.getResourceType(), csarInfo);
+ String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
user = serviceBusinessLogic.validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
- return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock,
- nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
- nodeNameValue.getKey(), isNested);
+ return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, nodeTypeArtifactsToHandle,
+ nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested);
}
- protected UploadResourceInfo fillResourceMetadata(String yamlName, Service resourceVf,
- String nodeName, User user) {
+ protected UploadResourceInfo fillResourceMetadata(String yamlName, Service resourceVf, String nodeName, User user) {
UploadResourceInfo resourceMetaData = new UploadResourceInfo();
-
// validate nodetype name prefix
if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
- log.debug("invalid nodeName:{} does not start with {}.", nodeName,
- Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
- throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
- yamlName, resourceMetaData.getName(), nodeName);
+ log.debug("invalid nodeName:{} does not start with {}.", nodeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
+ throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
}
-
String actualName = this.getNodeTypeActualName(nodeName);
String namePrefix = nodeName.replace(actualName, "");
String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
-
// if we import from csar, the node_type name can be
+
// org.openecomp.resource.abstract.node_name - in this case we always
+
// create a vfc
if (resourceType.equals(Constants.ABSTRACT)) {
resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
}
// validating type
if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
- log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(),
- ResourceTypeEnum.values());
- throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
- yamlName, resourceMetaData.getName(), nodeName);
+ log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values());
+ throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
}
-
// Setting name
resourceMetaData.setName(resourceVf.getSystemName() + actualName);
-
// Setting type from name
String type = resourceType.toUpperCase();
resourceMetaData.setResourceType(type);
-
resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
resourceMetaData.setContactId(user.getUserId());
-
// Setting tag
List<String> tags = new ArrayList<>();
tags.add(resourceMetaData.getName());
resourceMetaData.setTags(tags);
-
// Setting category
CategoryDefinition category = new CategoryDefinition();
category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
@@ -2086,24 +1854,20 @@ public class ServiceImportParseLogic {
List<CategoryDefinition> categories = new ArrayList<>();
categories.add(category);
resourceMetaData.setCategories(categories);
-
return resourceMetaData;
}
-
- public Resource propagateStateToCertified(User user, Resource resource,
- LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
- boolean forceCertificationAllowed) {
-
+ public Resource propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
+ boolean needLock, boolean forceCertificationAllowed) {
Either<Resource, ResponseFormat> result = null;
try {
- if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed
- && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) {
+ if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed && lifecycleBusinessLogic
+ .isFirstCertification(resource.getVersion())) {
nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
}
if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
- Either<ArtifactDefinition, Operation> eitherPopulated = serviceBusinessLogic.populateToscaArtifacts(
- resource, user, false, inTransaction, needLock);
+ Either<ArtifactDefinition, Operation> eitherPopulated = serviceBusinessLogic
+ .populateToscaArtifacts(resource, user, false, inTransaction, needLock);
return resource;
}
return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
@@ -2122,14 +1886,11 @@ public class ServiceImportParseLogic {
}
}
- public Resource buildValidComplexVfc(CsarInfo csarInfo, String nodeName,
- Map<String, NodeTypeInfo> nodesInfo) {
-
+ public Resource buildValidComplexVfc(CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
Resource complexVfc = buildComplexVfcMetadata(csarInfo, nodeName, nodesInfo);
log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
csarInfo.addNodeToQueue(nodeName);
- return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(),
- AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
+ return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
}
public Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
@@ -2138,28 +1899,24 @@ public class ServiceImportParseLogic {
} else {
updateOrCreateGroups(resource, groups);
}
- Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
- .getToscaElement(resource.getUniqueId());
+ Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
if (updatedResource.isRight()) {
- throw new ComponentException(componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
+ throw new ComponentException(
+ componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
}
return updatedResource.left().value();
}
protected void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
-
Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
if (artifactMap == null) {
artifactMap = new HashMap<>();
}
String resourceUniqueId = resource.getUniqueId();
- List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration()
- .getExcludeResourceCategory();
- List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration()
- .getExcludeResourceType();
- Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
- .getConfiguration().getInformationalResourceArtifacts();
+ List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
+ List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
+ Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getInformationalResourceArtifacts();
List<CategoryDefinition> categories = resource.getCategories();
boolean isCreateArtifact = true;
if (exludeResourceCategory != null) {
@@ -2173,18 +1930,16 @@ public class ServiceImportParseLogic {
if (informationalResourceArtifacts != null && isCreateArtifact) {
Set<String> keys = informationalResourceArtifacts.keySet();
for (String informationalResourceArtifactName : keys) {
- Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
- .get(informationalResourceArtifactName);
+ Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
if (serviceBusinessLogic.artifactsBusinessLogic != null) {
- ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic.createArtifactPlaceHolderInfo(
- resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
- ArtifactGroupTypeEnum.INFORMATIONAL);
+ ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
+ .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
+ ArtifactGroupTypeEnum.INFORMATIONAL);
artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
}
}
}
resource.setArtifacts(artifactMap);
-
}
public void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts,
@@ -2207,10 +1962,7 @@ public class ServiceImportParseLogic {
public void handleGroupsProperties(Service service, Map<String, GroupDefinition> groups) {
List<InputDefinition> inputs = service.getInputs();
if (MapUtils.isNotEmpty(groups)) {
- groups.values()
- .stream()
- .filter(g -> isNotEmpty(g.getProperties()))
- .flatMap(g -> g.getProperties().stream())
+ groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream())
.forEach(p -> handleGetInputs(p, inputs));
}
}
@@ -2218,10 +1970,7 @@ public class ServiceImportParseLogic {
public void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
List<InputDefinition> inputs = resource.getInputs();
if (MapUtils.isNotEmpty(groups)) {
- groups.values()
- .stream()
- .filter(g -> isNotEmpty(g.getProperties()))
- .flatMap(g -> g.getProperties().stream())
+ groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream())
.forEach(p -> handleGetInputs(p, inputs));
}
}
@@ -2230,10 +1979,8 @@ public class ServiceImportParseLogic {
if (isNotEmpty(property.getGetInputValues())) {
if (inputs == null || inputs.isEmpty()) {
log.debug("Failed to add property {} to group. Inputs list is empty ", property);
- serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
- .stream()
- .map(GetInputValueDataDefinition::getInputName)
- .collect(toList()).toString());
+ serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND,
+ property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
}
ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues().listIterator();
while (getInputValuesIter.hasNext()) {
@@ -2251,9 +1998,7 @@ public class ServiceImportParseLogic {
}
public InputDefinition findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
- Optional<InputDefinition> inputOpt = inputs.stream()
- .filter(p -> p.getName().equals(getInput.getInputName()))
- .findFirst();
+ Optional<InputDefinition> inputOpt = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findFirst();
if (!inputOpt.isPresent()) {
log.debug("#findInputByName - Failed to find the input {} ", getInput.getInputName());
serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, getInput.getInputName());
@@ -2267,10 +2012,9 @@ public class ServiceImportParseLogic {
Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
.associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
if (addPropToInst.isRight()) {
- log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
- addPropToInst.right().value());
- throw new ComponentException(componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
+ log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), addPropToInst.right().value());
+ throw new ComponentException(
+ componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
}
} catch (Exception e) {
log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage());
@@ -2284,71 +2028,55 @@ public class ServiceImportParseLogic {
Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
.associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
if (addInputToInst.isRight()) {
- log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
- addInputToInst.right().value());
- throw new ComponentException(componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
+ log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), addInputToInst.right().value());
+ throw new ComponentException(
+ componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
}
}
}
public void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource,
Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
- StorageOperationStatus addArtToInst = toscaOperationFacade
- .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
+ StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
- throw new ComponentException(componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
+ throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
}
}
public void associateArtifactsToInstances(String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
-
StorageOperationStatus addArtToInst;
-
addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
- throw new ComponentException(componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
+ throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
}
}
public void associateOrAddCalculatedCapReq(String yamlName, Resource resource,
Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
-
StorageOperationStatus addArtToInst;
- addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
- resource);
+ addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, resource);
if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
- log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
- addArtToInst);
- throw new ComponentException(componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
+ log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+ throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
}
}
public void associateInstAttributeToComponentToInstances(String yamlName, Resource resource,
Map<String, List<AttributeDefinition>> instAttributes) {
-
StorageOperationStatus addArtToInst;
- addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
- resource);
+ addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource);
if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
- log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
- addArtToInst);
- throw new ComponentException(componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
+ log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+ throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
}
}
public Resource getResourceAfterCreateRelations(Resource resource) {
ComponentParametersView parametersView = getComponentFilterAfterCreateRelations();
- Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
- .getToscaElement(resource.getUniqueId(), parametersView);
-
+ Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
if (eitherGetResource.isRight()) {
throwComponentExceptionByResource(eitherGetResource.right().value(), resource);
}
@@ -2356,8 +2084,7 @@ public class ServiceImportParseLogic {
}
public Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(status), resource);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource);
throw new ComponentException(responseFormat);
}
@@ -2380,10 +2107,9 @@ public class ServiceImportParseLogic {
}
}
- public Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(
- String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities,
- Map<String, List<UploadCapInfo>> uploadedCapabilities) {
-
+ public Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(String resourceId,
+ Map<String, List<CapabilityDefinition>> defaultCapabilities,
+ Map<String, List<UploadCapInfo>> uploadedCapabilities) {
Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId, defaultCapabilities, validCapabilitiesMap));
return validCapabilitiesMap;
@@ -2394,10 +2120,9 @@ public class ServiceImportParseLogic {
Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
.associateComponentInstanceInputsToComponent(instInputs, service.getUniqueId());
if (addInputToInst.isRight()) {
- log.debug("failed to associate inputs value of resource {} status is {}", service.getUniqueId(),
- addInputToInst.right().value());
- throw new ComponentException(componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
+ log.debug("failed to associate inputs value of resource {} status is {}", service.getUniqueId(), addInputToInst.right().value());
+ throw new ComponentException(
+ componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
}
}
}
@@ -2407,30 +2132,26 @@ public class ServiceImportParseLogic {
Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
.associateComponentInstancePropertiesToComponent(instProperties, service.getUniqueId());
if (addPropToInst.isRight()) {
- throw new ComponentException(componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
+ throw new ComponentException(
+ componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
}
}
public void associateDeploymentArtifactsToInstances(User user, String yamlName, Service resource,
Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
- StorageOperationStatus addArtToInst = toscaOperationFacade
- .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
+ StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
- throw new ComponentException(componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
+ throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
}
}
public void associateArtifactsToInstances(String yamlName, Service resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
StorageOperationStatus addArtToInst;
-
addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
- throw new ComponentException(componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
+ throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
}
}
@@ -2438,86 +2159,66 @@ public class ServiceImportParseLogic {
Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
StorageOperationStatus addArtToInst;
- addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
- resource);
- log.debug("enter associateOrAddCalculatedCapReq,get instCapabilities:{},get instRequirements:{}",
- instCapabilities, instRequirements);
+ addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, resource);
+ log.debug("enter associateOrAddCalculatedCapReq,get instCapabilities:{},get instRequirements:{}", instCapabilities, instRequirements);
if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
- log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
- addArtToInst);
- throw new ComponentException(componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
+ log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+ throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
}
}
public void associateInstAttributeToComponentToInstances(String yamlName, Service resource,
Map<String, List<AttributeDefinition>> instAttributes) {
StorageOperationStatus addArtToInst;
-
- addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
- resource);
+ addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource);
if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
- log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
- addArtToInst);
- throw new ComponentException(componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
+ log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+ throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
}
}
public void associateRequirementsToService(String yamlName, Service resource, Map<String, ListRequirementDataDefinition> requirements) {
StorageOperationStatus addReqToService;
- addReqToService = toscaOperationFacade.associateRequirementsToService(requirements,
- resource.getUniqueId());
+ addReqToService = toscaOperationFacade.associateRequirementsToService(requirements, resource.getUniqueId());
if (addReqToService != StorageOperationStatus.OK && addReqToService != StorageOperationStatus.NOT_FOUND) {
- log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
- addReqToService);
- throw new ComponentException(componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(addReqToService), yamlName));
+ log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addReqToService);
+ throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addReqToService), yamlName));
}
}
public void associateCapabilitiesToService(String yamlName, Service resource, Map<String, ListCapabilityDataDefinition> capabilities) {
StorageOperationStatus addCapToService;
- addCapToService = toscaOperationFacade.associateCapabilitiesToService(capabilities,
- resource.getUniqueId());
+ addCapToService = toscaOperationFacade.associateCapabilitiesToService(capabilities, resource.getUniqueId());
if (addCapToService != StorageOperationStatus.OK && addCapToService != StorageOperationStatus.NOT_FOUND) {
- log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
- addCapToService);
- throw new ComponentException(componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(addCapToService), yamlName));
+ log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addCapToService);
+ throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addCapToService), yamlName));
}
}
public void associateResourceInstances(String yamlName, Service service, List<RequirementCapabilityRelDef> relations) {
Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade
.associateResourceInstances(service, service.getUniqueId(), relations);
-
if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
StorageOperationStatus status = relationsEither.right().value();
- log.debug("failed to associate instances of service {} status is {}", service.getUniqueId(),
- status);
- throw new ComponentException(componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
+ log.debug("failed to associate instances of service {} status is {}", service.getUniqueId(), status);
+ throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
}
}
public void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type, List<CapabilityDefinition> capabilities) {
- List<CapabilityDefinition> list = capabilities.stream().map(CapabilityDefinition::new)
- .collect(toList());
+ List<CapabilityDefinition> list = capabilities.stream().map(CapabilityDefinition::new).collect(toList());
originCapabilities.put(type, list);
}
public void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap, List<UploadCapInfo> capabilities) {
for (UploadCapInfo capability : capabilities) {
if (isNotEmpty(capability.getProperties())) {
- newPropertiesMap.put(capability.getName(), capability.getProperties().stream()
- .collect(toMap(UploadInfo::getName, p -> p)));
+ newPropertiesMap.put(capability.getName(), capability.getProperties().stream().collect(toMap(UploadInfo::getName, p -> p)));
}
}
}
public Service getServiceWithGroups(String resourceId) {
-
ComponentParametersView filter = new ComponentParametersView();
filter.setIgnoreGroups(false);
Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
@@ -2528,7 +2229,6 @@ public class ServiceImportParseLogic {
}
public Resource getResourceWithGroups(String resourceId) {
-
ComponentParametersView filter = new ComponentParametersView();
filter.setIgnoreGroups(false);
Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
@@ -2539,15 +2239,12 @@ public class ServiceImportParseLogic {
}
public void associateResourceInstances(String yamlName, Resource resource, List<RequirementCapabilityRelDef> relations) {
-
Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade
.associateResourceInstances(resource, resource.getUniqueId(), relations);
if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
StorageOperationStatus status = relationsEither.right().value();
- log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
- status);
- throw new ComponentException(componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
+ log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), status);
+ throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
}
}
@@ -2557,23 +2254,19 @@ public class ServiceImportParseLogic {
UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
ComponentInstance currentCompInstance = null;
for (ComponentInstance compInstance : componentInstancesList) {
-
if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
currentCompInstance = compInstance;
break;
}
}
if (currentCompInstance == null) {
- log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
- resource.getUniqueId());
- BeEcompErrorManager.getInstance().logInternalDataError(
- COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
- resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), resource.getUniqueId());
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, resource.getUniqueId(),
+ BeEcompErrorManager.ErrorSeverity.ERROR);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
throw new ComponentException(responseFormat);
}
-
ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
if (addRelationToRiRes.getStatus() != 200) {
throw new ComponentException(addRelationToRiRes);
@@ -2581,30 +2274,25 @@ public class ServiceImportParseLogic {
}
}
- protected ResponseFormat addRelationToRI(String yamlName, Resource resource,
- UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
+ protected ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue,
+ List<RequirementCapabilityRelDef> relations) {
List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
ComponentInstance currentCompInstance = null;
-
for (ComponentInstance compInstance : componentInstancesList) {
-
if (compInstance.getName().equals(nodesInfoValue.getName())) {
currentCompInstance = compInstance;
break;
}
}
if (currentCompInstance == null) {
- log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(),
- resource.getUniqueId());
- BeEcompErrorManager.getInstance().logInternalDataError(
- COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
- resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
- return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
- yamlName);
+ log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId());
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, resource.getUniqueId(),
+ BeEcompErrorManager.ErrorSeverity.ERROR);
+ return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
}
String resourceInstanceId = currentCompInstance.getUniqueId();
Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
-
if (regMap != null) {
Iterator<Map.Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
while (nodesRegValue.hasNext()) {
@@ -2616,16 +2304,13 @@ public class ServiceImportParseLogic {
RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
regCapRelDef.setFromNode(resourceInstanceId);
log.debug("try to find available requirement {} ", regName);
- Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
- yamlName, nodesInfoValue, currentCompInstance,
- uploadRegInfo.getCapabilityName());
+ Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, yamlName, nodesInfoValue,
+ currentCompInstance, uploadRegInfo.getCapabilityName());
if (eitherReqStatus.isRight()) {
return eitherReqStatus.right().value();
}
-
RequirementDefinition validReq = eitherReqStatus.left().value();
- List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
- .getRelationships();
+ List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef.getRelationships();
if (reqAndRelationshipPairList == null) {
reqAndRelationshipPairList = new ArrayList<>();
}
@@ -2636,7 +2321,6 @@ public class ServiceImportParseLogic {
RelationshipImpl relationship = new RelationshipImpl();
relationship.setType(validReq.getCapability());
reqAndRelationshipPair.setRelationships(relationship);
-
ComponentInstance currentCapCompInstance = null;
for (ComponentInstance compInstance : componentInstancesList) {
if (compInstance.getName().equals(uploadRegInfo.getNode())) {
@@ -2644,30 +2328,24 @@ public class ServiceImportParseLogic {
break;
}
}
-
if (currentCapCompInstance == null) {
- log.debug("The component instance with name {} not found on resource {} ",
- uploadRegInfo.getNode(), resource.getUniqueId());
- BeEcompErrorManager.getInstance().logInternalDataError(
- COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
- resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
- return componentsUtils
- .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ log.debug("The component instance with name {} not found on resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, resource.getUniqueId(),
+ BeEcompErrorManager.ErrorSeverity.ERROR);
+ return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
}
regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
log.debug("try to find aviable Capability req name is {} ", validReq.getName());
- CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
- currentCapCompInstance, uploadRegInfo);
+ CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
if (aviableCapForRel == null) {
BeEcompErrorManager.getInstance().logInternalDataError(
- "aviable capability was not found. req name is " + validReq.getName()
- + " component instance is " + currentCapCompInstance.getUniqueId(),
- resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
- return componentsUtils
- .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ "aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance
+ .getUniqueId(), resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
+ return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
}
CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
capReqRel.setRelation(reqAndRelationshipPair);
@@ -2681,5 +2359,4 @@ public class ServiceImportParseLogic {
}
return componentsUtils.getResponseFormat(ActionStatus.OK);
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/SoftwareInformationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/SoftwareInformationBusinessLogic.java
index d6b17ca604..576dc41ccc 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/SoftwareInformationBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/SoftwareInformationBusinessLogic.java
@@ -16,9 +16,13 @@
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
+import static java.util.stream.Collectors.toList;
+import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
+
+import java.util.List;
+import java.util.Optional;
import org.apache.commons.collections.CollectionUtils;
import org.openecomp.sdc.be.components.csar.CsarInfo;
import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
@@ -33,18 +37,12 @@ import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import java.util.List;
-import java.util.Optional;
-
-import static java.util.stream.Collectors.toList;
-import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
-
@Component("softwareInformationBusinessLogic")
public class SoftwareInformationBusinessLogic {
- private final PropertyBusinessLogic propertyBusinessLogic;
private static final String SOFTWARE_VERSION_PROPERTY_NAME = "software_versions";
private static final String DEFAULT_SOFTWARE_VERSION_PROPERTY_NAME = "default_software_version";
+ private final PropertyBusinessLogic propertyBusinessLogic;
@Autowired
public SoftwareInformationBusinessLogic(final PropertyBusinessLogic propertyBusinessLogic) {
@@ -53,17 +51,16 @@ public class SoftwareInformationBusinessLogic {
/**
* Adds the software information from a csar package to the resource {@link SoftwareInformationBusinessLogic#SOFTWARE_VERSION_PROPERTY_NAME}
- * property.<br/> The csar package must contain the expected non-mano yaml file with the software information. Also
- * the resource must have the {@link SoftwareInformationBusinessLogic#SOFTWARE_VERSION_PROPERTY_NAME} property.
+ * property.<br/> The csar package must contain the expected non-mano yaml file with the software information. Also the resource must have the
+ * {@link SoftwareInformationBusinessLogic#SOFTWARE_VERSION_PROPERTY_NAME} property.
*
* @param resource the resource to add the software information
* @param csarInfo the csar package representation
- * @return if the expected property exists in the resource and the csar package contains the software information
- * file, an Optional<PropertyDefinition> with the updated property; otherwise Optional.empty().
+ * @return if the expected property exists in the resource and the csar package contains the software information file, an
+ * Optional<PropertyDefinition> with the updated property; otherwise Optional.empty().
* @throws BusinessLogicException when there was a problem while updating the property
*/
- public Optional<PropertyDefinition> setSoftwareInformation(final Resource resource,
- final CsarInfo csarInfo) throws BusinessLogicException {
+ public Optional<PropertyDefinition> setSoftwareInformation(final Resource resource, final CsarInfo csarInfo) throws BusinessLogicException {
final Optional<String> softwareInformation = csarInfo.getSoftwareInformationPath();
if (!softwareInformation.isPresent()) {
return Optional.empty();
@@ -73,26 +70,22 @@ public class SoftwareInformationBusinessLogic {
return Optional.empty();
}
final byte[] softwareInformationYaml = csarInfo.getCsar().get(softwareInformation.get());
- final PnfSoftwareInformation pnfSoftwareInformation =
- parseSoftwareInformation(softwareInformationYaml).orElse(null);
+ final PnfSoftwareInformation pnfSoftwareInformation = parseSoftwareInformation(softwareInformationYaml).orElse(null);
if (pnfSoftwareInformation == null) {
return Optional.empty();
}
-
- final List<String> versionList = pnfSoftwareInformation.getSoftwareVersionSet().stream()
- .map(PnfSoftwareVersion::getVersion).collect(toList());
- final String softwareVersionInformation =
- getPropertyJsonStringValue(versionList, ToscaPropertyType.LIST.getType());
+ final List<String> versionList = pnfSoftwareInformation.getSoftwareVersionSet().stream().map(PnfSoftwareVersion::getVersion)
+ .collect(toList());
+ final String softwareVersionInformation = getPropertyJsonStringValue(versionList, ToscaPropertyType.LIST.getType());
propertyDefinition.setValue(softwareVersionInformation);
-
- final PropertyDefinition updatedPropertyDefinition =
- propertyBusinessLogic.updateComponentProperty(resource.getUniqueId(), propertyDefinition);
-
+ final PropertyDefinition updatedPropertyDefinition = propertyBusinessLogic
+ .updateComponentProperty(resource.getUniqueId(), propertyDefinition);
// set default-software-version as first entry of software version list for resource type pnf
- if(resource.getResourceType() == ResourceTypeEnum.PNF && !versionList.isEmpty()){
+ if (resource.getResourceType() == ResourceTypeEnum.PNF && !versionList.isEmpty()) {
final String sw_version = versionList.get(0);
- Optional<InputDefinition> default_Sw_Ver_PropertyDefinition = resource.safeGetInputs().stream().filter(s->DEFAULT_SOFTWARE_VERSION_PROPERTY_NAME.equals(s.getName())).findFirst();
- if(default_Sw_Ver_PropertyDefinition.isPresent()) {
+ Optional<InputDefinition> default_Sw_Ver_PropertyDefinition = resource.safeGetInputs().stream()
+ .filter(s -> DEFAULT_SOFTWARE_VERSION_PROPERTY_NAME.equals(s.getName())).findFirst();
+ if (default_Sw_Ver_PropertyDefinition.isPresent()) {
default_Sw_Ver_PropertyDefinition.get().setDefaultValue(sw_version);
}
}
@@ -103,8 +96,7 @@ public class SoftwareInformationBusinessLogic {
* Parses the non-mano software information yaml file.
*
* @param softwareInformationYaml the file byte array
- * @return an {@code Optional<PnfSoftwareInformation>} if the file was successful parsed, otherwise {@code
- * Optional.empty()}
+ * @return an {@code Optional<PnfSoftwareInformation>} if the file was successful parsed, otherwise {@code Optional.empty()}
*/
private Optional<PnfSoftwareInformation> parseSoftwareInformation(byte[] softwareInformationYaml) {
return SoftwareInformationArtifactYamlParser.parse(softwareInformationYaml);
@@ -112,6 +104,7 @@ public class SoftwareInformationBusinessLogic {
/**
* Finds the {@link SoftwareInformationBusinessLogic#SOFTWARE_VERSION_PROPERTY_NAME} property in a Resource
+ *
* @param resource the resource to search for the property
* @return an {@code Optional<PnfSoftwareInformation>} if the property was found, otherwise {@code Optional.empty()}
*/
@@ -119,8 +112,7 @@ public class SoftwareInformationBusinessLogic {
if (CollectionUtils.isEmpty(resource.getProperties())) {
return Optional.empty();
}
- return resource.getProperties().stream()
- .filter(propertyDefinition -> propertyDefinition.getName().equals(SOFTWARE_VERSION_PROPERTY_NAME))
+ return resource.getProperties().stream().filter(propertyDefinition -> propertyDefinition.getName().equals(SOFTWARE_VERSION_PROPERTY_NAME))
.findFirst();
}
@@ -135,7 +127,6 @@ public class SoftwareInformationBusinessLogic {
if (!softwareInformation.isPresent()) {
return false;
}
-
csarInfo.getCsar().remove(softwareInformation.get());
return true;
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/TogglingBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/TogglingBusinessLogic.java
index 538f565917..252c58d3e7 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/TogglingBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/TogglingBusinessLogic.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl;
import java.util.Arrays;
@@ -42,17 +41,15 @@ import org.togglz.core.util.NamedFeature;
public class TogglingBusinessLogic extends BaseBusinessLogic {
@Autowired
- public TogglingBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
- IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation,
- InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
- ArtifactsOperations artifactToscaOperation) {
- super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation,
- interfaceLifecycleTypeOperation, artifactToscaOperation);
+ public TogglingBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+ IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
+ InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
+ super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+ artifactToscaOperation);
}
public Map<String, Boolean> getAllFeatureStates() {
- return Arrays.stream(ToggleableFeature.values()).collect(Collectors.toMap(Enum::name,
- ToggleableFeature::isActive));
+ return Arrays.stream(ToggleableFeature.values()).collect(Collectors.toMap(Enum::name, ToggleableFeature::isActive));
}
public boolean getFeatureState(String featureName) {
@@ -60,8 +57,7 @@ public class TogglingBusinessLogic extends BaseBusinessLogic {
}
public void setAllFeatures(boolean state) {
- Arrays.asList(ToggleableFeature.values())
- .forEach(toggleableFeature -> updateFeatureState(toggleableFeature.name(), state));
+ Arrays.asList(ToggleableFeature.values()).forEach(toggleableFeature -> updateFeatureState(toggleableFeature.name(), state));
}
public void updateFeatureState(String featureName, boolean state) {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafPermission.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafPermission.java
index 9c952415a3..4dc8c98e49 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafPermission.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafPermission.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.aaf;
import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
@@ -25,39 +24,35 @@ import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
public enum AafPermission {
-
- READ(PermNames.READ_VALUE),
- WRITE(PermNames.WRITE_VALUE),
- DELETE(PermNames.DELETE_VALUE),
- INTERNAL_ALL(PermNames.INTERNAL_ALL_VALUE);
-
+ READ(PermNames.READ_VALUE), WRITE(PermNames.WRITE_VALUE), DELETE(PermNames.DELETE_VALUE), INTERNAL_ALL(PermNames.INTERNAL_ALL_VALUE);
private String permission;
private String permissionSuffix;
AafPermission(String permissionSuffix) {
this.permissionSuffix = permissionSuffix;
- this.permission = String.format("%s.%s",
- ConfigurationManager.getConfigurationManager().getConfiguration().getAafNamespace(),
- permissionSuffix);
- }
-
- public String getFullPermission() {
- return permission;
+ this.permission = String
+ .format("%s.%s", ConfigurationManager.getConfigurationManager().getConfiguration().getAafNamespace(), permissionSuffix);
}
public static AafPermission getEnumByString(String perm) {
for (AafPermission e : AafPermission.values()) {
- if (perm.equals(e.getPermissionSuffix()))
+ if (perm.equals(e.getPermissionSuffix())) {
return e;
+ }
}
throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY, perm);
}
+ public String getFullPermission() {
+ return permission;
+ }
+
public String getPermissionSuffix() {
return this.permissionSuffix;
}
public static class PermNames {
+
public static final String READ_VALUE = "endpoint.api.access|*|read";
public static final String WRITE_VALUE = "endpoint.api.access|*|write";
public static final String DELETE_VALUE = "endpoint.api.access|*|delete";
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafRoles.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafRoles.java
index 34ca5965a1..95cebcacdc 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafRoles.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafRoles.java
@@ -17,24 +17,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.aaf;
import org.openecomp.sdc.be.config.ConfigurationManager;
public enum AafRoles {
+ READ_ONLY("app.readonly"), ALL("app.all");
+ private String role;
- READ_ONLY("app.readonly"),
- ALL("app.all");
-
- private String role;
-
- AafRoles(String roleSuffix) {
- this.role = ConfigurationManager.getConfigurationManager().getConfiguration().getAafNamespace() + "." + roleSuffix;
- }
-
- public String getRole() {
- return role;
- }
+ AafRoles(String roleSuffix) {
+ this.role = ConfigurationManager.getConfigurationManager().getConfiguration().getAafNamespace() + "." + roleSuffix;
+ }
+ public String getRole() {
+ return role;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/PermissionAllowed.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/PermissionAllowed.java
index a963e5e533..782e2ea8c2 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/PermissionAllowed.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/PermissionAllowed.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.aaf;
import java.lang.annotation.ElementType;
@@ -28,5 +27,6 @@ import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface PermissionAllowed {
+
String[] value();
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/RoleAuthorizationHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/RoleAuthorizationHandler.java
index b963cf6135..bc66a8c67e 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/RoleAuthorizationHandler.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/RoleAuthorizationHandler.java
@@ -17,10 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.aaf;
-
+import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@@ -31,19 +30,15 @@ import org.openecomp.sdc.be.servlets.BeGenericServlet;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.ThreadLocalsHolder;
-import javax.servlet.http.HttpServletRequest;
-
// aop id defined via application-context.xml. the annotations are only for test purposes
@Aspect
public class RoleAuthorizationHandler {
private static final Logger log = Logger.getLogger(RoleAuthorizationHandler.class);
-
private final ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager();
@Before("@annotation(permissions)")
public void authorizeRole(JoinPoint joinPoint, PermissionAllowed permissions) {
-
if (isPermissionAuthenticationNeeded()) {
String methodName = joinPoint.getSignature().toShortString();
HttpServletRequest request = ((BeGenericServlet) joinPoint.getThis()).getServletRequest();
@@ -58,13 +53,12 @@ public class RoleAuthorizationHandler {
logAuth(methodName, perms, false, false);
throw new ByActionStatusComponentException(ActionStatus.AUTH_FAILED);
}
-
}
private void logAuth(String methodName, String[] perms, boolean beforeAuth, Boolean success) {
- if (beforeAuth)
+ if (beforeAuth) {
log.trace("#{} - authorizing before invoking endpoint {}", methodName);
- else {
+ } else {
String status = success ? "SUCCESS" : "FAILED";
log.trace("#{} - authorizing before invoking endpoint {}, Status: {}", methodName, status);
}
@@ -77,6 +71,8 @@ public class RoleAuthorizationHandler {
private boolean isPermissionAuthenticationNeeded() {
if (configurationManager.getConfiguration().getAafAuthNeeded() && ThreadLocalsHolder.isExternalRequest()) {
return true;
- } else return false;
+ } else {
+ return false;
+ }
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/ArtifactOperationInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/ArtifactOperationInfo.java
index 84316dbdff..be529fe113 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/ArtifactOperationInfo.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/ArtifactOperationInfo.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.artifact;
import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE;
@@ -34,8 +33,7 @@ public final class ArtifactOperationInfo {
private final boolean isExternalApi;
private final boolean ignoreLifecycleState;
- public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState,
- ArtifactOperationEnum artifactOperationEnum) {
+ public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
this.artifactOperationEnum = artifactOperationEnum;
this.isExternalApi = isExternalApi;
this.ignoreLifecycleState = ignoreLifecycleState;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/ArtifactTypeToPayloadTypeSelector.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/ArtifactTypeToPayloadTypeSelector.java
index 3e3b9e260f..3362686ef3 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/ArtifactTypeToPayloadTypeSelector.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/ArtifactTypeToPayloadTypeSelector.java
@@ -19,15 +19,8 @@
* * ============LICENSE_END=========================================================
*
*/
-
package org.openecomp.sdc.be.components.impl.artifact;
-import org.openecomp.sdc.common.api.ArtifactTypeEnum;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
-
import static org.openecomp.sdc.be.components.impl.artifact.PayloadTypeEnum.HEAT_YAML;
import static org.openecomp.sdc.be.components.impl.artifact.PayloadTypeEnum.NOT_DEFINED;
import static org.openecomp.sdc.common.api.ArtifactTypeEnum.DCAE_INVENTORY_JSON;
@@ -47,6 +40,11 @@ import static org.openecomp.sdc.common.api.ArtifactTypeEnum.VF_LICENSE;
import static org.openecomp.sdc.common.api.ArtifactTypeEnum.VNF_CATALOG;
import static org.openecomp.sdc.common.api.ArtifactTypeEnum.YANG_XML;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import org.openecomp.sdc.common.api.ArtifactTypeEnum;
+
public class ArtifactTypeToPayloadTypeSelector {
private static final Map<ArtifactTypeWithExtension, PayloadTypeEnum> artifactTypeWithExtension2PayloadType = new HashMap<>();
@@ -66,17 +64,14 @@ public class ArtifactTypeToPayloadTypeSelector {
artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(DCAE_INVENTORY_JSON, JSON), PayloadTypeEnum.JSON);
artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(DCAE_INVENTORY_JSON, YML), PayloadTypeEnum.YAML);
artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(DCAE_INVENTORY_JSON, YAML), PayloadTypeEnum.YAML);
-
artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(DCAE_INVENTORY_TOSCA, XML), PayloadTypeEnum.XML);
artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(DCAE_INVENTORY_TOSCA, JSON), PayloadTypeEnum.JSON);
artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(DCAE_INVENTORY_TOSCA, YML), PayloadTypeEnum.YAML);
artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(DCAE_INVENTORY_TOSCA, YAML), PayloadTypeEnum.YAML);
-
artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(VES_EVENTS, XML), PayloadTypeEnum.XML);
artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(VES_EVENTS, JSON), PayloadTypeEnum.JSON);
artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(VES_EVENTS, YML), PayloadTypeEnum.YAML);
artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(VES_EVENTS, YAML), PayloadTypeEnum.YAML);
-
artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(LIFECYCLE_OPERATIONS, XML), PayloadTypeEnum.XML);
artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(LIFECYCLE_OPERATIONS, JSON), PayloadTypeEnum.JSON);
artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(LIFECYCLE_OPERATIONS, YML), PayloadTypeEnum.YAML);
@@ -88,7 +83,6 @@ public class ArtifactTypeToPayloadTypeSelector {
artifactType2PayloadType.put(HEAT_VOL.getType().toLowerCase(), HEAT_YAML);
artifactType2PayloadType.put(HEAT_NET.getType().toLowerCase(), HEAT_YAML);
artifactType2PayloadType.put(HEAT_ENV.getType().toLowerCase(), PayloadTypeEnum.HEAT_ENV);
-
artifactType2PayloadType.put(YANG_XML.getType().toLowerCase(), PayloadTypeEnum.XML);
artifactType2PayloadType.put(VNF_CATALOG.getType().toLowerCase(), PayloadTypeEnum.XML);
artifactType2PayloadType.put(VF_LICENSE.getType().toLowerCase(), PayloadTypeEnum.XML);
@@ -114,6 +108,7 @@ public class ArtifactTypeToPayloadTypeSelector {
}
private class ArtifactTypeWithExtension {
+
private String artifactType;
private String fileExtension;
@@ -136,9 +131,8 @@ public class ArtifactTypeToPayloadTypeSelector {
return false;
}
ArtifactTypeWithExtension otherArtifactTypeWithExtension = (ArtifactTypeWithExtension) other;
-
- return isArtifactTypeEqual(otherArtifactTypeWithExtension.getArtifactType()) &&
- isFileExtensionEqual(otherArtifactTypeWithExtension.getFileExtension());
+ return isArtifactTypeEqual(otherArtifactTypeWithExtension.getArtifactType()) && isFileExtensionEqual(
+ otherArtifactTypeWithExtension.getFileExtension());
}
@Override
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/PayloadTypeEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/PayloadTypeEnum.java
index 4a71d4bc86..b94b565d79 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/PayloadTypeEnum.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/PayloadTypeEnum.java
@@ -19,13 +19,17 @@
* * ============LICENSE_END=========================================================
* * Modifications copyright (c) 2020 Nokia
*/
-
package org.openecomp.sdc.be.components.impl.artifact;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import fj.data.Either;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import javax.xml.XMLConstants;
+import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
+import javax.xml.parsers.SAXParserFactory;
import org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.common.log.wrappers.Logger;
@@ -36,12 +40,6 @@ import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;
-import javax.xml.XMLConstants;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParserFactory;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-
public enum PayloadTypeEnum {
HEAT_YAML {
@Override
@@ -50,9 +48,7 @@ public enum PayloadTypeEnum {
if (isNotValidYaml(payload, yamlToObjectConverter)) {
return Either.right(ActionStatus.INVALID_YAML);
}
-
- DeploymentArtifactHeatConfiguration heatConfiguration =
- yamlToObjectConverter.convert(payload, DeploymentArtifactHeatConfiguration.class);
+ DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(payload, DeploymentArtifactHeatConfiguration.class);
if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) {
log.debug("HEAT doesn't contain required \"heat_template_version\" section.");
return Either.right(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT);
@@ -68,8 +64,7 @@ public enum PayloadTypeEnum {
private boolean isNotValidYaml(byte[] payload, YamlToObjectConverter yamlToObjectConverter) {
return !yamlToObjectConverter.isValidYaml(payload);
}
- },
- HEAT_ENV {
+ }, HEAT_ENV {
@Override
public Either<Boolean, ActionStatus> isValid(byte[] payload) {
return isValidYaml(payload);
@@ -79,8 +74,7 @@ public enum PayloadTypeEnum {
public boolean isHeatRelated() {
return true;
}
- },
- XML {
+ }, XML {
@Override
public Either<Boolean, ActionStatus> isValid(byte[] payload) {
try {
@@ -103,11 +97,10 @@ public enum PayloadTypeEnum {
reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
} catch (SAXNotRecognizedException exception) {
log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false",
- exception.getMessage(), exception);
+ exception.getMessage(), exception);
}
}
- },
- JSON {
+ }, JSON {
@Override
public Either<Boolean, ActionStatus> isValid(byte[] payload) {
try {
@@ -118,29 +111,20 @@ public enum PayloadTypeEnum {
}
return Either.left(true);
}
- },
- YAML {
+ }, YAML {
@Override
public Either<Boolean, ActionStatus> isValid(byte[] payload) {
return isValidYaml(payload);
}
- },
- NOT_DEFINED {
+ }, NOT_DEFINED {
@Override
public Either<Boolean, ActionStatus> isValid(byte[] payload) {
return Either.left(true);
}
};
-
private static final Logger log = Logger.getLogger(PayloadTypeEnum.class);
private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
- public abstract Either<Boolean, ActionStatus> isValid(byte[] payload);
-
- public boolean isHeatRelated() {
- return false;
- }
-
private static Either<Boolean, ActionStatus> isValidYaml(byte[] payload) {
YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
if (yamlToObjectConverter.isValidYaml(payload)) {
@@ -150,4 +134,9 @@ public enum PayloadTypeEnum {
return Either.right(ActionStatus.INVALID_YAML);
}
+ public abstract Either<Boolean, ActionStatus> isValid(byte[] payload);
+
+ public boolean isHeatRelated() {
+ return false;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/BusinessLogicException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/BusinessLogicException.java
index acf80cb5d0..845487b1ab 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/BusinessLogicException.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/BusinessLogicException.java
@@ -16,7 +16,6 @@
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.exceptions;
import lombok.AllArgsConstructor;
@@ -28,5 +27,4 @@ public class BusinessLogicException extends Exception {
@Getter
private final ResponseFormat responseFormat;
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByActionStatusComponentException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByActionStatusComponentException.java
index 788d63819e..e973fe4bf3 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByActionStatusComponentException.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByActionStatusComponentException.java
@@ -19,12 +19,11 @@
*/
package org.openecomp.sdc.be.components.impl.exceptions;
+import java.util.Arrays;
import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.exception.ResponseFormat;
-import java.util.Arrays;
-
public class ByActionStatusComponentException extends ComponentException {
private final ActionStatus actionStatus;
@@ -51,10 +50,6 @@ public class ByActionStatusComponentException extends ComponentException {
@Override
public String toString() {
- return "ComponentException{" +
- "actionStatus=" + actionStatus +
- ", params=" + Arrays.toString(params) +
- '}';
+ return "ComponentException{" + "actionStatus=" + actionStatus + ", params=" + Arrays.toString(params) + '}';
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByResponseFormatComponentException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByResponseFormatComponentException.java
index 85fe3ec58a..3577b7adef 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByResponseFormatComponentException.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByResponseFormatComponentException.java
@@ -39,7 +39,7 @@ public class ByResponseFormatComponentException extends ComponentException {
return params.clone();
}
- public ActionStatus getActionStatus(){
+ public ActionStatus getActionStatus() {
return actionStatus;
}
@@ -50,9 +50,6 @@ public class ByResponseFormatComponentException extends ComponentException {
@Override
public String toString() {
- return "ComponentException{" +
- "responseFormat=" + responseFormat +
- '}';
+ return "ComponentException{" + "responseFormat=" + responseFormat + '}';
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java
index 1d9809806c..351d279875 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java
@@ -17,30 +17,22 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.exceptions;
+import javax.annotation.Nullable;
import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.exception.ResponseFormat;
-import javax.annotation.Nullable;
-
public class ComponentException extends RuntimeException {
/**
* This class will be initialized either by action status and params or by ResponseFormat
*/
-
private final transient ResponseFormat responseFormat;
private final ActionStatus actionStatus;
private final String[] params;
-
- public Resource getResource() {
- return resource;
- }
-
private final Resource resource;
public ComponentException(ResponseFormat responseFormat) {
@@ -62,6 +54,10 @@ public class ComponentException extends RuntimeException {
this.resource = resource;
}
+ public Resource getResource() {
+ return resource;
+ }
+
@Nullable
public ResponseFormat getResponseFormat() {
return responseFormat;
@@ -74,6 +70,4 @@ public class ComponentException extends RuntimeException {
public String[] getParams() {
return params.clone();
}
-
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/SdcResourceNotFoundException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/SdcResourceNotFoundException.java
index 441e68bb9d..594e3e4ea3 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/SdcResourceNotFoundException.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/SdcResourceNotFoundException.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,16 +17,16 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.exceptions;
public class SdcResourceNotFoundException extends RuntimeException {
- private static final long serialVersionUID = 4431147390120646573L;
+ private static final long serialVersionUID = 4431147390120646573L;
- public SdcResourceNotFoundException(){}
+ public SdcResourceNotFoundException() {
+ }
- public SdcResourceNotFoundException(String message){
- super(message);
- }
+ public SdcResourceNotFoundException(String message) {
+ super(message);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java
index 840fd03e0d..a00f44ce39 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,10 +17,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.generic;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
@@ -36,15 +38,10 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.stream.Collectors;
-
@org.springframework.stereotype.Component
public class GenericTypeBusinessLogic {
private final static Logger log = Logger.getLogger(GenericTypeBusinessLogic.class);
-
private final ComponentsUtils componentsUtils;
private final ToscaOperationFacade toscaOperationFacade;
@@ -58,58 +55,54 @@ public class GenericTypeBusinessLogic {
* @param component the component of which to fetch its generic type
* @return the generic node type which corresponds to the given component
*/
- public Either<Resource, ResponseFormat> fetchDerivedFromGenericType(Component component){
+ public Either<Resource, ResponseFormat> fetchDerivedFromGenericType(Component component) {
String genericTypeToscaName = getGenericTypeToscaName(component);
log.debug("Fetching generic tosca name {}", genericTypeToscaName);
- if(null == genericTypeToscaName) {
+ if (null == genericTypeToscaName) {
log.debug("Failed to fetch certified generic node type for component {}", component.getName());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
-
- Either<Resource, StorageOperationStatus> findLatestGeneric = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(genericTypeToscaName);
- if(findLatestGeneric.isRight()){
+ Either<Resource, StorageOperationStatus> findLatestGeneric = toscaOperationFacade
+ .getLatestCertifiedNodeTypeByToscaResourceName(genericTypeToscaName);
+ if (findLatestGeneric.isRight()) {
log.debug("Failed to fetch certified node type by tosca resource name {}", genericTypeToscaName);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERIC_TYPE_NOT_FOUND, component.assetType(), genericTypeToscaName));
}
-
Resource genericTypeResource = findLatestGeneric.left().value();
return Either.left(genericTypeResource);
}
/**
- *
* @param genericType the generic node type
* @return the generic type properties as inputs
*/
public List<InputDefinition> generateInputsFromGenericTypeProperties(Resource genericType) {
List<PropertyDefinition> genericTypeProps = genericType.getProperties();
- if(null != genericTypeProps) {
+ if (null != genericTypeProps) {
return convertGenericTypePropertiesToInputsDefintion(genericTypeProps, genericType.getUniqueId());
}
return new ArrayList<>();
}
public List<InputDefinition> convertGenericTypePropertiesToInputsDefintion(List<PropertyDefinition> genericTypeProps, String genericUniqueId) {
- return genericTypeProps.stream()
- .map(p -> setInputDefinitionFromProp(p, genericUniqueId))
- .collect(Collectors.toList());
+ return genericTypeProps.stream().map(p -> setInputDefinitionFromProp(p, genericUniqueId)).collect(Collectors.toList());
}
- private InputDefinition setInputDefinitionFromProp(PropertyDefinition prop, String genericUniqueId){
+ private InputDefinition setInputDefinitionFromProp(PropertyDefinition prop, String genericUniqueId) {
InputDefinition input = new InputDefinition(prop);
input.setOwnerId(genericUniqueId);
return input;
}
private <T extends Component> String getGenericTypeToscaName(T component) {
- if(component.getDerivedFromGenericType() != null && !component.getDerivedFromGenericType().isEmpty()){
+ if (component.getDerivedFromGenericType() != null && !component.getDerivedFromGenericType().isEmpty()) {
return component.getDerivedFromGenericType();
}
- return isCvfcHasDerivedFrom(component) ? ((Resource)component).getDerivedFrom().get(0) : component.fetchGenericTypeToscaNameFromConfig();
+ return isCvfcHasDerivedFrom(component) ? ((Resource) component).getDerivedFrom().get(0) : component.fetchGenericTypeToscaNameFromConfig();
}
private <T extends Component> boolean isCvfcHasDerivedFrom(T component) {
- return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource)component).getResourceType() == ResourceTypeEnum.CVFC && CollectionUtils.isNotEmpty(((Resource)component).getDerivedFrom());
+ return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC
+ && CollectionUtils.isNotEmpty(((Resource) component).getDerivedFrom());
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupMembersUpdater.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupMembersUpdater.java
index b4df58b46d..74e16a1876 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupMembersUpdater.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupMembersUpdater.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,17 +17,15 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.group;
-import org.apache.commons.collections.MapUtils;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.springframework.stereotype.Component;
+import static org.apache.commons.collections.MapUtils.isEmpty;
import java.util.List;
import java.util.Map;
-
-import static org.apache.commons.collections.MapUtils.isEmpty;
+import org.apache.commons.collections.MapUtils;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.springframework.stereotype.Component;
/**
* A Helper class which handles altering the members state of a group
@@ -69,8 +67,4 @@ public class GroupMembersUpdater {
}
return invertedMap.get(memberToFind).toString();
}
-
-
-
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupVersionUpdater.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupVersionUpdater.java
index 8e9ba7a88b..29a2d7c88d 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupVersionUpdater.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupVersionUpdater.java
@@ -17,10 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.group;
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+
import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.openecomp.sdc.be.components.impl.version.OnChangeVersionCommand;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -35,63 +39,27 @@ import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.utils.GroupUtils;
import org.openecomp.sdc.common.log.wrappers.Logger;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Consumer;
-
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-
-
/**
* A Helper class which handles altering the version of a group
*/
@org.springframework.stereotype.Component
public class GroupVersionUpdater implements OnChangeVersionCommand {
-
+
private static final Logger log = Logger.getLogger(GroupVersionUpdater.class);
private final GroupsOperation groupsOperation;
private final ComponentsUtils componentsUtils;
-
public GroupVersionUpdater(GroupsOperation groupsOperation, ComponentsUtils componentsUtils) {
this.groupsOperation = groupsOperation;
this.componentsUtils = componentsUtils;
-
- }
-
-
- @Override
- public ActionStatus onChangeVersion(Component container) {
- log.debug("#onChangeVersion - replacing all group members for component instance");
- Consumer<List<GroupDefinition>> replaceGroupMemberTask = (groups) -> increaseVersion(groups, container);
- return updateGroupsVersion(container, replaceGroupMemberTask);
- }
-
- public void increaseVersion(List<GroupDefinition> groups, Component container) {
- groups.forEach(group -> increaseMajorVersion(group, container));
- }
-
-
- private void increaseMajorVersion(GroupDefinition group, Component container) {
- String version = group.getVersion();
-
- String newVersion = GroupUtils.updateVersion(PromoteVersionEnum.MAJOR, group.getVersion());
-
- if(!version.equals(newVersion) ){
- if(isGenerateGroupUUID(group, container)) {
- String groupUUID = UniqueIdBuilder.generateUUID();
- group.setGroupUUID(groupUUID);
- }
- group.setVersion(String.valueOf(newVersion));
- }
}
static <T> List<T> emptyIfNull(final List<T> list) {
- return (list == null? Collections.emptyList() : list);
+ return (list == null ? Collections.emptyList() : list);
}
static <T, U> Map<T, U> emptyIfNull(final Map<T, U> list) {
- return (list == null? Collections.emptyMap() : list);
+ return (list == null ? Collections.emptyMap() : list);
}
static boolean isGenerateGroupUUID(GroupDefinition group, Component container) {
@@ -100,16 +68,11 @@ public class GroupVersionUpdater implements OnChangeVersionCommand {
} else {
List<String> artifactsUuid = emptyIfNull(group.getArtifactsUuid());
Map<String, ArtifactDefinition> deploymentArtifacts = emptyIfNull(container.getDeploymentArtifacts());
- List<String> heatArtifactUniqueIDs = emptyIfNull(group.getArtifacts()).stream().filter(a -> !a.endsWith("env")).collect(
- Collectors.toList());
-
+ List<String> heatArtifactUniqueIDs = emptyIfNull(group.getArtifacts()).stream().filter(a -> !a.endsWith("env"))
+ .collect(Collectors.toList());
for (String heatArtifactUniqueID : heatArtifactUniqueIDs) {
- ArtifactDefinition artifactDefinition = deploymentArtifacts
- .get(heatArtifactUniqueID.split("\\.", -1)[1]);
-
- if ((artifactDefinition == null
- || artifactDefinition.isEmpty())
- || !artifactsUuid.contains(artifactDefinition.getArtifactUUID())) {
+ ArtifactDefinition artifactDefinition = deploymentArtifacts.get(heatArtifactUniqueID.split("\\.", -1)[1]);
+ if ((artifactDefinition == null || artifactDefinition.isEmpty()) || !artifactsUuid.contains(artifactDefinition.getArtifactUUID())) {
return true;
}
}
@@ -117,6 +80,29 @@ public class GroupVersionUpdater implements OnChangeVersionCommand {
}
}
+ @Override
+ public ActionStatus onChangeVersion(Component container) {
+ log.debug("#onChangeVersion - replacing all group members for component instance");
+ Consumer<List<GroupDefinition>> replaceGroupMemberTask = (groups) -> increaseVersion(groups, container);
+ return updateGroupsVersion(container, replaceGroupMemberTask);
+ }
+
+ public void increaseVersion(List<GroupDefinition> groups, Component container) {
+ groups.forEach(group -> increaseMajorVersion(group, container));
+ }
+
+ private void increaseMajorVersion(GroupDefinition group, Component container) {
+ String version = group.getVersion();
+ String newVersion = GroupUtils.updateVersion(PromoteVersionEnum.MAJOR, group.getVersion());
+ if (!version.equals(newVersion)) {
+ if (isGenerateGroupUUID(group, container)) {
+ String groupUUID = UniqueIdBuilder.generateUUID();
+ group.setGroupUUID(groupUUID);
+ }
+ group.setVersion(String.valueOf(newVersion));
+ }
+ }
+
private ActionStatus updateGroupsVersion(Component groupsContainer, Consumer<List<GroupDefinition>> updateGroupVersion) {
List<GroupDefinition> groups = groupsContainer.getGroups();
if (isEmpty(groups)) {
@@ -124,14 +110,10 @@ public class GroupVersionUpdater implements OnChangeVersionCommand {
}
updateGroupVersion.accept(groups);
return updateGroups(groupsContainer.getUniqueId(), groups);
- }
+ }
-
private ActionStatus updateGroups(String componentId, List<GroupDefinition> groupsToUpdate) {
log.debug("#updateGroups - updating {} groups for container {}", groupsToUpdate.size(), componentId);
return componentsUtils.convertFromStorageResponse(groupsOperation.updateGroupsOnComponent(componentId, groupsToUpdate));
-
}
-
}
-
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/ComponentInstanceChangeOperationOrchestrator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/ComponentInstanceChangeOperationOrchestrator.java
index e631e9f728..fa1211d8ab 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/ComponentInstanceChangeOperationOrchestrator.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/ComponentInstanceChangeOperationOrchestrator.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,18 +17,16 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.instance;
+import java.util.Iterator;
+import java.util.List;
+import java.util.function.Function;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.common.log.wrappers.Logger;
-import java.util.Iterator;
-import java.util.List;
-import java.util.function.Function;
-
@org.springframework.stereotype.Component
public class ComponentInstanceChangeOperationOrchestrator {
@@ -40,24 +38,27 @@ public class ComponentInstanceChangeOperationOrchestrator {
}
public ActionStatus doPostChangeVersionOperations(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) {
- log.debug("#doPostChangeVersionOperations - starting post change version operations for component {}. from instance {} to instance {}", container.getUniqueId(), prevVersion.getUniqueId(), newVersion.getUniqueId());
- Function<OnComponentInstanceChangeOperation, ActionStatus> instanceChangeTaskRunner = operation -> operation.onChangeVersion(container, prevVersion, newVersion);
+ log.debug("#doPostChangeVersionOperations - starting post change version operations for component {}. from instance {} to instance {}",
+ container.getUniqueId(), prevVersion.getUniqueId(), newVersion.getUniqueId());
+ Function<OnComponentInstanceChangeOperation, ActionStatus> instanceChangeTaskRunner = operation -> operation
+ .onChangeVersion(container, prevVersion, newVersion);
return doOnChangeInstanceOperations(instanceChangeTaskRunner);
}
public ActionStatus doOnDeleteInstanceOperations(Component container, String deletedInstanceId) {
- log.debug("#doPostChangeVersionOperations - starting on delete instance operations for component {} and instance {}.", container.getUniqueId(), deletedInstanceId);
- Function<OnComponentInstanceChangeOperation, ActionStatus> instanceChangeTaskRunner = operation -> operation.onDelete(container, deletedInstanceId);
+ log.debug("#doPostChangeVersionOperations - starting on delete instance operations for component {} and instance {}.",
+ container.getUniqueId(), deletedInstanceId);
+ Function<OnComponentInstanceChangeOperation, ActionStatus> instanceChangeTaskRunner = operation -> operation
+ .onDelete(container, deletedInstanceId);
return doOnChangeInstanceOperations(instanceChangeTaskRunner);
}
private ActionStatus doOnChangeInstanceOperations(Function<OnComponentInstanceChangeOperation, ActionStatus> instanceChangeTaskRunner) {
ActionStatus onDeleteInstanceResult = ActionStatus.OK;
Iterator<OnComponentInstanceChangeOperation> onDeleteInstIter = onInstanceChangeOperations.iterator();
- while(onDeleteInstIter.hasNext() && onDeleteInstanceResult == ActionStatus.OK) {
+ while (onDeleteInstIter.hasNext() && onDeleteInstanceResult == ActionStatus.OK) {
onDeleteInstanceResult = instanceChangeTaskRunner.apply(onDeleteInstIter.next());
}
return onDeleteInstanceResult;
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperation.java
index 656dd2e6e3..7a8f1201de 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperation.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,9 +17,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.instance;
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+
+import java.util.List;
+import java.util.function.Consumer;
import org.openecomp.sdc.be.components.impl.group.GroupMembersUpdater;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum;
@@ -30,10 +33,6 @@ import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation;
import org.openecomp.sdc.common.log.wrappers.Logger;
-import java.util.List;
-import java.util.function.Consumer;
-
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
@org.springframework.stereotype.Component
public class GroupMembersUpdateOperation implements OnComponentInstanceChangeOperation {
@@ -50,8 +49,10 @@ public class GroupMembersUpdateOperation implements OnComponentInstanceChangeOpe
@Override
public ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) {
- log.debug("#onChangeVersion - replacing all group members for component instance {} with new component instance on component", prevVersion.getUniqueId(), newVersion.getUniqueId(), container.getUniqueId());
- Consumer<List<GroupDefinition>> replaceGroupMemberTask = (groups) -> groupMembersUpdater.replaceMember(groups, prevVersion.getUniqueId(), newVersion.getUniqueId());
+ log.debug("#onChangeVersion - replacing all group members for component instance {} with new component instance on component",
+ prevVersion.getUniqueId(), newVersion.getUniqueId(), container.getUniqueId());
+ Consumer<List<GroupDefinition>> replaceGroupMemberTask = (groups) -> groupMembersUpdater
+ .replaceMember(groups, prevVersion.getUniqueId(), newVersion.getUniqueId());
return doUpdateGroupMembers(container, prevVersion.getUniqueId(), replaceGroupMemberTask);
}
@@ -75,9 +76,6 @@ public class GroupMembersUpdateOperation implements OnComponentInstanceChangeOpe
private ActionStatus updateGroups(Component container, List<GroupDefinition> groupsToUpdate) {
log.debug("#updateGroups - updating {} groups for container {}", groupsToUpdate.size(), container.getUniqueId());
return groupsOperation.updateGroups(container, groupsToUpdate, PromoteVersionEnum.MINOR)
- .either(groupsUpdated -> ActionStatus.OK,
- err -> componentsUtils.convertFromStorageResponse(err, container.getComponentType()));
+ .either(groupsUpdated -> ActionStatus.OK, err -> componentsUtils.convertFromStorageResponse(err, container.getComponentType()));
}
-
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnChangeVersionOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnChangeVersionOperation.java
index 173fb3fdbd..5093a153cb 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnChangeVersionOperation.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnChangeVersionOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,22 +17,22 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.instance;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
+
@FunctionalInterface
public interface OnChangeVersionOperation {
/**
* A side effect operation to execute when a component instance version was changed from {@code prevVersion} to {@code newVersion}
- * @param container the container which contains the instance which is version was changed
+ *
+ * @param container the container which contains the instance which is version was changed
* @param prevVersion the previous version of the component instance.
- * @param newVersion the new version of the component instance.
+ * @param newVersion the new version of the component instance.
* @return the status of the operation
*/
ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion);
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnComponentInstanceChangeOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnComponentInstanceChangeOperation.java
index a01421eadb..f27cf5b031 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnComponentInstanceChangeOperation.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnComponentInstanceChangeOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.instance;
import org.openecomp.sdc.be.components.impl.OnDeleteEntityOperation;
@@ -26,4 +25,5 @@ import org.openecomp.sdc.be.components.impl.OnDeleteEntityOperation;
* An interface which groups all operations to be executed when an action on a component instance has occurred
*/
public interface OnComponentInstanceChangeOperation extends OnChangeVersionOperation, OnDeleteEntityOperation {
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/PolicyTargetsUpdateOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/PolicyTargetsUpdateOperation.java
index 863be79d38..7ef9fc77fb 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/PolicyTargetsUpdateOperation.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/PolicyTargetsUpdateOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.instance;
import org.openecomp.sdc.be.components.impl.policy.PolicyTargetsUpdateHandler;
@@ -39,8 +38,10 @@ public class PolicyTargetsUpdateOperation implements OnComponentInstanceChangeOp
@Override
public ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) {
- log.debug("#onChangeVersion - replacing all policy targets referencing component instance {} with component instance {}", prevVersion.getUniqueId(), newVersion.getUniqueId());
- return policyTargetsUpdateHandler.replacePoliciesTargets(container, prevVersion.getUniqueId(), newVersion.getUniqueId(), PolicyTargetType.COMPONENT_INSTANCES);
+ log.debug("#onChangeVersion - replacing all policy targets referencing component instance {} with component instance {}",
+ prevVersion.getUniqueId(), newVersion.getUniqueId());
+ return policyTargetsUpdateHandler
+ .replacePoliciesTargets(container, prevVersion.getUniqueId(), newVersion.getUniqueId(), PolicyTargetType.COMPONENT_INSTANCES);
}
@Override
@@ -48,6 +49,4 @@ public class PolicyTargetsUpdateOperation implements OnComponentInstanceChangeOp
log.debug("#onDelete - removing all component {} policy targets referencing component instance {}", container.getUniqueId(), deletedEntityId);
return policyTargetsUpdateHandler.removePoliciesTargets(container, deletedEntityId, PolicyTargetType.COMPONENT_INSTANCES);
}
-
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/ComponentLockAspect.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/ComponentLockAspect.java
index 892ea8cfd4..cfd0675f58 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/ComponentLockAspect.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/ComponentLockAspect.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.lock;
import org.aspectj.lang.ProceedingJoinPoint;
@@ -46,13 +45,10 @@ public class ComponentLockAspect {
componentLocker.lock(componentId, componentType);
log.trace("#{} - after locking component {} of type {}", methodName, componentId, componentType);
return proceedingJoinPoint.proceed();
- }
- finally {
+ } finally {
log.trace("#{} - before unlocking component {} of type {}", methodName, componentId, componentType);
componentLocker.unlock(componentId, componentType);
log.trace("#{} - after unlocking component {} of type {}", methodName, componentId, componentType);
}
}
-
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/LockingTransactional.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/LockingTransactional.java
index 44e49eb039..9a0d2517d8 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/LockingTransactional.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/LockingTransactional.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,16 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.lock;
-import org.springframework.transaction.annotation.Transactional;
-
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
+import org.springframework.transaction.annotation.Transactional;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/model/ToscaTypeImportData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/model/ToscaTypeImportData.java
index 00f5fd8ab1..a5416dd73d 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/model/ToscaTypeImportData.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/model/ToscaTypeImportData.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,12 +17,10 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.model;
-import org.openecomp.sdc.be.model.normatives.ToscaTypeMetadata;
-
import java.util.Map;
+import org.openecomp.sdc.be.model.normatives.ToscaTypeMetadata;
public class ToscaTypeImportData {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandler.java
index 3b3dab34a6..df2ea21857 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandler.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandler.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,9 +17,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.policy;
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+
+import java.util.List;
+import java.util.function.Consumer;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
import org.openecomp.sdc.be.impl.ComponentsUtils;
@@ -29,11 +32,6 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.common.log.wrappers.Logger;
-import java.util.List;
-import java.util.function.Consumer;
-
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-
@org.springframework.stereotype.Component
public class PolicyTargetsUpdateHandler {
@@ -42,7 +40,8 @@ public class PolicyTargetsUpdateHandler {
private final ComponentsUtils componentsUtils;
private final PolicyTargetsUpdater policyTargetsUpdater;
- public PolicyTargetsUpdateHandler(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, PolicyTargetsUpdater policyTargetsUpdater) {
+ public PolicyTargetsUpdateHandler(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils,
+ PolicyTargetsUpdater policyTargetsUpdater) {
this.toscaOperationFacade = toscaOperationFacade;
this.componentsUtils = componentsUtils;
this.policyTargetsUpdater = policyTargetsUpdater;
@@ -56,11 +55,13 @@ public class PolicyTargetsUpdateHandler {
public ActionStatus replacePoliciesTargets(Component container, String prevTargetId, String newTargetId, PolicyTargetType targetType) {
log.debug("#replacePoliciesTargets - replacing all policy targets referencing target {} with target {}", prevTargetId, newTargetId);
- Consumer<List<PolicyDefinition>> replaceTarget = policies -> policyTargetsUpdater.replaceTarget(policies, prevTargetId, newTargetId, targetType);
+ Consumer<List<PolicyDefinition>> replaceTarget = policies -> policyTargetsUpdater
+ .replaceTarget(policies, prevTargetId, newTargetId, targetType);
return updatePolicyTargets(container, prevTargetId, targetType, replaceTarget);
}
- private ActionStatus updatePolicyTargets(Component container, String targetId, PolicyTargetType targetType, Consumer<List<PolicyDefinition>> updatePolicyTargetTaskRunner) {
+ private ActionStatus updatePolicyTargets(Component container, String targetId, PolicyTargetType targetType,
+ Consumer<List<PolicyDefinition>> updatePolicyTargetTaskRunner) {
List<PolicyDefinition> policiesWithPrevInstanceAsTarget = container.resolvePoliciesContainingTarget(targetId, targetType);
if (isEmpty(policiesWithPrevInstanceAsTarget)) {
return ActionStatus.OK;
@@ -74,5 +75,4 @@ public class PolicyTargetsUpdateHandler {
StorageOperationStatus updatePolicyResult = toscaOperationFacade.updatePoliciesOfComponent(policiesContainer.getUniqueId(), policiesToUpdate);
return componentsUtils.convertFromStorageResponse(updatePolicyResult, policiesContainer.getComponentType());
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdater.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdater.java
index adf927178f..e2d5f546da 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdater.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdater.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,9 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.policy;
+import static java.util.Collections.emptyList;
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+
+import java.util.List;
+import java.util.Map;
+import java.util.function.UnaryOperator;
import org.apache.commons.collections.MapUtils;
import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum;
@@ -27,13 +32,6 @@ import org.openecomp.sdc.be.model.PolicyDefinition;
import org.openecomp.sdc.be.model.utils.GroupUtils;
import org.springframework.stereotype.Component;
-import java.util.List;
-import java.util.Map;
-import java.util.function.UnaryOperator;
-
-import static java.util.Collections.emptyList;
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-
/**
* A Helper class which handles altering the targets state of a policy
*/
@@ -41,7 +39,7 @@ import static org.apache.commons.collections.CollectionUtils.isEmpty;
public class PolicyTargetsUpdater {
public void removeTarget(List<PolicyDefinition> policies, String targetId, PolicyTargetType targetType) {
- policies.forEach(policy ->removePolicyTarget(policy, targetId, targetType));
+ policies.forEach(policy -> removePolicyTarget(policy, targetId, targetType));
}
public void replaceTarget(List<PolicyDefinition> policies, String oldTargetId, String newTargetId, PolicyTargetType targetType) {
@@ -62,21 +60,19 @@ public class PolicyTargetsUpdater {
if (isEmpty(policyTargets)) {
return;
}
-
policyTargets.remove(targetId);
policy.setVersion(GroupUtils.updateVersion(PromoteVersionEnum.MINOR, policy.getVersion()));
}
private List<String> getTargetsList(PolicyDefinition policyDefinition, PolicyTargetType targetType) {
Map<PolicyTargetType, List<String>> targets = policyDefinition.getTargets();
- if(MapUtils.isEmpty(targets) || isEmpty(targets.get(targetType))) {
+ if (MapUtils.isEmpty(targets) || isEmpty(targets.get(targetType))) {
return emptyList();
}
return targets.get(targetType);
}
private UnaryOperator<String> prevInstanceIdByNewInstanceId(String prevInstanceId, String newInstanceId) {
- return instId -> instId.equals(prevInstanceId) ? newInstanceId: instId;
+ return instId -> instId.equals(prevInstanceId) ? newInstanceId : instId;
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyVersionUpdater.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyVersionUpdater.java
index ef2f8cbad9..ac6e89d6a1 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyVersionUpdater.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyVersionUpdater.java
@@ -17,10 +17,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.policy;
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+import java.util.List;
+import java.util.function.Consumer;
import org.openecomp.sdc.be.components.impl.version.OnChangeVersionCommand;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum;
@@ -33,30 +35,21 @@ import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.utils.GroupUtils;
import org.openecomp.sdc.common.log.wrappers.Logger;
-import java.util.List;
-import java.util.function.Consumer;
-
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-
-
/**
* A Helper class which handles altering the version of a group
*/
@org.springframework.stereotype.Component
public class PolicyVersionUpdater implements OnChangeVersionCommand {
-
+
private static final Logger log = Logger.getLogger(PolicyVersionUpdater.class);
private final ToscaOperationFacade toscaOperationFacade;
private final ComponentsUtils componentsUtils;
-
public PolicyVersionUpdater(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils) {
this.toscaOperationFacade = toscaOperationFacade;
this.componentsUtils = componentsUtils;
-
}
-
-
+
@Override
public ActionStatus onChangeVersion(Component container) {
log.debug("#onChangeVersion - replacing all group members for component instance");
@@ -68,21 +61,16 @@ public class PolicyVersionUpdater implements OnChangeVersionCommand {
policies.forEach(policy -> increaseMajorVersion(policy));
}
-
private void increaseMajorVersion(PolicyDefinition policy) {
String version = policy.getVersion();
-
String newVersion = GroupUtils.updateVersion(PromoteVersionEnum.MAJOR, policy.getVersion());
-
- if(!version.equals(newVersion) ){
+ if (!version.equals(newVersion)) {
String groupUUID = UniqueIdBuilder.generateUUID();
policy.setPolicyUUID(groupUUID);
policy.setVersion(String.valueOf(newVersion));
}
+ }
- }
-
-
private ActionStatus updatePoliciesVersion(Component container, Consumer<List<PolicyDefinition>> updatePoliciesVersion) {
List<PolicyDefinition> policies = container.resolvePoliciesList();
if (isEmpty(policies)) {
@@ -90,15 +78,11 @@ public class PolicyVersionUpdater implements OnChangeVersionCommand {
}
updatePoliciesVersion.accept(policies);
return updatePolicies(container, policies);
- }
+ }
-
private ActionStatus updatePolicies(Component policiesContainer, List<PolicyDefinition> policiesToUpdate) {
log.debug("#updatePolicies - updating {} policies for container {}", policiesToUpdate.size(), policiesContainer.getUniqueId());
StorageOperationStatus updatePolicyResult = toscaOperationFacade.updatePoliciesOfComponent(policiesContainer.getUniqueId(), policiesToUpdate);
return componentsUtils.convertFromStorageResponse(updatePolicyResult, policiesContainer.getComponentType());
}
-
}
-
-
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CINodeFilterUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CINodeFilterUtils.java
index 36c1e585d8..a7dd5afc10 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CINodeFilterUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CINodeFilterUtils.java
@@ -13,9 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.openecomp.sdc.be.components.impl.utils;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.RequirementNodeFilterCapabilityDataDefinition;
@@ -25,22 +27,15 @@ import org.openecomp.sdc.be.model.UploadNodeFilterInfo;
import org.openecomp.sdc.be.model.UploadNodeFilterPropertyInfo;
import org.openecomp.sdc.common.log.wrappers.Logger;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
public class CINodeFilterUtils {
Logger log = Logger.getLogger(CINodeFilterUtils.class);
-
- public CINodeFilterDataDefinition getNodeFilterDataDefinition(
- UploadNodeFilterInfo uploadNodeFilterInfo, String uniqueId) {
- CINodeFilterDataDefinition nodeFilterDataDefinition =
- new CINodeFilterDataDefinition();
+ public CINodeFilterDataDefinition getNodeFilterDataDefinition(UploadNodeFilterInfo uploadNodeFilterInfo, String uniqueId) {
+ CINodeFilterDataDefinition nodeFilterDataDefinition = new CINodeFilterDataDefinition();
nodeFilterDataDefinition.setName(uploadNodeFilterInfo.getName());
- List<RequirementNodeFilterPropertyDataDefinition> collect =
- uploadNodeFilterInfo.getProperties().stream().map(this::buildProperty).collect(Collectors.toList());
+ List<RequirementNodeFilterPropertyDataDefinition> collect = uploadNodeFilterInfo.getProperties().stream().map(this::buildProperty)
+ .collect(Collectors.toList());
ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> listDataDefinition = new ListDataDefinition<>();
listDataDefinition.getListToscaDataDefinition().addAll(collect);
nodeFilterDataDefinition.setProperties(listDataDefinition);
@@ -51,38 +46,31 @@ public class CINodeFilterUtils {
}
private ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> converCapabilties(
- Map<String, UploadNodeFilterCapabilitiesInfo> capabilities) {
- ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> listDataDefinition =
- new ListDataDefinition<>();
+ Map<String, UploadNodeFilterCapabilitiesInfo> capabilities) {
+ ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> listDataDefinition = new ListDataDefinition<>();
for (UploadNodeFilterCapabilitiesInfo capability : capabilities.values()) {
- RequirementNodeFilterCapabilityDataDefinition requirementNodeFilterCapabilityDataDefinition =
- convertCapability(capability);
+ RequirementNodeFilterCapabilityDataDefinition requirementNodeFilterCapabilityDataDefinition = convertCapability(capability);
listDataDefinition.add(requirementNodeFilterCapabilityDataDefinition);
}
return listDataDefinition;
}
- private RequirementNodeFilterCapabilityDataDefinition convertCapability(
- UploadNodeFilterCapabilitiesInfo capability) {
+ private RequirementNodeFilterCapabilityDataDefinition convertCapability(UploadNodeFilterCapabilitiesInfo capability) {
RequirementNodeFilterCapabilityDataDefinition retVal = new RequirementNodeFilterCapabilityDataDefinition();
retVal.setName(capability.getName());
- List<RequirementNodeFilterPropertyDataDefinition> props =
- capability.getProperties().stream().map(this::buildProperty).collect(Collectors.toList());
+ List<RequirementNodeFilterPropertyDataDefinition> props = capability.getProperties().stream().map(this::buildProperty)
+ .collect(Collectors.toList());
ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> propsList = new ListDataDefinition<>();
propsList.getListToscaDataDefinition().addAll(props);
retVal.setProperties(propsList);
return retVal;
}
-
- private RequirementNodeFilterPropertyDataDefinition buildProperty(
- UploadNodeFilterPropertyInfo uploadNodeFilterPropertyInfo) {
+ private RequirementNodeFilterPropertyDataDefinition buildProperty(UploadNodeFilterPropertyInfo uploadNodeFilterPropertyInfo) {
RequirementNodeFilterPropertyDataDefinition retVal = new RequirementNodeFilterPropertyDataDefinition();
retVal.setName(uploadNodeFilterPropertyInfo.getName());
List<String> propertyConstraints = uploadNodeFilterPropertyInfo.getValues();
retVal.setConstraints(propertyConstraints);
return retVal;
}
-
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CapabilityTypeImportUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CapabilityTypeImportUtils.java
index 20a294c076..8deebb60b8 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CapabilityTypeImportUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CapabilityTypeImportUtils.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,12 +17,10 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.utils;
-import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
-
import java.util.Objects;
+import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
public class CapabilityTypeImportUtils {
@@ -33,16 +31,14 @@ public class CapabilityTypeImportUtils {
if (capabilityType1 == capabilityType2) {
return true;
}
-
if (capabilityType1 == null || capabilityType2 == null) {
return false;
}
-
- return Objects.equals(capabilityType1.getType(), capabilityType2.getType()) &&
- Objects.equals(capabilityType1.getVersion(), capabilityType2.getVersion()) &&
- Objects.equals(capabilityType1.getDerivedFrom(), capabilityType2.getDerivedFrom()) &&
- Objects.equals(capabilityType1.getValidSourceTypes(), capabilityType2.getValidSourceTypes()) &&
- Objects.equals(capabilityType1.getDescription(), capabilityType2.getDescription()) &&
- Objects.equals(capabilityType1.getProperties(), capabilityType2.getProperties());
+ return Objects.equals(capabilityType1.getType(), capabilityType2.getType()) && Objects
+ .equals(capabilityType1.getVersion(), capabilityType2.getVersion()) && Objects
+ .equals(capabilityType1.getDerivedFrom(), capabilityType2.getDerivedFrom()) && Objects
+ .equals(capabilityType1.getValidSourceTypes(), capabilityType2.getValidSourceTypes()) && Objects
+ .equals(capabilityType1.getDescription(), capabilityType2.getDescription()) && Objects
+ .equals(capabilityType1.getProperties(), capabilityType2.getProperties());
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ComponentUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ComponentUtils.java
index 02176d902b..038df27939 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ComponentUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ComponentUtils.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.utils;
import java.util.List;
@@ -37,46 +36,28 @@ public final class ComponentUtils {
private ComponentUtils() {
}
- public static boolean checkArtifactInComponent(
- Component component, String artifactId
- ) {
- Predicate<ArtifactDefinition> hasSameArtifactId =
- ad -> ad != null && ad.getUniqueId().equals(artifactId);
-
- return exists(component.getArtifacts(), hasSameArtifactId) ||
- exists(component.getDeploymentArtifacts(), hasSameArtifactId) ||
- exists(component.getToscaArtifacts(), hasSameArtifactId) ||
- hasOperationImplementationWithUniqueId(component, artifactId) ||
- isServiceAndHasApiArtifactWithUniqueId(component, hasSameArtifactId);
+ public static boolean checkArtifactInComponent(Component component, String artifactId) {
+ Predicate<ArtifactDefinition> hasSameArtifactId = ad -> ad != null && ad.getUniqueId().equals(artifactId);
+ return exists(component.getArtifacts(), hasSameArtifactId) || exists(component.getDeploymentArtifacts(), hasSameArtifactId) || exists(
+ component.getToscaArtifacts(), hasSameArtifactId) || hasOperationImplementationWithUniqueId(component, artifactId)
+ || isServiceAndHasApiArtifactWithUniqueId(component, hasSameArtifactId);
}
- private static boolean isServiceAndHasApiArtifactWithUniqueId(Component component,
- Predicate<ArtifactDefinition> hasSameArtifactId) {
- return component.getComponentType() == ComponentTypeEnum.SERVICE && exists(
- ((Service) component).getServiceApiArtifacts(), hasSameArtifactId);
+ private static boolean isServiceAndHasApiArtifactWithUniqueId(Component component, Predicate<ArtifactDefinition> hasSameArtifactId) {
+ return component.getComponentType() == ComponentTypeEnum.SERVICE && exists(((Service) component).getServiceApiArtifacts(), hasSameArtifactId);
}
private static boolean hasOperationImplementationWithUniqueId(Component component, String artifactId) {
- return findFirst(valueStream(component.getInterfaces())
- .flatMap(v -> valueStream(v.getOperationsMap()))
- .map(OperationDataDefinition::getImplementation),
- e -> e != null && e.getUniqueId().equals(artifactId)
- ).isPresent();
+ return findFirst(
+ valueStream(component.getInterfaces()).flatMap(v -> valueStream(v.getOperationsMap())).map(OperationDataDefinition::getImplementation),
+ e -> e != null && e.getUniqueId().equals(artifactId)).isPresent();
}
- public static boolean checkArtifactInResourceInstance(
- Component component, String resourceInstanceId, String artifactId
- ) {
- Predicate<ComponentInstance> hasSameResourceId =
- ri -> ri != null && ri.getUniqueId().equals(resourceInstanceId);
-
- Predicate<ArtifactDefinition> hasSameArtifactId =
- ad -> ad != null && ad.getUniqueId().equals(artifactId);
-
- return findFirst(component.getComponentInstances(), hasSameResourceId).map(ri ->
- exists(ri.getDeploymentArtifacts(), hasSameArtifactId) ||
- exists(ri.getArtifacts(), hasSameArtifactId)
- ).isPresent();
+ public static boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
+ Predicate<ComponentInstance> hasSameResourceId = ri -> ri != null && ri.getUniqueId().equals(resourceInstanceId);
+ Predicate<ArtifactDefinition> hasSameArtifactId = ad -> ad != null && ad.getUniqueId().equals(artifactId);
+ return findFirst(component.getComponentInstances(), hasSameResourceId)
+ .map(ri -> exists(ri.getDeploymentArtifacts(), hasSameArtifactId) || exists(ri.getArtifacts(), hasSameArtifactId)).isPresent();
}
private static <V> Optional<V> findFirst(List<V> ovs, Predicate<V> p) {
@@ -84,9 +65,7 @@ public final class ComponentUtils {
}
private static <K, V> boolean exists(Map<K, V> okvs, Predicate<V> p) {
- return Optional.ofNullable(okvs)
- .flatMap(kvs -> findFirst(kvs.values().stream(), p))
- .isPresent();
+ return Optional.ofNullable(okvs).flatMap(kvs -> findFirst(kvs.values().stream(), p)).isPresent();
}
private static <V> Optional<V> findFirst(Stream<V> vs, Predicate<V> p) {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CreateServiceFromYamlParameter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CreateServiceFromYamlParameter.java
index 5d2f26a991..b0ad5ef9ee 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CreateServiceFromYamlParameter.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CreateServiceFromYamlParameter.java
@@ -13,9 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.openecomp.sdc.be.components.impl.utils;
+import java.util.List;
+import java.util.Map;
import lombok.Getter;
import lombok.Setter;
import org.openecomp.sdc.be.components.csar.CsarInfo;
@@ -23,11 +24,10 @@ import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.NodeTypeInfo;
import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
-import java.util.List;
-import java.util.Map;
@Getter
@Setter
public class CreateServiceFromYamlParameter {
+
private String yamlName;
private ParsedToscaYamlInfo parsedToscaYamlInfo;
private List<ArtifactDefinition> createdArtifacts;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/DirectivesUtil.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/DirectivesUtil.java
index eb7e6baaf3..c759440b4f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/DirectivesUtil.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/DirectivesUtil.java
@@ -16,7 +16,6 @@
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.utils;
import java.util.List;
@@ -29,9 +28,7 @@ public class DirectivesUtil {
private static Optional<String> getDirective(final String directiveValue) {
final List<String> directives = ConfigurationManager.getConfigurationManager().getConfiguration().getDirectives();
if (CollectionUtils.isNotEmpty(directives)) {
- return directives.stream()
- .filter(directiveValues -> directiveValues.equalsIgnoreCase(directiveValue))
- .findFirst();
+ return directives.stream().filter(directiveValues -> directiveValues.equalsIgnoreCase(directiveValue)).findFirst();
}
return Optional.empty();
}
@@ -42,5 +39,4 @@ public class DirectivesUtil {
}
return inDirectives.stream().allMatch(directive -> getDirective(directive).isPresent());
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ExceptionUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ExceptionUtils.java
index ec4192c966..316b82b94e 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ExceptionUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ExceptionUtils.java
@@ -40,27 +40,23 @@ public class ExceptionUtils {
this.janusGraphDao = janusGraphDao;
}
- public <T> T rollBackAndThrow(ActionStatus actionStatus, String ... params) {
- janusGraphDao.rollback();
- throw new ByActionStatusComponentException(actionStatus, params);
- }
+ public <T> T rollBackAndThrow(ActionStatus actionStatus, String... params) {
+ janusGraphDao.rollback();
+ throw new ByActionStatusComponentException(actionStatus, params);
+ }
public <T> T rollBackAndThrow(ResponseFormat responseFormat) {
janusGraphDao.rollback();
throw new ByResponseFormatComponentException(responseFormat);
}
- public <T> T rollBackAndThrow(StorageOperationStatus status, String ... params) {
+ public <T> T rollBackAndThrow(StorageOperationStatus status, String... params) {
janusGraphDao.rollback();
throw new StorageException(status, params);
}
- public <T> T rollBackAndThrow(JanusGraphOperationStatus status, String ... params) {
+ public <T> T rollBackAndThrow(JanusGraphOperationStatus status, String... params) {
janusGraphDao.rollback();
throw new StorageException(status, params);
}
-
-
-
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtils.java
index 4516a226d4..e8ba2d1a2f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtils.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,19 +17,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.utils;
-import org.openecomp.sdc.be.dao.utils.MapUtil;
-import org.openecomp.sdc.be.model.PolicyTypeDefinition;
-import org.openecomp.sdc.be.model.PropertyDefinition;
+import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
+import static org.springframework.util.CollectionUtils.isEmpty;
import java.util.List;
import java.util.Map;
import java.util.Objects;
-
-import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
-import static org.springframework.util.CollectionUtils.isEmpty;
+import org.openecomp.sdc.be.dao.utils.MapUtil;
+import org.openecomp.sdc.be.model.PolicyTypeDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
public class PolicyTypeImportUtils {
@@ -43,22 +41,15 @@ public class PolicyTypeImportUtils {
if (pt1 == null || pt2 == null) {
return false;
}
- return Objects.equals(pt1.getType(), pt2.getType()) &&
- Objects.equals(pt1.getName(), pt2.getName()) &&
- Objects.equals(pt1.getIcon(), pt2.getIcon()) &&
- Objects.equals(pt1.getVersion(), pt2.getVersion()) &&
- Objects.equals(pt1.getDerivedFrom(), pt2.getDerivedFrom()) &&
- Objects.equals(pt1.getTargets(), pt2.getTargets()) &&
- Objects.equals(pt1.getMetadata(), pt2.getMetadata()) &&
- Objects.equals(pt1.getDescription(), pt2.getDescription()) &&
- PolicyTypeImportUtils.isPolicyPropertiesEquals(pt1.getProperties(), pt2.getProperties());
+ return Objects.equals(pt1.getType(), pt2.getType()) && Objects.equals(pt1.getName(), pt2.getName()) && Objects
+ .equals(pt1.getIcon(), pt2.getIcon()) && Objects.equals(pt1.getVersion(), pt2.getVersion()) && Objects
+ .equals(pt1.getDerivedFrom(), pt2.getDerivedFrom()) && Objects.equals(pt1.getTargets(), pt2.getTargets()) && Objects
+ .equals(pt1.getMetadata(), pt2.getMetadata()) && Objects.equals(pt1.getDescription(), pt2.getDescription()) && PolicyTypeImportUtils
+ .isPolicyPropertiesEquals(pt1.getProperties(), pt2.getProperties());
}
- private static boolean isPolicyPropertiesEquals(List<PropertyDefinition> pt1Props,
- List<PropertyDefinition> pt2Props) {
- if ((pt1Props == pt2Props)
- || pt1Props == null && isEmpty(pt2Props)
- || pt2Props == null && isEmpty(pt1Props)) {
+ private static boolean isPolicyPropertiesEquals(List<PropertyDefinition> pt1Props, List<PropertyDefinition> pt2Props) {
+ if ((pt1Props == pt2Props) || pt1Props == null && isEmpty(pt2Props) || pt2Props == null && isEmpty(pt1Props)) {
return true;
} else if (!isPropertiesListSizesEquals(pt1Props, pt2Props)) {
return false;
@@ -66,8 +57,8 @@ public class PolicyTypeImportUtils {
// The two cases tested by these assertions should have been taken care of by the previous two tests
assert (pt1Props != null && pt2Props != null);
Map<String, PropertyDefinition> pt1PropsByName = MapUtil.toMap(pt1Props, PropertyDefinition::getName);
- long numberOfEqualsProperties = pt2Props.stream()
- .filter(pt2Prop -> policyPropertyEquals(pt1PropsByName.get(pt2Prop.getName()), pt2Prop)).count();
+ long numberOfEqualsProperties = pt2Props.stream().filter(pt2Prop -> policyPropertyEquals(pt1PropsByName.get(pt2Prop.getName()), pt2Prop))
+ .count();
return numberOfEqualsProperties == pt1Props.size();
}
}
@@ -79,17 +70,13 @@ public class PolicyTypeImportUtils {
if (pt1Prop == null || pt2Prop == null) {
return false;
}
- return Objects.equals(pt1Prop.getDefaultValue(), pt2Prop.getDefaultValue()) &&
- Objects.equals(pt1Prop.isDefinition(), pt2Prop.isDefinition()) &&
- Objects.equals(pt1Prop.getDescription(), pt2Prop.getDescription()) &&
- Objects.equals(pt1Prop.isPassword(), pt2Prop.isPassword()) &&
- Objects.equals(pt1Prop.isRequired(), pt2Prop.isRequired()) &&
- Objects.equals(pt1Prop.getSchemaType(), pt2Prop.getSchemaType()) &&
- Objects.equals(pt1Prop.getType(), pt2Prop.getType());
+ return Objects.equals(pt1Prop.getDefaultValue(), pt2Prop.getDefaultValue()) && Objects.equals(pt1Prop.isDefinition(), pt2Prop.isDefinition())
+ && Objects.equals(pt1Prop.getDescription(), pt2Prop.getDescription()) && Objects.equals(pt1Prop.isPassword(), pt2Prop.isPassword())
+ && Objects.equals(pt1Prop.isRequired(), pt2Prop.isRequired()) && Objects.equals(pt1Prop.getSchemaType(), pt2Prop.getSchemaType())
+ && Objects.equals(pt1Prop.getType(), pt2Prop.getType());
}
private static boolean isPropertiesListSizesEquals(List<PropertyDefinition> pt1Props, List<PropertyDefinition> pt2Props) {
- return (isEmpty(pt1Props) && isEmpty(pt2Props))
- || (isNotEmpty(pt1Props) && isNotEmpty(pt2Props) && pt1Props.size() == pt2Props.size());
+ return (isEmpty(pt1Props) && isEmpty(pt2Props)) || (isNotEmpty(pt1Props) && isNotEmpty(pt2Props) && pt1Props.size() == pt2Props.size());
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/validation/PMDictionaryValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/validation/PMDictionaryValidator.java
index eee84bb14b..d7f92929cb 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/validation/PMDictionaryValidator.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/validation/PMDictionaryValidator.java
@@ -40,8 +40,7 @@ public class PMDictionaryValidator {
public Optional<String> validateIfPmDictionary(String artifactType, byte[] decodedPayload) {
if (isPmDictionary(artifactType)) {
- return validate(decodedPayload).stream()
- .reduce((a, b) -> a + "; " + b);
+ return validate(decodedPayload).stream().reduce((a, b) -> a + "; " + b);
}
return Optional.empty();
}
@@ -54,9 +53,7 @@ public class PMDictionaryValidator {
List<String> errors = new ArrayList<>();
try {
List<YamlDocumentValidationError> validationErrors = yamlContentValidator.validate(fileContent);
- validationErrors.stream()
- .map(this::formatErrorMessage)
- .forEach(errors::add);
+ validationErrors.stream().map(this::formatErrorMessage).forEach(errors::add);
} catch (Exception e) {
errors.add(e.getMessage());
}
@@ -64,10 +61,6 @@ public class PMDictionaryValidator {
}
private String formatErrorMessage(YamlDocumentValidationError error) {
- return String.format("Document number: %d, Path: %s, Message: %s",
- error.getYamlDocumentNumber(),
- error.getPath(),
- error.getMessage());
+ return String.format("Document number: %d, Path: %s, Message: %s", error.getYamlDocumentNumber(), error.getPath(), error.getMessage());
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/OnChangeVersionCommand.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/OnChangeVersionCommand.java
index de115b5099..19cc14ed0d 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/OnChangeVersionCommand.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/OnChangeVersionCommand.java
@@ -17,23 +17,21 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.version;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.model.Component;
-
@FunctionalInterface
public interface OnChangeVersionCommand {
-
+
/**
* A side effect operation to execute when a component instance version was changed from {@code prevVersion} to {@code newVersion}
- * @param container the container which contains the instance which is version was changed
+ *
+ * @param container the container which contains the instance which is version was changed
* @param prevVersion the previous version of the component instance.
- * @param newVersion the new version of the component instance.
+ * @param newVersion the new version of the component instance.
* @return the status of the operation
*/
ActionStatus onChangeVersion(Component container);
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/VesionUpdateHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/VesionUpdateHandler.java
index 13086c7884..a6bc4d0081 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/VesionUpdateHandler.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/VesionUpdateHandler.java
@@ -17,50 +17,38 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.components.impl.version;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
-
-
-
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.common.log.wrappers.Logger;
@org.springframework.stereotype.Component
public class VesionUpdateHandler {
-
- private static final Logger log = Logger.getLogger(VesionUpdateHandler.class);
+ private static final Logger log = Logger.getLogger(VesionUpdateHandler.class);
private final List<OnChangeVersionCommand> onChangeVersionOperations;
-
- public VesionUpdateHandler( List<OnChangeVersionCommand> onChangeVersionOperations) {
-
+
+ public VesionUpdateHandler(List<OnChangeVersionCommand> onChangeVersionOperations) {
this.onChangeVersionOperations = onChangeVersionOperations;
}
-
-
+
public ActionStatus doPostChangeVersionCommand(Component container) {
- log.debug("#doPostChangeVersionOperations - starting post change version operations for component {}. from instance {} to instance {}", container.getUniqueId());
+ log.debug("#doPostChangeVersionOperations - starting post change version operations for component {}. from instance {} to instance {}",
+ container.getUniqueId());
Function<OnChangeVersionCommand, ActionStatus> vesionChangeTaskRunner = operation -> operation.onChangeVersion(container);
return doOnChangeVesionOperations(vesionChangeTaskRunner);
}
-
+
private ActionStatus doOnChangeVesionOperations(Function<OnChangeVersionCommand, ActionStatus> vesionChangeTaskRunner) {
ActionStatus onVesionChangeResult = ActionStatus.OK;
Iterator<OnChangeVersionCommand> onChangeVesionIter = onChangeVersionOperations.iterator();
- while(onChangeVesionIter.hasNext() && onVesionChangeResult == ActionStatus.OK) {
+ while (onChangeVesionIter.hasNext() && onVesionChangeResult == ActionStatus.OK) {
onVesionChangeResult = vesionChangeTaskRunner.apply(onChangeVesionIter.next());
}
return onVesionChangeResult;
}
-
-
-
-
-
}