X-Git-Url: https://gerrit.onap.org/r/gitweb?a=blobdiff_plain;ds=sidebyside;f=catalog-be%2Fsrc%2Fmain%2Fjava%2Forg%2Fopenecomp%2Fsdc%2Fbe%2Fcomponents%2Fimpl%2FServiceImportParseLogic.java;h=29758b6bc574a65f500b5d043fc38ae540e367c9;hb=fc2bd161cb694f426d0f02e8b322870177036f7f;hp=cf70d39743b8d75100447f6c3fe6590bc7469117;hpb=5ce2da3100483eb505876b428c7c490ff445ba5c;p=sdc.git 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 cf70d39743..29758b6bc5 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,11 +13,27 @@ * 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; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toMap; +import static java.util.stream.Collectors.toSet; +import static org.apache.commons.collections.CollectionUtils.isNotEmpty; import fj.data.Either; +import java.util.ArrayList; +import java.util.Collections; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; import lombok.Getter; import lombok.Setter; import org.apache.commons.codec.binary.Base64; @@ -26,6 +42,7 @@ import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.csar.CsarInfo; import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo; +import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException; import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException; import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; @@ -33,13 +50,53 @@ import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.datatypes.elements.*; +import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.RequirementSubstitutionFilterPropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.CreatedFrom; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.AttributeDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.CapabilityRequirementRelationship; +import org.openecomp.sdc.be.model.CapabilityTypeDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceInput; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.InterfaceDefinition; +import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.NodeTypeInfo; +import org.openecomp.sdc.be.model.Operation; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.RelationshipImpl; +import org.openecomp.sdc.be.model.RelationshipInfo; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.UploadCapInfo; +import org.openecomp.sdc.be.model.UploadComponentInstanceInfo; +import org.openecomp.sdc.be.model.UploadInfo; +import org.openecomp.sdc.be.model.UploadNodeFilterInfo; +import org.openecomp.sdc.be.model.UploadPropInfo; +import org.openecomp.sdc.be.model.UploadReqInfo; +import org.openecomp.sdc.be.model.UploadResourceInfo; +import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; @@ -55,7 +112,6 @@ import org.openecomp.sdc.be.tosca.CsarUtils; import org.openecomp.sdc.be.utils.CommonBeUtils; import org.openecomp.sdc.be.utils.TypeUtils; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; -import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.GeneralUtility; @@ -65,12 +121,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; -import java.util.*; -import java.util.function.Function; - -import static java.util.stream.Collectors.*; -import static org.apache.commons.collections.CollectionUtils.isNotEmpty; - @Getter @Setter @org.springframework.stereotype.Component @@ -86,23 +136,13 @@ public class ServiceImportParseLogic { 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"; - - + private static final Logger log = Logger.getLogger(ServiceImportParseLogic.class); @Autowired private ServiceBusinessLogic serviceBusinessLogic; - public ServiceBusinessLogic getServiceBusinessLogic() { - return serviceBusinessLogic; - } - - public void setServiceBusinessLogic( - ServiceBusinessLogic serviceBusinessLogic) { - this.serviceBusinessLogic = serviceBusinessLogic; - } - @Autowired - protected ComponentsUtils componentsUtils; + private ComponentsUtils componentsUtils; @Autowired - protected ToscaOperationFacade toscaOperationFacade; + private ToscaOperationFacade toscaOperationFacade; @Autowired private LifecycleBusinessLogic lifecycleBusinessLogic; @Autowired @@ -110,36 +150,27 @@ public class ServiceImportParseLogic { @Autowired private ResourceImportManager resourceImportManager; @Autowired + private ComponentSubstitutionFilterBusinessLogic substitutionFilterBusinessLogic; + @Autowired private IInterfaceLifecycleOperation interfaceTypeOperation = null; - private static final Logger log = Logger.getLogger(ServiceImportParseLogic.class); - @Autowired private ICapabilityTypeOperation capabilityTypeOperation = null; - - public ICapabilityTypeOperation getCapabilityTypeOperation() { - return capabilityTypeOperation; - } - - public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) { - this.capabilityTypeOperation = capabilityTypeOperation; - } + @Autowired + private ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic; public Either>>, ResponseFormat> findNodeTypesArtifactsToHandle( - Map nodeTypesInfo, CsarInfo csarInfo, Service oldResource) { - + Map nodeTypesInfo, CsarInfo csarInfo, Service oldResource) { Map>> nodeTypesArtifactsToHandle = new HashMap<>(); - Either>>, ResponseFormat> nodeTypesArtifactsToHandleRes - = Either.left(nodeTypesArtifactsToHandle); - + Either>>, ResponseFormat> nodeTypesArtifactsToHandleRes = Either + .left(nodeTypesArtifactsToHandle); try { Map> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar()); - Map> 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> 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); @@ -148,45 +179,41 @@ public class ServiceImportParseLogic { return nodeTypesArtifactsToHandleRes; } - private Map> extractVfcToscaNames(Map nodeTypesInfo, - String vfResourceName, CsarInfo csarInfo) { + private Map> extractVfcToscaNames(Map nodeTypesInfo, String vfResourceName, + CsarInfo csarInfo) { Map> vfcToscaNames = new HashMap<>(); - Map nodes = extractAllNodes(nodeTypesInfo, csarInfo); if (!nodes.isEmpty()) { Iterator> nodesNameEntry = nodes.entrySet().iterator(); while (nodesNameEntry.hasNext()) { Map.Entry nodeType = nodesNameEntry.next(); - ImmutablePair toscaResourceName = buildNestedToscaResourceName( - ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey()); + ImmutablePair 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 nodeNameValue, Map mapToConvert, - String nodeResourceType, CsarInfo csarInfo) { + public String buildNodeTypeYaml(Map.Entry nodeNameValue, Map 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 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 buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, - String nodeTypeFullName) { + ImmutablePair buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, String nodeTypeFullName) { String actualType; String actualVfName; if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) { @@ -199,30 +226,24 @@ public class ServiceImportParseLogic { String nameWithouNamespacePrefix; try { StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX); - if (!nodeTypeFullName.contains(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)){ + 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)); - //toscaResourceName.append(actualType.toLowerCase()); } 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) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE); + componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE); log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e); throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName); } @@ -239,15 +260,16 @@ public class ServiceImportParseLogic { private void extractNodeTypes(Map nodes, Map mappedToscaTemplate) { Either, ImportUtils.ResultStatusEnum> eitherNodeTypes = ImportUtils - .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES); + .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES); if (eitherNodeTypes.isLeft()) { nodes.putAll(eitherNodeTypes.left().value()); } } - protected void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo, Map>> nodeTypesArtifactsToHandle, - Service resource, Map> extractedVfcsArtifacts, String namespace, ImmutablePair vfcToscaNames){ - + protected void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo, + Map>> nodeTypesArtifactsToHandle, + Service resource, Map> extractedVfcsArtifacts, String namespace, + ImmutablePair vfcToscaNames) { EnumMap> curNodeTypeArtifactsToHandle = null; log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft()); Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), null); @@ -259,22 +281,22 @@ 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 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) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE); + componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE); log.debug("Exception occured when findAddNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e); throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfcToscaNames.getLeft()); } @@ -284,10 +306,8 @@ public class ServiceImportParseLogic { } } - protected void handleAndAddExtractedVfcsArtifacts(List vfcArtifacts, - List artifactsToAdd) { - List vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName) - .collect(toList()); + protected void handleAndAddExtractedVfcsArtifacts(List vfcArtifacts, List artifactsToAdd) { + List vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName).collect(toList()); artifactsToAdd.stream().forEach(a -> { if (!vfcArtifactNames.contains(a.getArtifactName())) { vfcArtifacts.add(a); @@ -297,28 +317,27 @@ public class ServiceImportParseLogic { }); } - protected Resource findVfcResource(CsarInfo csarInfo, Service resource, String currVfcToscaName, String previousVfcToscaName, StorageOperationStatus status) { + protected Resource findVfcResource(CsarInfo csarInfo, Service resource, String currVfcToscaName, String previousVfcToscaName, + StorageOperationStatus status) { if (status != null && status != StorageOperationStatus.NOT_FOUND) { log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, status); throw new ComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID()); } else if (org.apache.commons.lang.StringUtils.isNotEmpty(currVfcToscaName)) { - return (Resource)toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName) - .left() - .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st)); + return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName, resource.getModel()).left() + .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st)); } return null; } - protected EnumMap> findNodeTypeArtifactsToHandle( - Resource curNodeType, List extractedArtifacts) { - + protected EnumMap> findNodeTypeArtifactsToHandle(Resource curNodeType, + List extractedArtifacts) { EnumMap> nodeTypeArtifactsToHandle = null; try { List artifactsToUpload = new ArrayList<>(extractedArtifacts); List artifactsToUpdate = new ArrayList<>(); List artifactsToDelete = new ArrayList<>(); processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, artifactsToDelete, - collectExistingArtifacts(curNodeType)); + collectExistingArtifacts(curNodeType)); nodeTypeArtifactsToHandle = putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete); } catch (Exception e) { log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e); @@ -336,16 +355,15 @@ 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) - .collect(toMap(Map.Entry::getKey, Map.Entry::getValue))); + existingArtifacts.putAll( + curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL) + .collect(toMap(Map.Entry::getKey, Map.Entry::getValue))); } return existingArtifacts; } - protected EnumMap> putFoundArtifacts(List artifactsToUpload, List artifactsToUpdate, List artifactsToDelete) { + protected EnumMap> putFoundArtifacts( + List artifactsToUpload, List artifactsToUpdate, List artifactsToDelete) { EnumMap> nodeTypeArtifactsToHandle = null; if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) { nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class); @@ -363,26 +381,23 @@ public class ServiceImportParseLogic { } protected void processExistingNodeTypeArtifacts(List extractedArtifacts, List artifactsToUpload, - List artifactsToUpdate, List artifactsToDelete, - Map existingArtifacts) { + List artifactsToUpdate, List artifactsToDelete, + Map 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 artifactsToUpload, List artifactsToUpdate, Map existingArtifacts, ArtifactDefinition currNewArtifact) { - Optional foundArtifact = existingArtifacts.values() - .stream() - .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())) - .findFirst(); + protected void processNodeTypeArtifact(List artifactsToUpload, List artifactsToUpdate, + Map existingArtifacts, ArtifactDefinition currNewArtifact) { + Optional 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()); @@ -390,29 +405,26 @@ 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()); } } } - protected void updateFoundArtifact(List artifactsToUpdate, ArtifactDefinition currNewArtifact, ArtifactDefinition foundArtifact) { + protected void updateFoundArtifact(List 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())); + foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData())); + foundArtifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData())); artifactsToUpdate.add(foundArtifact); } } - public void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, - List createdArtifacts, - Either, ResponseFormat> eitherNonMetaArtifacts) { + public void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List createdArtifacts, + Either, ResponseFormat> eitherNonMetaArtifacts) { if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null - && eitherNonMetaArtifacts.isLeft()) { + && eitherNonMetaArtifacts.isLeft()) { Either eitherResult = eitherNonMetaArtifacts.left().value(); if (eitherResult.isLeft()) { createdArtifacts.add(eitherResult.left().value()); @@ -440,8 +452,7 @@ public class ServiceImportParseLogic { } protected boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map allGroups, - Set allGroupMembers) { - + Set allGroupMembers) { boolean stop = false; // In Case Not Group Stop if (!allGroups.containsKey(groupName)) { @@ -451,33 +462,29 @@ 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) { final Set allMembers = allGroups.get(groupName).getMembers().keySet(); Set membersOfTypeGroup = allMembers.stream(). - // Filter In Only Group members - filter(allGroups::containsKey). - // Collect - collect(toSet()); + // Filter In Only Group members + filter(allGroups::containsKey). + // Collect + collect(toSet()); stop = allGroupMembers.containsAll(membersOfTypeGroup); } return stop; } - public Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, - Map nodesInfo) { - + public Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, Map 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) { - + 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); @@ -492,21 +499,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 validateResourceType(User user, Resource resource, - AuditingActionEnum actionEnum) { + protected Either validateResourceType(User user, Resource resource, AuditingActionEnum actionEnum) { Either eitherResult = Either.left(true); if (resource.getResourceType() == null) { log.debug("Invalid resource type for resource"); @@ -517,8 +523,7 @@ public class ServiceImportParseLogic { return eitherResult; } - protected Either validateLifecycleTypesCreate(User user, Resource resource, - AuditingActionEnum actionEnum) { + protected Either validateLifecycleTypesCreate(User user, Resource resource, AuditingActionEnum actionEnum) { Either eitherResult = Either.left(true); if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) { log.debug("validate interface lifecycle Types Exist"); @@ -526,21 +531,16 @@ public class ServiceImportParseLogic { while (intItr.hasNext() && eitherResult.isLeft()) { InterfaceDefinition interfaceDefinition = intItr.next(); String intType = interfaceDefinition.getUniqueId(); - Either eitherCapTypeFound = interfaceTypeOperation - .getInterface(intType); + Either 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); } @@ -549,18 +549,14 @@ public class ServiceImportParseLogic { return eitherResult; } - public Either validateCapabilityTypesCreate(User user, - ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, - boolean inTransaction) { - + public Either validateCapabilityTypesCreate(User user, ICapabilityTypeOperation capabilityTypeOperation, + Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) { Either eitherResult = Either.left(true); if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) { log.debug("validate capability Types Exist - capabilities section"); - for (Map.Entry> 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()); } @@ -569,8 +565,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()); } @@ -579,25 +575,22 @@ public class ServiceImportParseLogic { return eitherResult; } - protected Either validateCapabilityTypeExists(User user, - ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, - Either eitherResult, Map.Entry> typeEntry, - boolean inTransaction) { + protected Either validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, + Resource resource, AuditingActionEnum actionEnum, + Either eitherResult, + Map.Entry> typeEntry, + boolean inTransaction) { Either eitherCapTypeFound = capabilityTypeOperation - .getCapabilityType(typeEntry.getKey(), inTransaction); + .getCapabilityType(UniqueIdBuilder.buildCapabilityTypeUid(resource.getModel(), 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()); @@ -633,35 +626,31 @@ public class ServiceImportParseLogic { return eitherResult; } - protected Either validateCapabilityTypeExists(User user, - ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List validationObjects, - AuditingActionEnum actionEnum, Either eitherResult, String type, - boolean inTransaction) { + protected Either validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, + Resource resource, List validationObjects, + AuditingActionEnum actionEnum, + Either eitherResult, String type, + boolean inTransaction) { try { Either eitherCapTypeFound = capabilityTypeOperation - .getCapabilityType(type, inTransaction); + .getCapabilityType(UniqueIdBuilder.buildCapabilityTypeUid(resource.getModel(), 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()); @@ -669,8 +658,8 @@ public class ServiceImportParseLogic { return eitherResult; } - protected Either validateResourceFieldsBeforeCreate(User user, Resource resource, - AuditingActionEnum actionEnum, boolean inTransaction) { + protected Either validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum, + boolean inTransaction) { serviceBusinessLogic.validateComponentFieldsBeforeCreate(user, resource, actionEnum); // validate category log.debug("validate category"); @@ -699,38 +688,33 @@ 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); } - protected void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) { + protected void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) { if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) { return; } String templateName = resource.getDerivedFrom().get(0); - Either dataModelResponse = toscaOperationFacade - .validateToscaResourceNameExists(templateName); + Either 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); + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource); log.trace("audit before sending response"); componentsUtils.auditResource(responseFormat, user, resource, actionEnum); throw new ComponentException(componentsUtils.convertFromStorageResponse(storageStatus)); @@ -742,13 +726,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 licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration() - .getLicenseTypes(); + List licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getLicenseTypes(); if (!licenseTypes.contains(licenseType)) { log.debug("License type {} isn't configured", licenseType); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); @@ -776,19 +758,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, - "" + 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 ComponentException(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 ComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER); } @@ -804,7 +785,6 @@ public class ServiceImportParseLogic { componentsUtils.auditResource(errorResponse, user, resource, actionEnum); throw new ComponentException(ActionStatus.MISSING_VENDOR_RELEASE); } - validateVendorReleaseName(vendorRelease, user, resource, actionEnum); } @@ -812,12 +792,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); @@ -827,17 +806,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 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"); @@ -853,30 +829,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 { @@ -890,27 +862,20 @@ public class ServiceImportParseLogic { throw new ComponentException(categories.right().value()); } List categoryList = categories.left().value(); - Optional foundCategory = categoryList.stream() - .filter(cat -> cat.getName().equals(category.getName())) + Optional 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 foundSubcategory = foundCategory.get() - .getSubcategories() - .stream() - .filter(subcat -> subcat.getName().equals(subcategory.getName())) - .findFirst(); + Optional 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){ + } catch (Exception e) { log.debug("Exception occured when validateCategoryListed, error is:{}", e.getMessage(), e); throw new ComponentException(ActionStatus.GENERAL_ERROR); } @@ -919,15 +884,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."); @@ -938,18 +900,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); @@ -959,8 +918,7 @@ public class ServiceImportParseLogic { } } - private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName, - Map nodesInfo) { + private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName, Map nodesInfo) { Resource cvfc = new Resource(); NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName); cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName)); @@ -976,15 +934,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 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(); @@ -993,17 +947,14 @@ public class ServiceImportParseLogic { List 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); @@ -1014,54 +965,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 tags = new ArrayList<>(); tags.add(resourceMetaData.getName()); resourceMetaData.setTags(tags); - // Setting category CategoryDefinition category = new CategoryDefinition(); category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME); @@ -1071,13 +1011,11 @@ public class ServiceImportParseLogic { List 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()); @@ -1091,8 +1029,8 @@ public class ServiceImportParseLogic { } public Either findAviableRequiremen(String regName, String yamlName, - UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, - String capName) { + UploadComponentInstanceInfo uploadComponentInstanceInfo, + ComponentInstance currentCompInstance, String capName) { Map> comInstRegDefMap = currentCompInstance.getRequirements(); List list = comInstRegDefMap.get(capName); RequirementDefinition validRegDef = null; @@ -1100,8 +1038,7 @@ public class ServiceImportParseLogic { for (Map.Entry> 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(); @@ -1119,7 +1056,6 @@ public class ServiceImportParseLogic { validRegDef = reqDef; break; } - } } if (validRegDef != null) { @@ -1129,8 +1065,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(); @@ -1152,23 +1087,23 @@ 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); } return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo); - }catch (Exception e){ + } catch (Exception e) { log.debug("Exception occured when findAvailableCapabilityByTypeOrName, error is:{}", e.getMessage(), e); throw new ComponentException(ActionStatus.GENERAL_ERROR); } @@ -1178,11 +1113,9 @@ public class ServiceImportParseLogic { Map> capMap = instance.getCapabilities(); if (capMap.containsKey(validReq.getCapability())) { List 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; @@ -1197,29 +1130,26 @@ 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> capMap = currentCapCompInstance.getCapabilities(); if (!capMap.containsKey(validReq.getCapability())) { return null; } Optional capByName = capMap.get(validReq.getCapability()).stream() - .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny(); + .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; } @@ -1245,12 +1175,15 @@ public class ServiceImportParseLogic { parametersView.setIgnoreComponentInstances(false); parametersView.setIgnoreInputs(false); // inputs are read when creating + // property values on instances parametersView.setIgnoreUsers(false); return parametersView; } - protected void addValidComponentInstanceCapabilities(String key, List capabilities, String resourceId, Map> defaultCapabilities, Map> validCapabilitiesMap){ + protected void addValidComponentInstanceCapabilities(String key, List capabilities, String resourceId, + Map> defaultCapabilities, + Map> validCapabilitiesMap) { String capabilityType = capabilities.get(0).getType(); if (defaultCapabilities.containsKey(capabilityType)) { CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType); @@ -1263,18 +1196,16 @@ public class ServiceImportParseLogic { } } - protected CapabilityDefinition getCapability(String resourceId, Map> defaultCapabilities, String capabilityType) { + protected CapabilityDefinition getCapability(String resourceId, Map> defaultCapabilities, + String capabilityType) { CapabilityDefinition defaultCapability; if (isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) { defaultCapability = defaultCapabilities.get(capabilityType).get(0); } else { - Either getFullComponentRes = toscaOperationFacade - .getToscaFullElement(resourceId); + Either 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); } @@ -1282,33 +1213,27 @@ public class ServiceImportParseLogic { } protected void validateCapabilityProperties(List 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 validProperties = new ArrayList<>(); Map defaultProperties = defaultCapability.getProperties().stream() - .collect(toMap(PropertyDefinition::getName, Function - .identity())); + .collect(toMap(PropertyDefinition::getName, Function.identity())); List 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); @@ -1327,28 +1252,27 @@ public class ServiceImportParseLogic { } public void setDeploymentArtifactsPlaceHolder(Component component, User user) { - if(component instanceof Service){ + if (component instanceof Service) { Service service = (Service) component; Map 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 artifactMap = resource.getDeploymentArtifacts(); if (artifactMap == null) { artifactMap = new HashMap<>(); } - Map deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager() - .getConfiguration().getDeploymentResourceArtifacts(); + Map deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() + .getDeploymentResourceArtifacts(); if (deploymentResourceArtifacts != null) { Map 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); } - } protected void processDeploymentResourceArtifacts(User user, Resource resource, Map artifactMap, String k, Object v) { @@ -1361,16 +1285,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) v, - user, ArtifactGroupTypeEnum.DEPLOYMENT); - if (artifactDefinition != null - && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) { + ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic + .createArtifactPlaceHolderInfo(resource.getUniqueId(), k, (Map) v, user, ArtifactGroupTypeEnum.DEPLOYMENT); + if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) { artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); } } @@ -1378,26 +1299,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 nodesInfo) { + protected Resource buildComplexVfcMetadata(CsarInfo csarInfo, String nodeName, Map nodesInfo) { Resource cvfc = new Resource(); NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName); cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName)); @@ -1413,15 +1327,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 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(); @@ -1430,11 +1340,9 @@ public class ServiceImportParseLogic { List 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; } @@ -1445,34 +1353,46 @@ 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); } } public Service createInputsOnService(Service service, Map inputs) { List resourceProperties = service.getInputs(); - if (MapUtils.isNotEmpty(inputs)|| isNotEmpty(resourceProperties)) { - - Either, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, - service); + if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) { + Either, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, service); if (createInputs.isRight()) { throw new ComponentException(createInputs.right().value()); } } else { return service; } - Either updatedResource = toscaOperationFacade - .getToscaElement(service.getUniqueId()); + Either updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId()); + if (updatedResource.isRight()) { + throw new ComponentException(componentsUtils + .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service, + ComponentTypeEnum.SERVICE)); + } + return updatedResource.left().value(); + } + + public Service createSubstitutionFilterOnService(Service service, + ListDataDefinition substitutionFilterProperties) + throws BusinessLogicException { + if (substitutionFilterProperties == null || substitutionFilterProperties.isEmpty()) { + return service; + } + substitutionFilterBusinessLogic.addSubstitutionFilterInGraph(service.getUniqueId(), substitutionFilterProperties); + Either 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(); } @@ -1481,24 +1401,21 @@ public class ServiceImportParseLogic { public Service createServiceTransaction(Service service, User user, boolean isNormative) { // validate resource name uniqueness log.debug("validate resource name"); - Either eitherValidation = toscaOperationFacade.validateComponentNameExists( - service.getName(), null, service.getComponentType()); + Either 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())); + .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) { @@ -1507,18 +1424,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); @@ -1532,86 +1446,77 @@ public class ServiceImportParseLogic { artifactMap = new HashMap<>(); } String resourceUniqueId = service.getUniqueId(); - List exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration() - .getExcludeResourceCategory(); - List exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration() - .getExcludeResourceType(); - Map informationalResourceArtifacts = ConfigurationManager.getConfigurationManager() - .getConfiguration().getInformationalResourceArtifacts(); + List exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory(); + List exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType(); + Map informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() + .getInformationalResourceArtifacts(); List categories = service.getCategories(); boolean isCreateArtifact = true; if (exludeResourceCategory != null) { String category = categories.get(0).getName(); - isCreateArtifact = exludeResourceCategory.stream().noneMatch(e->e.equalsIgnoreCase(category)); + isCreateArtifact = exludeResourceCategory.stream().noneMatch(e -> e.equalsIgnoreCase(category)); } - if (informationalResourceArtifacts != null && isCreateArtifact) { Set keys = informationalResourceArtifacts.keySet(); for (String informationalResourceArtifactName : keys) { - Map artifactInfoMap = (Map) informationalResourceArtifacts - .get(informationalResourceArtifactName); - ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic.createArtifactPlaceHolderInfo( - resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user, - ArtifactGroupTypeEnum.INFORMATIONAL); - artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); - + Map artifactInfoMap = (Map) informationalResourceArtifacts.get(informationalResourceArtifactName); + if (serviceBusinessLogic.artifactsBusinessLogic != null) { + 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 createdArtifacts, List nodeTypesNewCreatedArtifacts) { - if(!inTransaction) { + public void rollback(boolean inTransaction, Service service, List createdArtifacts, + List nodeTypesNewCreatedArtifacts) { + if (!inTransaction) { serviceBusinessLogic.janusGraphDao.rollback(); } if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) { createdArtifacts.addAll(nodeTypesNewCreatedArtifacts); - log.debug("Found {} newly created artifacts to deleted, the component name: {}",createdArtifacts.size(), service.getName()); + log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(), service.getName()); } } - public Map getNodeTypesFromTemplate(Map mappedToscaTemplate) { - return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES) - .left().orValue(HashMap::new); + public Map getNodeTypesFromTemplate(Map mappedToscaTemplate) { + 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) { - Either resourceResponse = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, - inTransaction, needLock); - if(resourceResponse.isRight()){ + private Resource nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, + boolean needLock) { + Either resourceResponse = lifecycleBusinessLogic + .changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock); + if (resourceResponse.isRight()) { throw new ByResponseFormatComponentException(resourceResponse.right().value()); } return resourceResponse.left().value(); } - public Either validateNestedDerivedFromDuringUpdate(Resource currentResource, - Resource updateInfoResource, boolean hasBeenCertified) { - + public Either validateNestedDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource, + boolean hasBeenCertified) { List currentDerivedFrom = currentResource.getDerivedFrom(); List 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 validateDerivedFromExtending = validateDerivedFromExtending(null, - currentResource, updateInfoResource, null); - + Either 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; @@ -1621,64 +1526,59 @@ public class ServiceImportParseLogic { return Either.left(true); } - protected Either validateDerivedFromExtending(User user, Resource currentResource, - Resource updateInfoResource, AuditingActionEnum actionEnum) { + protected Either validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource, + AuditingActionEnum actionEnum) { String currentTemplateName = currentResource.getDerivedFrom().get(0); String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0); - Either dataModelResponse = toscaOperationFacade - .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName); + .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName, currentResource.getModel()); 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); log.debug("validate description before update"); - serviceBusinessLogic.componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null); + if (serviceBusinessLogic.componentDescriptionValidator != null) { + serviceBusinessLogic.componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null); + } log.debug("validate icon before update"); log.debug("validate tags before update"); - serviceBusinessLogic.componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null); + if (serviceBusinessLogic.componentTagsValidator != null) { + serviceBusinessLogic.componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null); + } log.debug("validate vendor name before update"); log.debug("validate resource vendor model number before update"); log.debug("validate vendor release before update"); log.debug("validate contact info before update"); - serviceBusinessLogic.componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null); + if (serviceBusinessLogic.componentContactIdValidator != null) { + serviceBusinessLogic.componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null); + } 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) { @@ -1686,10 +1586,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); } } @@ -1701,32 +1599,26 @@ 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) { - 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()); + if (response.getRequestError() != null) { + 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 ComponentException(response); } @@ -1740,21 +1632,18 @@ public class ServiceImportParseLogic { public Resource createInputsOnResource(Resource resource, Map inputs) { List resourceProperties = resource.getInputs(); - if (MapUtils.isNotEmpty(inputs)|| isNotEmpty(resourceProperties)) { - - Either, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, - resource); + if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) { + Either, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource); if (createInputs.isRight()) { throw new ComponentException(createInputs.right().value()); } } else { return resource; } - Either updatedResource = toscaOperationFacade - .getToscaElement(resource.getUniqueId()); + Either 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(); } @@ -1774,33 +1663,27 @@ public class ServiceImportParseLogic { if (isNotEmpty(groupsToCreate)) { fillGroupsFinalFields(groupsToCreate); if (isNotEmpty(groupsFromResource)) { - serviceBusinessLogic.groupBusinessLogic.addGroups(resource, - groupsToCreate, true) - .left() - .on(serviceBusinessLogic::throwComponentException); + serviceBusinessLogic.groupBusinessLogic.addGroups(resource, groupsToCreate, true).left() + .on(serviceBusinessLogic::throwComponentException); } else { - serviceBusinessLogic.groupBusinessLogic.createGroups(resource, - groupsToCreate, true) - .left() - .on(serviceBusinessLogic::throwComponentException); + 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() - .on(serviceBusinessLogic::throwComponentException); + serviceBusinessLogic.groupBusinessLogic.updateGroups(resource, groupsToUpdate, true).left() + .on(serviceBusinessLogic::throwComponentException); } } - protected void addGroupsToCreateOrUpdate(List groupsFromResource, List groupsAsList, List groupsToUpdate, List groupsToCreate) { + protected void addGroupsToCreateOrUpdate(List groupsFromResource, List groupsAsList, + List groupsToUpdate, List groupsToCreate) { for (GroupDefinition group : groupsAsList) { - Optional op = groupsFromResource.stream() - .filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName())).findAny(); + Optional op = groupsFromResource.stream().filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName())) + .findAny(); if (op.isPresent()) { GroupDefinition groupToUpdate = op.get(); groupToUpdate.setMembers(group.getMembers()); @@ -1813,10 +1696,10 @@ public class ServiceImportParseLogic { } } - protected void addGroupsToDelete(List groupsFromResource, List groupsAsList, List groupsToDelete) { + protected void addGroupsToDelete(List groupsFromResource, List groupsAsList, + List groupsToDelete) { for (GroupDefinition group : groupsFromResource) { - Optional op = groupsAsList.stream() - .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny(); + Optional op = groupsAsList.stream().filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny(); if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) { groupsToDelete.add(group); } @@ -1824,10 +1707,8 @@ public class ServiceImportParseLogic { } protected List updateGroupsMembersUsingResource(Map groups, Service component) { - List result = new ArrayList<>(); List componentInstances = component.getComponentInstances(); - if (groups != null) { Either validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups); if (validateCyclicGroupsDependencies.isRight()) { @@ -1848,44 +1729,38 @@ public class ServiceImportParseLogic { return result; } - public void updateGroupMembers(Map groups, GroupDefinition updatedGroupDefinition, Service component, List componentInstances, String groupName, Map members) { + public void updateGroupMembers(Map groups, GroupDefinition updatedGroupDefinition, Service component, + List componentInstances, String groupName, Map members) { Set 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 memberNames = componentInstances.stream() - .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId)); + Map memberNames = componentInstances.stream().collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId)); memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> ""))); - Map relevantInstances = memberNames.entrySet().stream() - .filter(n -> compInstancesNames.contains(n.getKey())) - .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)); - + Map 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 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 validateCyclicGroupsDependencies(Map allGroups) { - Either result = Either.left(true); try { Iterator> allGroupsItr = allGroups.entrySet().iterator(); @@ -1898,8 +1773,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); } } @@ -1911,9 +1785,7 @@ public class ServiceImportParseLogic { return result; } - protected void fillAllGroupMemebersRecursivly(String groupName, Map allGroups, - Set allGroupMembers) { - + protected void fillAllGroupMemebersRecursivly(String groupName, Map allGroups, Set allGroupMembers) { // Found Cyclic dependency if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) { return; @@ -1922,100 +1794,84 @@ public class ServiceImportParseLogic { // All Members Of Current Group Resource Instances & Other Groups Set currGroupMembers = groupDefinition.getMembers().keySet(); // Filtered Members Of Current Group containing only members which + // are groups List 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()); - + // 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); } } - public ImmutablePair createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock, + public ImmutablePair createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, + boolean isInTransaction, boolean needLock, Map> nodeTypeArtifactsToHandle, - List nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, - String nodeName, boolean isNested) { - + List nodeTypesNewCreatedArtifacts, + boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName, + boolean isNested) { LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT, - LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR); - - Function validator = resource -> validateResourceCreationFromNodeType( - resource, creator); - - return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, - lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle, - nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested); - } - - public ImmutablePair createNodeTypeResourceFromYaml( - String yamlName, Map.Entry nodeNameValue, User user, Map mapToConvert, - Service resourceVf, boolean needLock, - Map> nodeTypeArtifactsToHandle, - List nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, - boolean isNested) { - + LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR); + Function validator = resource -> validateResourceCreationFromNodeType(resource, creator); + return resourceImportManager + .importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock, + nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested); + } + + public ImmutablePair createNodeTypeResourceFromYaml(String yamlName, Map.Entry nodeNameValue, User user, + Map mapToConvert, Service resourceVf, + boolean needLock, + Map> nodeTypeArtifactsToHandle, + List 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 tags = new ArrayList<>(); tags.add(resourceMetaData.getName()); resourceMetaData.setTags(tags); - // Setting category CategoryDefinition category = new CategoryDefinition(); category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME); @@ -2025,24 +1881,20 @@ public class ServiceImportParseLogic { List 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 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 eitherPopulated = serviceBusinessLogic.populateToscaArtifacts( - resource, user, false, inTransaction, needLock); + Either eitherPopulated = serviceBusinessLogic + .populateToscaArtifacts(resource, user, false, inTransaction, needLock); return resource; } return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock); @@ -2061,14 +1913,11 @@ public class ServiceImportParseLogic { } } - public Resource buildValidComplexVfc(CsarInfo csarInfo, String nodeName, - Map nodesInfo) { - + public Resource buildValidComplexVfc(CsarInfo csarInfo, String nodeName, Map 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 groups) { @@ -2077,11 +1926,10 @@ public class ServiceImportParseLogic { } else { updateOrCreateGroups(resource, groups); } - Either updatedResource = toscaOperationFacade - .getToscaElement(resource.getUniqueId()); + Either 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(); } @@ -2092,44 +1940,43 @@ public class ServiceImportParseLogic { artifactMap = new HashMap<>(); } String resourceUniqueId = resource.getUniqueId(); - List exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration() - .getExcludeResourceCategory(); - List exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration() - .getExcludeResourceType(); - Map informationalResourceArtifacts = ConfigurationManager.getConfigurationManager() - .getConfiguration().getInformationalResourceArtifacts(); + List exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory(); + List exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType(); + Map informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() + .getInformationalResourceArtifacts(); List categories = resource.getCategories(); boolean isCreateArtifact = true; if (exludeResourceCategory != null) { String category = categories.get(0).getName(); - isCreateArtifact = exludeResourceCategory.stream().noneMatch(e->e.equalsIgnoreCase(category)); + 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)); + isCreateArtifact = exludeResourceType.stream().noneMatch(e -> e.equalsIgnoreCase(resourceType)); } if (informationalResourceArtifacts != null && isCreateArtifact) { Set keys = informationalResourceArtifacts.keySet(); for (String informationalResourceArtifactName : keys) { - Map artifactInfoMap = (Map) informationalResourceArtifacts - .get(informationalResourceArtifactName); - ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic.createArtifactPlaceHolderInfo( - resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user, - ArtifactGroupTypeEnum.INFORMATIONAL); - artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); - + Map artifactInfoMap = (Map) informationalResourceArtifacts.get(informationalResourceArtifactName); + if (serviceBusinessLogic.artifactsBusinessLogic != null) { + 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 createdArtifacts, List nodeTypesNewCreatedArtifacts) { - if(!inTransaction) { + public void rollback(boolean inTransaction, Resource resource, List createdArtifacts, + List nodeTypesNewCreatedArtifacts) { + if (!inTransaction) { serviceBusinessLogic.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()); + log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(), resource.getName()); } } @@ -2142,22 +1989,16 @@ public class ServiceImportParseLogic { public void handleGroupsProperties(Service service, Map groups) { List inputs = service.getInputs(); if (MapUtils.isNotEmpty(groups)) { - groups.values() - .stream() - .filter(g -> isNotEmpty(g.getProperties())) - .flatMap(g -> g.getProperties().stream()) - .forEach(p -> handleGetInputs(p, inputs)); + groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream()) + .forEach(p -> handleGetInputs(p, inputs)); } } public void handleGroupsProperties(Resource resource, Map groups) { List 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)); + groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream()) + .forEach(p -> handleGetInputs(p, inputs)); } } @@ -2165,10 +2006,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 getInputValuesIter = property.getGetInputValues().listIterator(); while (getInputValuesIter.hasNext()) { @@ -2186,9 +2025,7 @@ public class ServiceImportParseLogic { } public InputDefinition findInputByName(List inputs, GetInputValueDataDefinition getInput) { - Optional inputOpt = inputs.stream() - .filter(p -> p.getName().equals(getInput.getInputName())) - .findFirst(); + Optional 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()); @@ -2196,15 +2033,15 @@ public class ServiceImportParseLogic { return inputOpt.get(); } - public void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource, Map> instProperties) { + public void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource, + Map> instProperties) { try { Either>, StorageOperationStatus> addPropToInst = toscaOperationFacade - .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId()); + .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()); @@ -2212,86 +2049,74 @@ public class ServiceImportParseLogic { } } - public void associateComponentInstanceInputsToComponent(String yamlName, Resource resource, Map> instInputs) { + public void associateComponentInstanceInputsToComponent(String yamlName, Resource resource, + Map> instInputs) { if (MapUtils.isNotEmpty(instInputs)) { Either>, StorageOperationStatus> addInputToInst = toscaOperationFacade - .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId()); + .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> instDeploymentArtifacts) { - StorageOperationStatus addArtToInst = toscaOperationFacade - .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user); + public void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource, + Map> 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 ComponentException(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); + throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); } } public void associateArtifactsToInstances(String yamlName, Resource resource, Map> 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>> instCapabilities, Map>> instRequirements) { - + public void associateOrAddCalculatedCapReq(String yamlName, Resource resource, + Map>> instCapabilities, + Map>> 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> instAttributes) { - + public void associateInstAttributeToComponentToInstances(String yamlName, Resource resource, + Map> 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 eitherGetResource = toscaOperationFacade - .getToscaElement(resource.getUniqueId(), parametersView); - + Either eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView); if (eitherGetResource.isRight()) { - throwComponentExceptionByResource(eitherGetResource.right().value(),resource); + throwComponentExceptionByResource(eitherGetResource.right().value(), resource); } return eitherGetResource.left().value(); } 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); } public void setCapabilityNamesTypes(Map> originCapabilities, - Map> uploadedCapabilities) { + Map> uploadedCapabilities) { for (Map.Entry> currEntry : uploadedCapabilities.entrySet()) { if (originCapabilities.containsKey(currEntry.getKey())) { currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey())); @@ -2309,138 +2134,129 @@ public class ServiceImportParseLogic { } } - public Map> getValidComponentInstanceCapabilities( - String resourceId, Map> defaultCapabilities, - Map> uploadedCapabilities) { - + public Map> getValidComponentInstanceCapabilities(String resourceId, + Map> defaultCapabilities, + Map> uploadedCapabilities) { Map> validCapabilitiesMap = new HashMap<>(); - uploadedCapabilities.forEach((k,v)->addValidComponentInstanceCapabilities(k,v,resourceId,defaultCapabilities,validCapabilitiesMap)); + uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId, defaultCapabilities, validCapabilitiesMap)); return validCapabilitiesMap; } public void associateComponentInstanceInputsToComponent(String yamlName, Service service, Map> instInputs) { if (MapUtils.isNotEmpty(instInputs)) { Either>, StorageOperationStatus> addInputToInst = toscaOperationFacade - .associateComponentInstanceInputsToComponent(instInputs, service.getUniqueId()); + .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)); + } + } + } + + public void associateCINodeFilterToComponent(String yamlName, Service service, Map nodeFilter) { + log.trace("************* Going to associate all resource node filters {}", yamlName); + if (MapUtils.isNotEmpty(nodeFilter)) { + StorageOperationStatus status = componentNodeFilterBusinessLogic.associateNodeFilterToComponentInstance(service.getUniqueId(), nodeFilter); + if (status != StorageOperationStatus.OK) { + throw new ComponentException( + componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName)); } } } - public void associateComponentInstancePropertiesToComponent(String yamlName, Service service, Map> instProperties) { + public void associateComponentInstancePropertiesToComponent(String yamlName, Service service, + Map> instProperties) { Either>, StorageOperationStatus> addPropToInst = toscaOperationFacade - .associateComponentInstancePropertiesToComponent(instProperties, service.getUniqueId()); + .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> instDeploymentArtifacts) { - StorageOperationStatus addArtToInst = toscaOperationFacade - .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user); + public void associateDeploymentArtifactsToInstances(User user, String yamlName, Service resource, + Map> 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 ComponentException(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); + throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); } } public void associateArtifactsToInstances(String yamlName, Service resource, Map> 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, Service resource, Map>> instCapabilities, Map>> instRequirements) { + public void associateOrAddCalculatedCapReq(String yamlName, Service resource, + Map>> instCapabilities, + Map>> 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> instAttributes) { + public void associateInstAttributeToComponentToInstances(String yamlName, Service resource, + Map> 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 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 capabilities) { + public void associateCapabilitiesToService(String yamlName, Service resource, Map 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 relations) { - Either, StorageOperationStatus> relationsEither = toscaOperationFacade.associateResourceInstances(service, service.getUniqueId(), relations); - + Either, 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> originCapabilities, String type, List capabilities) { - List list = capabilities.stream().map(CapabilityDefinition::new) - .collect(toList()); + List list = capabilities.stream().map(CapabilityDefinition::new).collect(toList()); originCapabilities.put(type, list); } public void addCapabilitiesProperties(Map> newPropertiesMap, List 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 updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter); @@ -2451,7 +2267,6 @@ public class ServiceImportParseLogic { } public Resource getResourceWithGroups(String resourceId) { - ComponentParametersView filter = new ComponentParametersView(); filter.setIgnoreGroups(false); Either updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter); @@ -2462,39 +2277,34 @@ public class ServiceImportParseLogic { } public void associateResourceInstances(String yamlName, Resource resource, List relations) { - - Either, StorageOperationStatus> relationsEither = toscaOperationFacade.associateResourceInstances(resource, resource.getUniqueId(), relations); + Either, 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)); } } - public void addRelationsToRI(String yamlName, Resource resource, Map uploadResInstancesMap, List componentInstancesList, List relations) { + public void addRelationsToRI(String yamlName, Resource resource, Map uploadResInstancesMap, + List componentInstancesList, List relations) { for (Map.Entry 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(), 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); @@ -2502,30 +2312,25 @@ public class ServiceImportParseLogic { } } - protected ResponseFormat addRelationToRI(String yamlName, Resource resource, - UploadComponentInstanceInfo nodesInfoValue, List relations) { + protected ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue, + List relations) { List 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> regMap = nodesInfoValue.getRequirements(); - if (regMap != null) { Iterator>> nodesRegValue = regMap.entrySet().iterator(); while (nodesRegValue.hasNext()) { @@ -2537,16 +2342,13 @@ public class ServiceImportParseLogic { RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef(); regCapRelDef.setFromNode(resourceInstanceId); log.debug("try to find available requirement {} ", regName); - Either eitherReqStatus = findAviableRequiremen(regName, - yamlName, nodesInfoValue, currentCompInstance, - uploadRegInfo.getCapabilityName()); + Either eitherReqStatus = findAviableRequiremen(regName, yamlName, nodesInfoValue, + currentCompInstance, uploadRegInfo.getCapabilityName()); if (eitherReqStatus.isRight()) { return eitherReqStatus.right().value(); } - RequirementDefinition validReq = eitherReqStatus.left().value(); - List reqAndRelationshipPairList = regCapRelDef - .getRelationships(); + List reqAndRelationshipPairList = regCapRelDef.getRelationships(); if (reqAndRelationshipPairList == null) { reqAndRelationshipPairList = new ArrayList<>(); } @@ -2557,7 +2359,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())) { @@ -2565,30 +2366,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); @@ -2602,5 +2397,4 @@ public class ServiceImportParseLogic { } return componentsUtils.getResponseFormat(ActionStatus.OK); } - }