From 75aacbbe1acf78fa53378f07f0a8c7769449a17e Mon Sep 17 00:00:00 2001 From: Michael Lando Date: Mon, 17 Jul 2017 21:12:03 +0300 Subject: [SDC] rebase 1710 code Change-Id: I532ed68979fee7840ea8a5395e7e965b155fb9f9 Signed-off-by: Michael Lando --- catalog-model/pom.xml | 14 +- .../java/org/openecomp/sdc/be/model/Component.java | 10 + .../sdc/be/model/ComponentInstanceInput.java | 2 +- .../sdc/be/model/ComponentInstanceProperty.java | 3 +- .../openecomp/sdc/be/model/GroupDefinition.java | 8 + .../sdc/be/model/IPropertyInputCommon.java | 14 + .../org/openecomp/sdc/be/model/ImportCsarInfo.java | 73 + .../org/openecomp/sdc/be/model/NodeTypeInfo.java | 55 + .../be/model/RequirementAndRelationshipPair.java | 2 +- .../java/org/openecomp/sdc/be/model/Resource.java | 12 +- .../java/org/openecomp/sdc/be/model/Service.java | 18 +- .../sdc/be/model/UploadComponentInstanceInfo.java | 18 + .../jsontitan/operations/ArtifactsOperations.java | 71 +- .../model/jsontitan/operations/BaseOperation.java | 29 +- .../jsontitan/operations/GroupsOperation.java | 2 +- .../operations/NodeTemplateOperation.java | 186 +- .../operations/TopologyTemplateOperation.java | 7 +- .../operations/ToscaElementLifecycleOperation.java | 83 +- .../operations/ToscaElementOperation.java | 96 +- .../jsontitan/operations/ToscaOperationFacade.java | 4097 ++++++++++---------- .../be/model/jsontitan/utils/ModelConverter.java | 46 +- .../be/model/operations/api/IServiceOperation.java | 7 +- .../model/operations/impl/AbstractOperation.java | 9 +- .../impl/ComponentInstanceOperation.java | 7 + .../model/operations/impl/ComponentOperation.java | 1 + .../model/operations/impl/GroupTypeOperation.java | 1 - .../model/operations/impl/PolicyTypeOperation.java | 1 - .../tosca/converters/ToscaMapValueConverter.java | 3 + .../tosca/validators/HeatStringValidator.java | 4 +- .../be/model/tosca/validators/KeyValidator.java | 4 +- .../be/model/tosca/validators/StringValidator.java | 4 +- .../sdc/be/ui/model/UiResourceMetadata.java | 10 + .../sdc/be/ui/model/UiServiceMetadata.java | 20 + .../operations/ArtifactsOperationsTest.java | 85 + .../operations/ToscaElementOperationTest.java | 344 ++ .../operations/ToscaElementOperationTestImpl.java | 74 + .../be/model/jsontitan/utils/GraphTestUtils.java | 114 + 37 files changed, 3236 insertions(+), 2298 deletions(-) create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/IPropertyInputCommon.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/ImportCsarInfo.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/NodeTypeInfo.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperationsTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTestImpl.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/GraphTestUtils.java (limited to 'catalog-model') diff --git a/catalog-model/pom.xml b/catalog-model/pom.xml index a4538fd3db..ef485ae870 100644 --- a/catalog-model/pom.xml +++ b/catalog-model/pom.xml @@ -224,7 +224,19 @@ ${commons-jci-core.version} test - + + org.powermock + powermock-module-junit4 + 1.7.0RC4 + test + + + org.powermock + powermock-api-mockito-common + 1.6.5 + test + + diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java index 036108e81f..9ffefa6384 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java @@ -22,9 +22,12 @@ package org.openecomp.sdc.be.model; import java.io.Serializable; import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import org.codehaus.jackson.annotate.JsonIgnore; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -288,6 +291,13 @@ public abstract class Component implements Serializable { this.deploymentArtifacts = deploymentArtifacts; } + public Map getAllArtifacts() { + HashMap allArtifacts = new HashMap<>(); + allArtifacts.putAll(Optional.ofNullable(this.deploymentArtifacts).orElse(Collections.emptyMap())); + allArtifacts.putAll(Optional.ofNullable(this.artifacts).orElse(Collections.emptyMap())); + return allArtifacts; + } + public List getCategories() { return categories; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java index abcac352cc..1ffbede599 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java @@ -25,7 +25,7 @@ import java.util.List; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyRule; -public class ComponentInstanceInput extends InputDefinition implements IComponentInstanceConnectedElement { +public class ComponentInstanceInput extends InputDefinition implements IComponentInstanceConnectedElement, IPropertyInputCommon { /** * diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java index 25bbb50da4..26c5c02ed5 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java @@ -26,8 +26,7 @@ import java.util.List; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyRule; - -public class ComponentInstanceProperty extends PropertyDefinition implements IComponentInstanceConnectedElement, Serializable{ +public class ComponentInstanceProperty extends PropertyDefinition implements IComponentInstanceConnectedElement, IPropertyInputCommon, Serializable { /** * diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java index 167fa2f0a1..625afe4f96 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java @@ -80,4 +80,12 @@ public class GroupDefinition extends GroupDataDefinition implements Serializable } + //returns true iff groupName has the same prefix has the resource + public boolean isSamePrefix(String resourceName){ + String name = this.getName(); + if ( name != null && name.toLowerCase().trim().startsWith(resourceName.toLowerCase())) + return true; + return false; + } + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/IPropertyInputCommon.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/IPropertyInputCommon.java new file mode 100644 index 0000000000..2f7a580bb6 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/IPropertyInputCommon.java @@ -0,0 +1,14 @@ +package org.openecomp.sdc.be.model; + +import java.util.List; + +import org.openecomp.sdc.be.datatypes.elements.PropertyRule; +import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; + +public interface IPropertyInputCommon { + + String getType(); + SchemaDefinition getSchema(); + List getRules(); + String getName(); +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ImportCsarInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ImportCsarInfo.java new file mode 100644 index 0000000000..460a107c89 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ImportCsarInfo.java @@ -0,0 +1,73 @@ +package org.openecomp.sdc.be.model; + +import java.util.HashMap; +import java.util.Map; +import java.util.PriorityQueue; +import java.util.Queue; + +public class ImportCsarInfo { + String vfResourceName; + User modifier; + String csarUUID; + Map csar; + Map createdNodesToscaResourceNames; + Queue cvfcToCreateQueue; + + public ImportCsarInfo(String vfResourceName, User modifier, String csarUUID, Map csar){ + this.vfResourceName = vfResourceName; + this.modifier = modifier; + this.csarUUID = csarUUID; + this.csar = csar; + this.createdNodesToscaResourceNames = new HashMap<>(); + this.cvfcToCreateQueue = new PriorityQueue<>(); + } + + public String getVfResourceName() { + return vfResourceName; + } + + public void setVfResourceName(String vfResourceName) { + this.vfResourceName = vfResourceName; + } + + public User getModifier() { + return modifier; + } + + public void setModifier(User modifier) { + this.modifier = modifier; + } + + public String getCsarUUID() { + return csarUUID; + } + + public void setCsarUUID(String csarUUID) { + this.csarUUID = csarUUID; + } + + public Map getCsar() { + return csar; + } + + public void setCsar(Map csar) { + this.csar = csar; + } + + public Map getCreatedNodesToscaResourceNames() { + return createdNodesToscaResourceNames; + } + + public void setCreatedNodesToscaResourceNames(Map createdNodesToscaResourceNames) { + this.createdNodesToscaResourceNames = createdNodesToscaResourceNames; + } + + public Queue getCvfcToCreateQueue() { + return cvfcToCreateQueue; + } + + public void setCvfcToCreateQueue(Queue cvfcToCreateQueue) { + this.cvfcToCreateQueue = cvfcToCreateQueue; + } + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/NodeTypeInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/NodeTypeInfo.java new file mode 100644 index 0000000000..1da3b8de1c --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/NodeTypeInfo.java @@ -0,0 +1,55 @@ +package org.openecomp.sdc.be.model; + +import java.util.List; +import java.util.Map; + +public class NodeTypeInfo { + String type; + String templateFileName; + List derivedFrom; + boolean isNested; + Map mappedToscaTemplate; + + public NodeTypeInfo getUnmarkedCopy(){ + NodeTypeInfo unmarked = new NodeTypeInfo(); + unmarked.type = this.type; + unmarked.templateFileName = this.templateFileName; + unmarked.derivedFrom = this.derivedFrom; + unmarked.isNested = false; + unmarked.mappedToscaTemplate = this.mappedToscaTemplate; + return unmarked; + } + + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + public String getTemplateFileName() { + return templateFileName; + } + public void setTemplateFileName(String templateFileName) { + this.templateFileName = templateFileName; + } + public List getDerivedFrom() { + return derivedFrom; + } + public void setDerivedFrom(List derivedFrom) { + this.derivedFrom = derivedFrom; + } + public boolean isNested() { + return isNested; + } + public void setNested(boolean isNested) { + this.isNested = isNested; + } + + public Map getMappedToscaTemplate() { + return mappedToscaTemplate; + } + + public void setMappedToscaTemplate(Map mappedToscaTemplate) { + this.mappedToscaTemplate = mappedToscaTemplate; + } +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementAndRelationshipPair.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementAndRelationshipPair.java index afb013d29a..a3e4f48c51 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementAndRelationshipPair.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementAndRelationshipPair.java @@ -146,7 +146,7 @@ public class RequirementAndRelationshipPair implements Serializable { if ( !savedRelation.getRequirementId().equals(this.getRequirementUid()) ){ return false; } - if ( !savedRelation.getCapabiltyId().equals(this.getCapabilityUid()) ){ + if ( !savedRelation.getCapabilityId().equals(this.getCapabilityUid()) ){ return false; } if ( !savedRelation.getRequirement().equals(this.getRequirement()) ){ diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java index a9c6b44324..45fc5f62b3 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java @@ -255,6 +255,11 @@ public class Resource extends Component implements Serializable { ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()) .setVendorRelease(vendorRelease); } + + public void setResourceVendorModelNumber(String resourceVendorModelNumber){ + ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()). + setResourceVendorModelNumber(resourceVendorModelNumber); + } public String getVendorName() { return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()) @@ -266,6 +271,11 @@ public class Resource extends Component implements Serializable { .getVendorRelease(); } + public String getResourceVendorModelNumber(){ + return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()) + .getResourceVendorModelNumber(); + } + @Override public String fetchGenericTypeToscaNameFromConfig(){ String result = super.fetchGenericTypeToscaNameFromConfig(); @@ -282,7 +292,7 @@ public class Resource extends Component implements Serializable { @Override public boolean shouldGenerateInputs(){ //TODO add complex VFC condition when supported - return ResourceTypeEnum.VF == this.getResourceType(); + return ResourceTypeEnum.VF == this.getResourceType() || ResourceTypeEnum.CVFC == this.getResourceType() || ResourceTypeEnum.PNF == this.getResourceType(); } @Override diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java index 37a42bd581..cdd171184c 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java @@ -85,10 +85,26 @@ public class Service extends Component { public void setNamingPolicy(String namingPolicy) { getServiceMetadataDefinition().setNamingPolicy(namingPolicy); } - + public String getNamingPolicy() { return getServiceMetadataDefinition().getNamingPolicy(); } + + public void setServiceType(String serviceType){ + getServiceMetadataDefinition().setServiceType(serviceType); + } + + public String getServiceType(){ + return getServiceMetadataDefinition().getServiceType(); + } + + public void setServiceRole(String serviceRole){ + getServiceMetadataDefinition().setServiceRole(serviceRole); + } + + public String getServiceRole(){ + return getServiceMetadataDefinition().getServiceRole(); + } private ServiceMetadataDataDefinition getServiceMetadataDefinition() { return (ServiceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition(); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadComponentInstanceInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadComponentInstanceInfo.java index 329e816ea7..eb707787c0 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadComponentInstanceInfo.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadComponentInstanceInfo.java @@ -29,6 +29,8 @@ public class UploadComponentInstanceInfo { private Map> capabilities; private Map> requirements; private Map> properties; + private Map capabilitiesNamesToUpdate; + private Map requirementsNamesToUpdate; public Map> getProperties() { return properties; @@ -70,4 +72,20 @@ public class UploadComponentInstanceInfo { this.requirements = requirements; } + public Map getCapabilitiesNamesToUpdate() { + return capabilitiesNamesToUpdate; + } + + public void setCapabilitiesNamesToUpdate(Map capabilitiesNamesToUpdate) { + this.capabilitiesNamesToUpdate = capabilitiesNamesToUpdate; + } + + public Map getRequirementsNamesToUpdate() { + return requirementsNamesToUpdate; + } + + public void setRequirementsNamesToUpdate(Map requirementsNamesToUpdate) { + this.requirementsNamesToUpdate = requirementsNamesToUpdate; + } + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperations.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperations.java index e2766b1092..b8d8cb39de 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperations.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperations.java @@ -181,6 +181,27 @@ public class ArtifactsOperations extends BaseOperation { return Either.left(resMap); } + /** + * + * @param parentId the id of the instance container + * @param instanceId the id of the instance of which to return its artifacts + * @return instance and instance deployment artifacts mapped by artifact label name + */ + public Either, StorageOperationStatus> getAllInstanceArtifacts(String parentId, String instanceId) { + Map resMap = new HashMap<>(); + Either, TitanOperationStatus> instArtifacts = getInstanceArtifactsByLabel(parentId, instanceId, EdgeLabelEnum.INSTANCE_ARTIFACTS); + if (instArtifacts.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(instArtifacts.right().value())); + } + Either, TitanOperationStatus> deployInstArtifacts = getInstanceArtifactsByLabel(parentId, instanceId, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); + if (deployInstArtifacts.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deployInstArtifacts.right().value())); + } + resMap.putAll(instArtifacts.left().value()); + resMap.putAll(deployInstArtifacts.left().value()); + return Either.left(convertArtifactMapToArtifactDefinitionMap(resMap)); + } + public Either, StorageOperationStatus> getArtifacts(String parentId) { Either, TitanOperationStatus> foundArtifact = null; @@ -384,36 +405,36 @@ public class ArtifactsOperations extends BaseOperation { } private Either, TitanOperationStatus> getArtifactByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) { + Either, TitanOperationStatus> artifactsEither = getArtifactsDataByLabel(parentId, instanceId, edgeLabelEnum); + if (artifactsEither.isRight()) { + log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, artifactsEither.right().value()); + return Either.right(artifactsEither.right().value()); + } + Map artifactDataMap = artifactsEither.left().value(); + return Either.left(convertArtifactMapToArtifactDefinitionMap(artifactDataMap)); + } - Map artMap = null; - Map artifactDataMap = null; + private Either, TitanOperationStatus> getArtifactsDataByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) { + return edgeLabelEnum.isInstanceArtifactsLabel() ? getInstanceArtifactsByLabel(parentId, instanceId, edgeLabelEnum) : getDataFromGraph(parentId, edgeLabelEnum); + } - if (edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) { - Either, TitanOperationStatus> resultEither = getDataFromGraph(parentId, edgeLabelEnum); - if (resultEither.isRight()) { - log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, resultEither.right().value()); - return Either.right(resultEither.right().value()); - } - artifactDataMap = resultEither.left().value(); - } else { - Either, TitanOperationStatus> resultEither = getDataFromGraph(parentId, edgeLabelEnum); - if (resultEither.isRight()) { - log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, resultEither.right().value()); - return Either.right(resultEither.right().value()); - } - Map mapArtifacts = resultEither.left().value(); - MapArtifactDataDefinition artifactPerInstance = mapArtifacts.get(instanceId); - if (artifactPerInstance != null) { - artifactDataMap = artifactPerInstance.getMapToscaDataDefinition(); - } - } + private Map convertArtifactMapToArtifactDefinitionMap(Map artifactDataMap) { + Map artMap = new HashMap<>(); if (artifactDataMap != null && !artifactDataMap.isEmpty()) { - artMap = artifactDataMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> convertArtifactDataToArtifactDefinition(null, e.getValue()))); - } else { - artMap = new HashMap<>(); + artMap = artifactDataMap.entrySet().stream().collect(Collectors.toMap(Entry::getKey, e -> convertArtifactDataToArtifactDefinition(null, e.getValue()))); } - return Either.left(artMap); + return artMap; + } + private Either, TitanOperationStatus> getInstanceArtifactsByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) { + Either, TitanOperationStatus> resultEither = getDataFromGraph(parentId, edgeLabelEnum); + if (resultEither.isRight()) { + log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, resultEither.right().value()); + return Either.right(resultEither.right().value()); + } + Map mapArtifacts = resultEither.left().value(); + MapArtifactDataDefinition artifactPerInstance = mapArtifacts.get(instanceId); + return artifactPerInstance != null ? Either.left(artifactPerInstance.getMapToscaDataDefinition()) : Either.left(new HashMap<>()); } private Triple getEdgeLabelEnumFromArtifactGroupType(ArtifactGroupTypeEnum groupType, NodeTypeEnum nodeType) { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/BaseOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/BaseOperation.java index 69ac568ee9..0b60a07a28 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/BaseOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/BaseOperation.java @@ -1081,12 +1081,10 @@ public abstract class BaseOperation { * * @param toscaElementUid * @param edgeLabel - * @param vertexLabel * @param uniqueKeys - * @param mapKeyField * @return */ - public StorageOperationStatus deleteToscaDataElements(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List uniqueKeys, JsonPresentationFields mapKeyField) { + public StorageOperationStatus deleteToscaDataElements(String toscaElementUid, EdgeLabelEnum edgeLabel, List uniqueKeys) { StorageOperationStatus statusRes = StorageOperationStatus.OK; Either getToscaElementRes; @@ -1098,7 +1096,7 @@ public abstract class BaseOperation { statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); } if (statusRes == StorageOperationStatus.OK) { - statusRes = deleteToscaDataElements(getToscaElementRes.left().value(), edgeLabel, vertexLabel, uniqueKeys, mapKeyField); + statusRes = deleteToscaDataElements(getToscaElementRes.left().value(), edgeLabel, uniqueKeys); } return statusRes; } @@ -1219,25 +1217,22 @@ public abstract class BaseOperation { List uniqueKeys = new ArrayList<>(); uniqueKeys.add(uniqueKey); - return deleteToscaDataElements(toscaElement, edgeLabel, vertexLabel, uniqueKeys, mapKeyField); + return deleteToscaDataElements(toscaElement, edgeLabel, uniqueKeys); } @SuppressWarnings("unchecked") - /** - * Deletes tosca data elements belonging to tosca element according label - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param uniqueKeys - * @param mapKeyField - * @return - */ - public StorageOperationStatus deleteToscaDataElements(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List uniqueKeys, JsonPresentationFields mapKeyField) { +/** + * Deletes tosca data elements belonging to tosca element according label + * @param toscaElement + * @param edgeLabel + * @param uniqueKeys + * @return + */ + public StorageOperationStatus deleteToscaDataElements(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, List uniqueKeys) { StorageOperationStatus result = null; GraphVertex toscaDataVertex; - Map existingToscaDataMap = null; + Map existingToscaDataMap; Either toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); if (toscaDataVertexRes.isRight()) { TitanOperationStatus status = toscaDataVertexRes.right().value(); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java index 737c1c2d40..5f7502e7ce 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java @@ -139,7 +139,7 @@ public class GroupsOperation extends BaseOperation { } if (result == null) { List groupName = groups.stream().map(g -> g.getName()).collect(Collectors.toList()); - status = deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groupName, JsonPresentationFields.NAME); + status = deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.GROUPS, groupName); if (status != StorageOperationStatus.OK) { result = Either.right(status); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperation.java index 33db64234b..66d26c748f 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperation.java @@ -37,8 +37,6 @@ import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; @@ -67,12 +65,10 @@ import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; 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.DistributionStatusEnum; import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.GroupInstance; import org.openecomp.sdc.be.model.RelationshipImpl; @@ -849,10 +845,8 @@ public class NodeTemplateOperation extends BaseOperation { dataDefinition.setComponentVersion((String) originToscaElement.getMetadataValue(JsonPresentationFields.VERSION)); if (StringUtils.isEmpty(dataDefinition.getComponentName()) && originToscaElement != null) dataDefinition.setComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.NAME)); -// if (StringUtils.isEmpty(dataDefinition.getToscaComponentName()) && originToscaElement != null) - - dataDefinition.setToscaComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); - + if (originToscaElement != null) + dataDefinition.setToscaComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); if (dataDefinition.getOriginType() == null && originToscaElement != null) { ResourceTypeEnum resourceType = originToscaElement.getResourceType(); OriginTypeEnum originType = null; @@ -863,12 +857,18 @@ public class NodeTemplateOperation extends BaseOperation { case VFC: originType = OriginTypeEnum.VFC; break; + case CVFC: + originType = OriginTypeEnum.CVFC; + break; case VL: originType = OriginTypeEnum.VL; break; case CP: originType = OriginTypeEnum.CP; break; + case PNF: + originType = OriginTypeEnum.PNF; + break; default: break; } @@ -1016,7 +1016,7 @@ public class NodeTemplateOperation extends BaseOperation { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update topology template {} with new relations error {}. ", componentId, updateElement.right().value()); return DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value()); } - // update cap/req jsons, fullfilled cap/req jsons!!!!! + // update cap/req jsons, fulfilled cap/req jsons!!!!! Either status; CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Update calculated capabilty for container {}", containerV.getUniqueId()); status = updateOrCopyOnUpdate(capResult.left().value().getLeft(), containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES); @@ -1070,7 +1070,7 @@ public class NodeTemplateOperation extends BaseOperation { } GraphVertex containerV = containerVEither.left().value(); - // DE191707 - validatations + // DE191707 - validations Map jsonComposition = (Map) containerV.getJson(); CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue()); Map componentInstances = compositionDataDefinition.getComponentInstances(); @@ -1092,16 +1092,15 @@ public class NodeTemplateOperation extends BaseOperation { Either>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES); if (capResult.isRight()) { return Either.right(capResult.right().value()); - } - Map calculatedCapabilty = capResult.left().value().getRight(); + Map calculatedCapability = capResult.left().value().getRight(); Either>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); if (capResult.isRight()) { return Either.right(capResult.right().value()); } - Map fullFilledCapabilty = capFullResult.left().value().getRight(); + Map fulfilledCapability = capFullResult.left().value().getRight(); Either>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS); if (reqResult.isRight()) { @@ -1113,7 +1112,7 @@ public class NodeTemplateOperation extends BaseOperation { if (reqResult.isRight()) { return Either.right(reqResult.right().value()); } - Map fullfilledRequirement = reqFullResult.left().value().getRight(); + Map fulfilledRequirement = reqFullResult.left().value().getRight(); for (RequirementAndRelationshipPair relationPair : relationPairList) { Iterator> iterator = relations.entrySet().iterator(); @@ -1123,16 +1122,16 @@ public class NodeTemplateOperation extends BaseOperation { RelationshipInstDataDefinition relationInJson = entryInJson.getValue(); if (relationInJson.getFromId().equals(fromResInstanceUid) && relationInJson.getToId().equals(toResInstanceUid)) { if (relationPair.equalsTo(relationInJson)) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Remove relation from {} to {} capabilty {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationInJson.getType(), + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Remove relation from {} to {} capability {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationInJson.getType(), relationInJson.getCapabilityOwnerId(), relationInJson.getRequirementOwnerId()); iterator.remove(); // update calculated cap/req - StorageOperationStatus status = updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relationInJson); + StorageOperationStatus status = updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapability, fulfilledCapability, toResInstanceUid, relationInJson); if (status != StorageOperationStatus.OK) { return Either.right(status); } - status = updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, fromResInstanceUid, relationInJson); + status = updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fulfilledRequirement, fromResInstanceUid, relationInJson); if (status != StorageOperationStatus.OK) { return Either.right(status); } @@ -1168,90 +1167,87 @@ public class NodeTemplateOperation extends BaseOperation { private StorageOperationStatus updateCalculatedRequirementsAfterDeleteRelation(Map calculatedRequirement, Map fullFilledRequirement, String fromResInstanceUid, RelationshipInstDataDefinition relation) { StorageOperationStatus status; + String hereIsTheKey = null; MapListRequirementDataDefinition reqByInstance = calculatedRequirement.get(fromResInstanceUid); - if (reqByInstance == null) { - // move from fullfilled - status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation); + if (reqByInstance == null || reqByInstance.findKeyByItemUidMatch(relation.getRequirementId()) == null) { + // move from fulfilled + status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation, hereIsTheKey); } else { - ListRequirementDataDefinition reqByType = reqByInstance.findByKey(relation.getType()); - if (reqByType == null) { - // move from fullfilled - status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation); - } else { - Optional requirementOptional = reqByType.getListToscaDataDefinition().stream() - .filter(cap -> cap.getOwnerId().equals(relation.getRequirementOwnerId()) && cap.getName().equals(relation.getRequirement()) && cap.getUniqueId().equals(relation.getRequirementId())).findFirst(); + hereIsTheKey = reqByInstance.findKeyByItemUidMatch(relation.getRequirementId()); + ListRequirementDataDefinition reqByType = reqByInstance.findByKey(hereIsTheKey); + Optional requirementOptional = reqByType.getListToscaDataDefinition().stream() + .filter(req -> req.getOwnerId().equals(relation.getRequirementOwnerId()) && req.getName().equals(relation.getRequirement()) && req.getUniqueId().equals(relation.getRequirementId())).findFirst(); - if (requirementOptional.isPresent()) { + if (requirementOptional.isPresent()) { - RequirementDataDefinition requirement = requirementOptional.get(); - String leftOccurrences = requirement.getLeftOccurrences(); - if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) { - Integer leftIntValue = Integer.parseInt(leftOccurrences); - ++leftIntValue; - requirement.setLeftOccurrences(String.valueOf(leftIntValue)); - } - status = StorageOperationStatus.OK; - } else { - // move from fullfilled - status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation); + RequirementDataDefinition requirement = requirementOptional.get(); + String leftOccurrences = requirement.getLeftOccurrences(); + if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) { + Integer leftIntValue = Integer.parseInt(leftOccurrences); + ++leftIntValue; + requirement.setLeftOccurrences(String.valueOf(leftIntValue)); } + status = StorageOperationStatus.OK; + } else { + // move from fulfilled + status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation, hereIsTheKey); } } return status; } - private StorageOperationStatus updateCalculatedCapabiltyAfterDeleteRelation(Map calculatedCapabilty, Map fullFilledCapabilty, String toResInstanceUid, + + private StorageOperationStatus updateCalculatedCapabiltyAfterDeleteRelation(Map calculatedCapability, Map fullFilledCapability, String toResInstanceUid, RelationshipInstDataDefinition relation) { StorageOperationStatus status; - MapListCapabiltyDataDefinition capByInstance = calculatedCapabilty.get(toResInstanceUid); - if (capByInstance == null) { - // move from fullfilled - status = moveFromFullFilledCapabilty(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relation); + String hereIsTheKey = null; + MapListCapabiltyDataDefinition capByInstance = calculatedCapability.get(toResInstanceUid); + if (capByInstance == null || capByInstance.findKeyByItemUidMatch(relation.getCapabilityId()) == null) { + // move from fulfilled + status = moveFromFullFilledCapabilty(calculatedCapability, fullFilledCapability, toResInstanceUid, relation, hereIsTheKey); } else { - ListCapabilityDataDefinition capByType = capByInstance.findByKey(relation.getType()); - if (capByType == null) { - // move from fullfilled - status = moveFromFullFilledCapabilty(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relation); - } else { - Optional capabiltyOptional = capByType.getListToscaDataDefinition().stream() - .filter(cap -> cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabiltyId())).findFirst(); + hereIsTheKey = capByInstance.findKeyByItemUidMatch(relation.getCapabilityId()); + ListCapabilityDataDefinition capByType = capByInstance.findByKey(hereIsTheKey); + Optional capabilityOptional = capByType.getListToscaDataDefinition().stream() + .filter(cap -> cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabilityId())).findFirst(); - if (capabiltyOptional.isPresent()) { + if (capabilityOptional.isPresent()) { - CapabilityDataDefinition capability = capabiltyOptional.get(); - String leftOccurrences = capability.getLeftOccurrences(); - if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { - Integer leftIntValue = Integer.parseInt(leftOccurrences); - ++leftIntValue; - capability.setLeftOccurrences(String.valueOf(leftIntValue)); - } - status = StorageOperationStatus.OK; - } else { - // move from fullfilled - status = moveFromFullFilledCapabilty(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relation); + CapabilityDataDefinition capability = capabilityOptional.get(); + String leftOccurrences = capability.getLeftOccurrences(); + if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { + Integer leftIntValue = Integer.parseInt(leftOccurrences); + ++leftIntValue; + capability.setLeftOccurrences(String.valueOf(leftIntValue)); } + status = StorageOperationStatus.OK; + } else { + // move from fulfilled + status = moveFromFullFilledCapabilty(calculatedCapability, fullFilledCapability, toResInstanceUid, relation, hereIsTheKey); } } return status; } - private StorageOperationStatus moveFromFullFilledCapabilty(Map calculatedCapabilty, Map fullFilledCapabilty, String toResInstanceUid, - RelationshipInstDataDefinition relation) { - MapListCapabiltyDataDefinition capByInstance = fullFilledCapabilty.get(toResInstanceUid); + private StorageOperationStatus moveFromFullFilledCapabilty(Map calculatedCapability, Map fullFilledCapability, String toResInstanceUid, + RelationshipInstDataDefinition relation, String hereIsTheKey) { + MapListCapabiltyDataDefinition capByInstance = fullFilledCapability.get(toResInstanceUid); if (capByInstance == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capabilty in fullfilled list for instance {} ", toResInstanceUid); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capability in fulfilled list for instance {} ", toResInstanceUid); return StorageOperationStatus.GENERAL_ERROR; } - ListCapabilityDataDefinition capByType = capByInstance.findByKey(relation.getType()); - if (capByType == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capabilty type {} in fullfilled list for instance {} ", relation.getType(), toResInstanceUid); + if (null == hereIsTheKey) + hereIsTheKey = capByInstance.findKeyByItemUidMatch(relation.getCapabilityId()); + if (null == hereIsTheKey) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capability with id {} in fulfilled list for instance {} ", relation.getCapabilityId(), toResInstanceUid); return StorageOperationStatus.GENERAL_ERROR; } + ListCapabilityDataDefinition capByType = capByInstance.findByKey(hereIsTheKey); Iterator iterator = capByType.getListToscaDataDefinition().iterator(); boolean found = false; while (iterator.hasNext()) { CapabilityDataDefinition cap = iterator.next(); - if (cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getName().equals(relation.getRequirement()) && cap.getUniqueId().equals(relation.getCapabiltyId())) { + if (cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabilityId())) { found = true; iterator.remove(); // return to calculated list @@ -1260,38 +1256,40 @@ public class NodeTemplateOperation extends BaseOperation { ++leftIntValue; cap.setLeftOccurrences(String.valueOf(leftIntValue)); - MapListCapabiltyDataDefinition mapListCapaDataDef = calculatedCapabilty.get(toResInstanceUid); + MapListCapabiltyDataDefinition mapListCapaDataDef = calculatedCapability.get(toResInstanceUid); if (mapListCapaDataDef == null) { mapListCapaDataDef = new MapListCapabiltyDataDefinition(); } - ListCapabilityDataDefinition findByKey = mapListCapaDataDef.findByKey(relation.getType()); + ListCapabilityDataDefinition findByKey = mapListCapaDataDef.findByKey(hereIsTheKey); if (findByKey == null) { findByKey = new ListCapabilityDataDefinition(); - mapListCapaDataDef.put(relation.getType(), findByKey); + mapListCapaDataDef.put(hereIsTheKey, findByKey); } findByKey.add(cap); break; } } if (found == false) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capabilty type {} with ownerId {} in fullfilled list for instance {} ", relation.getType(), relation.getCapabilityOwnerId(), toResInstanceUid); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capability type {} with ownerId {} in fulfilled list for instance {} ", hereIsTheKey, relation.getCapabilityOwnerId(), toResInstanceUid); return StorageOperationStatus.GENERAL_ERROR; } return StorageOperationStatus.OK; } private StorageOperationStatus moveFromFullFilledRequirement(Map calculatedRequirement, Map fullFilledRequirement, String fromResInstanceUid, - RelationshipInstDataDefinition relation) { + RelationshipInstDataDefinition relation, String hereIsTheKey) { MapListRequirementDataDefinition reqByInstance = fullFilledRequirement.get(fromResInstanceUid); if (reqByInstance == null) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement in fullfilled list for instance {} ", fromResInstanceUid); return StorageOperationStatus.GENERAL_ERROR; } - ListRequirementDataDefinition reqByType = reqByInstance.findByKey(relation.getType()); - if (reqByType == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement type {} in fullfilled list for instance {} ", relation.getType(), fromResInstanceUid); + if(null == hereIsTheKey) + hereIsTheKey = reqByInstance.findKeyByItemUidMatch(relation.getRequirementId()); + if (null == hereIsTheKey) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement with id {} in fulfilled list for instance {} ", relation.getRequirementId(), fromResInstanceUid); return StorageOperationStatus.GENERAL_ERROR; } + ListRequirementDataDefinition reqByType = reqByInstance.findByKey(hereIsTheKey); Iterator iterator = reqByType.getListToscaDataDefinition().iterator(); boolean found = false; while (iterator.hasNext()) { @@ -1309,17 +1307,17 @@ public class NodeTemplateOperation extends BaseOperation { if (mapListReqDataDef == null) { mapListReqDataDef = new MapListRequirementDataDefinition(); } - ListRequirementDataDefinition findByKey = mapListReqDataDef.findByKey(relation.getType()); + ListRequirementDataDefinition findByKey = mapListReqDataDef.findByKey(hereIsTheKey); if (findByKey == null) { findByKey = new ListRequirementDataDefinition(); - mapListReqDataDef.put(relation.getType(), findByKey); + mapListReqDataDef.put(hereIsTheKey, findByKey); } findByKey.add(req); break; } } if (found == false) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement type {} with ownerId {} in fullfilled list for instance {} ", relation.getType(), relation.getCapabilityOwnerId(), fromResInstanceUid); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement type {} with ownerId {} in fulfilled list for instance {} ", hereIsTheKey, relation.getRequirementOwnerId(), fromResInstanceUid); return StorageOperationStatus.GENERAL_ERROR; } return StorageOperationStatus.OK; @@ -1414,22 +1412,22 @@ public class NodeTemplateOperation extends BaseOperation { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilities for type {} for instance {} in container {}.", type, toInstId, containerId); return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); } - CapabilityDataDefinition capabiltyForRelation = null; + CapabilityDataDefinition capabilityForRelation = null; Iterator iteratorCap = listCapabilityDataDefinition.getListToscaDataDefinition().iterator(); while (iteratorCap.hasNext()) { CapabilityDataDefinition cap = iteratorCap.next(); if (cap.getUniqueId().equals(relationPair.getCapabilityUid()) && cap.getOwnerId().equals(relationPair.getCapabilityOwnerId())) { - capabiltyForRelation = cap; + capabilityForRelation = cap; String leftOccurrences = cap.getLeftOccurrences(); if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { Integer leftIntValue = Integer.parseInt(leftOccurrences); if (leftIntValue > 0) { --leftIntValue; - capabiltyForRelation.setLeftOccurrences(String.valueOf(leftIntValue)); + capabilityForRelation.setLeftOccurrences(String.valueOf(leftIntValue)); if (leftIntValue == 0) { // remove from calculated iteratorCap.remove(); - // move to fullfilled + // move to fulfilled MapListCapabiltyDataDefinition mapListCapabiltyFullFilledInst = fullfilledCapabilty.get(toInstId); if (mapListCapabiltyFullFilledInst == null) { mapListCapabiltyFullFilledInst = new MapListCapabiltyDataDefinition(); @@ -1441,17 +1439,17 @@ public class NodeTemplateOperation extends BaseOperation { listCapabilityFull = new ListCapabilityDataDefinition(); mapListCapabiltyFullFilledInst.put(type, listCapabilityFull); } - listCapabilityFull.add(capabiltyForRelation); + listCapabilityFull.add(capabilityForRelation); } break; } else { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No left occurrences capabilty {} to {} in container {}.", capabiltyForRelation.getType(), toInstId, containerId); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No left occurrences capabilty {} to {} in container {}.", capabilityForRelation.getType(), toInstId, containerId); return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); } } } } - if (capabiltyForRelation == null) { + if (capabilityForRelation == null) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch capabilty for type {} for instance {} in container {}.", type, toInstId, containerId); return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); } @@ -1485,7 +1483,7 @@ public class NodeTemplateOperation extends BaseOperation { if (leftIntValue == 0) { // remove from calculated iteratorReq.remove(); - // move to fullfilled + // move to fulfilled MapListRequirementDataDefinition mapListRequirementFullFilledInst = fullfilledRequirement.get(fromInstId); if (mapListRequirementFullFilledInst == null) { mapListRequirementFullFilledInst = new MapListRequirementDataDefinition(); @@ -1507,16 +1505,14 @@ public class NodeTemplateOperation extends BaseOperation { } } } - if (!capabiltyForRelation.getType().equals(requirementForRelation.getCapability())) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No math for capabilty from type {} and requirement {} from {} to {} in container {}.", capabiltyForRelation.getType(), requirementForRelation.getCapability(), fromInstId, toInstId, + if (!capabilityForRelation.getType().equals(requirementForRelation.getCapability())) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No math for capability from type {} and requirement {} from {} to {} in container {}.", capabilityForRelation.getType(), requirementForRelation.getCapability(), fromInstId, toInstId, containerId); return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); } RelationshipInstDataDefinition relationshipTypeData = buildRelationshipInstData(fromInstId, toInstId, relationPair); - relationshipTypeData.setType(requirementForRelation.getRelationship()); - return Either.left(relationshipTypeData); } @@ -1531,7 +1527,7 @@ public class NodeTemplateOperation extends BaseOperation { relationshipInstData.setModificationTime(creationDate); relationshipInstData.setCapabilityOwnerId(relationPair.getCapabilityOwnerId()); relationshipInstData.setRequirementOwnerId(relationPair.getRequirementOwnerId()); - relationshipInstData.setCapabiltyId(relationPair.getCapabilityUid()); + relationshipInstData.setCapabilityId(relationPair.getCapabilityUid()); relationshipInstData.setRequirementId(relationPair.getRequirementUid()); relationshipInstData.setFromId(fromResInstanceUid); relationshipInstData.setToId(toInstId); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperation.java index 99a602f234..2d160bfc82 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperation.java @@ -140,7 +140,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation { return result; } StorageOperationStatus associateInstGroups = associateInstGroupsToComponent(topologyTemplateVertex, topologyTemplate); - if (associateInstProperties != StorageOperationStatus.OK) { + if (associateInstGroups != StorageOperationStatus.OK) { result = Either.right(associateInstInputs); return result; } @@ -786,12 +786,11 @@ public class TopologyTemplateOperation extends ToscaElementOperation { GraphVertex categoryV = childVertex.left().value(); Map metadataProperties = categoryV.getMetadataProperties(); CategoryDefinition category = new CategoryDefinition(); - category.setUniqueId((String) metadataProperties.get(GraphPropertyEnum.UNIQUE_ID)); + category.setUniqueId(categoryV.getUniqueId()); category.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME)); category.setName((String) metadataProperties.get(GraphPropertyEnum.NAME)); - Type listTypeCat = new TypeToken>() { - }.getType(); + Type listTypeCat = new TypeToken>() {}.getType(); List iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS.getProperty()), listTypeCat); category.setIcons(iconsfromJsonCat); categories.add(category); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementLifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementLifecycleOperation.java index d57e7cc255..4282a2cba8 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementLifecycleOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementLifecycleOperation.java @@ -27,7 +27,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.Map.Entry; import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; @@ -37,9 +36,7 @@ import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Vertex; - import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; @@ -55,20 +52,16 @@ import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.DistributionStatusEnum; -import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; @@ -78,10 +71,8 @@ import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.jsongraph.util.CommonUtility; import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; -import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -1014,8 +1005,8 @@ public class ToscaElementLifecycleOperation extends BaseOperation { } //TODO remove after jsonModelMigration - public void resolveToscaComponentName(ComponentInstanceDataDefinition vfInst, Map origCompMap) { - fixToscaComponentName(vfInst, origCompMap); + public boolean resolveToscaComponentName(ComponentInstanceDataDefinition vfInst, Map origCompMap) { + return fixToscaComponentName(vfInst, origCompMap); } private boolean fixToscaComponentName(ComponentInstanceDataDefinition vfInst, Map origCompMap) { @@ -1035,7 +1026,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find orig component {} . Status is {}. ", origCompEither.right().value()); return false; } - origComp = origCompEither.left().value(); + origComp = origCompEither.left().value(); origCompMap.put(origCompUid, origComp); } else { origComp = origCompMap.get(origCompUid); @@ -1460,4 +1451,72 @@ public class ToscaElementLifecycleOperation extends BaseOperation { } return false; } + + public Either forceCerificationOfToscaElement(String toscaElementId, String modifierId, String ownerId) { + Either resultUpdate = null; + Either result = null; + GraphVertex toscaElement = null; + GraphVertex modifier = null; + GraphVertex owner; + try { + Either, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); + if (getVerticesRes.isRight()) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); + } + if (result == null) { + toscaElement = getVerticesRes.left().value().get(toscaElementId); + modifier = getVerticesRes.left().value().get(modifierId); + owner = getVerticesRes.left().value().get(ownerId); + + StorageOperationStatus status = handleRelationsUponForceCertification(toscaElement, modifier, owner); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations on certification request for tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status); + } + } + if (result == null) { + LifecycleStateEnum nextState = LifecycleStateEnum.CERTIFIED; + + toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + toscaElement.addMetadataProperty(GraphPropertyEnum.VERSION, "1.0"); + + resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement); + if (resultUpdate.isRight()) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to set lifecycle for tosca elememt {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value()); + result = Either.right(resultUpdate.right().value()); + } + } + if (result == null) { + ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel()); + result = operation.getToscaElement(toscaElement.getUniqueId()); + } + return result; + + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during request certification tosca element {}. {}", toscaElementId, e.getMessage()); + } + return result; + } + + private StorageOperationStatus handleRelationsUponForceCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) { + + StorageOperationStatus result = null; + TitanOperationStatus status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE); + if (status != TitanOperationStatus.OK) { + result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + if (result == null) { + Map properties = new EnumMap<>(EdgePropertyEnum.class); + properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.CERTIFIED); + status = titanDao.createEdge(modifier, toscaElement, EdgeLabelEnum.STATE, properties); + if (status != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "failed to create edge. Status is {}", status); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperation.java index 99cbd34c9b..5aceb2ffd2 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperation.java @@ -20,16 +20,9 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import fj.data.Either; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Vertex; @@ -59,7 +52,6 @@ import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.be.resources.data.UserData; import org.openecomp.sdc.common.jsongraph.util.CommonUtility; import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; import org.openecomp.sdc.common.util.ValidationUtils; @@ -67,10 +59,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -import fj.data.Either; +import java.lang.reflect.Type; +import java.util.*; +import java.util.Map.Entry; public abstract class ToscaElementOperation extends BaseOperation { private static Logger log = LoggerFactory.getLogger(ToscaElementOperation.class.getName()); @@ -1074,13 +1065,15 @@ public abstract class ToscaElementOperation extends BaseOperation { return status; } - public Either, StorageOperationStatus> getElementCatalogData(ComponentTypeEnum componentType, ToscaElementTypeEnum toscaElement, boolean isHighestVersions) { + public Either, StorageOperationStatus> getElementCatalogData(ComponentTypeEnum componentType, List excludeTypes, boolean isHighestVersions) { Either, TitanOperationStatus> listOfComponents; if (isHighestVersions) { - listOfComponents = getListOfHighestComponents(componentType, toscaElement); - } else { - listOfComponents = getListOfHighestAndAllCertifiedComponents(componentType, toscaElement); + listOfComponents = getListOfHighestComponents(componentType, excludeTypes); } + else { + listOfComponents = getListOfHighestAndAllCertifiedComponents(componentType, excludeTypes); + } + if (listOfComponents.isRight() && listOfComponents.right().value() != TitanOperationStatus.NOT_FOUND) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(listOfComponents.right().value())); } @@ -1091,7 +1084,7 @@ public abstract class ToscaElementOperation extends BaseOperation { for (GraphVertex vertexComponent : highestAndAllCertified) { Either component = getLightComponent(vertexComponent, componentType, new ComponentParametersView(true)); if (component.isRight()) { - log.debug("Failed to fetch ligth element for {} error {}", vertexComponent.getUniqueId(), component.right().value()); + log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), component.right().value()); return Either.right(component.right().value()); } else { result.add(component.left().value()); @@ -1102,82 +1095,55 @@ public abstract class ToscaElementOperation extends BaseOperation { return Either.left(result); } - private Either, TitanOperationStatus> getListOfHighestComponents(ComponentTypeEnum componentType, ToscaElementTypeEnum toscaElement) { + private Either, TitanOperationStatus> getListOfHighestComponents(ComponentTypeEnum componentType, List excludeTypes) { Map propertiesToMatch = new HashMap<>(); + Map propertiesHasNotToMatch = new HashMap<>(); propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); if (componentType == ComponentTypeEnum.RESOURCE) { propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, false); + propertiesHasNotToMatch.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes); } - - Map propertiesHasNotToMatch = new HashMap<>(); propertiesHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - return titanDao.getByCriteria(ToscaElementTypeEnum.getVertexTypeByToscaType(toscaElement), propertiesToMatch, propertiesHasNotToMatch, JsonParseFlagEnum.ParseMetadata); + return titanDao.getByCriteria(null, propertiesToMatch, propertiesHasNotToMatch, JsonParseFlagEnum.ParseMetadata); } - public Either, TitanOperationStatus> getListOfHighestAndAllCertifiedComponents(ComponentTypeEnum componentType, ToscaElementTypeEnum toscaElement) { + // highest + (certified && !highest) + public Either, TitanOperationStatus> getListOfHighestAndAllCertifiedComponents(ComponentTypeEnum componentType, List excludeTypes) { long startFetchAllStates = System.currentTimeMillis(); + Either, TitanOperationStatus> highestNodes = getListOfHighestComponents(componentType, excludeTypes); + Map propertiesToMatchCertified = new HashMap<>(); + Map propertiesHasNotToMatchCertified = new HashMap<>(); propertiesToMatchCertified.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); propertiesToMatchCertified.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); if (componentType == ComponentTypeEnum.RESOURCE) { propertiesToMatchCertified.put(GraphPropertyEnum.IS_ABSTRACT, false); + propertiesHasNotToMatchCertified.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes); } - Map propertiesHasNotToMatchCertified = new HashMap<>(); propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_DELETED, true); + propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - Either, TitanOperationStatus> certifiedNodes = titanDao.getByCriteria(ToscaElementTypeEnum.getVertexTypeByToscaType(toscaElement), propertiesToMatchCertified, propertiesHasNotToMatchCertified, + Either, TitanOperationStatus> certifiedNotHighestNodes = titanDao.getByCriteria(null, propertiesToMatchCertified, propertiesHasNotToMatchCertified, JsonParseFlagEnum.ParseMetadata); - if (certifiedNodes.isRight() && certifiedNodes.right().value() != TitanOperationStatus.NOT_FOUND) { - return Either.right(certifiedNodes.right().value()); - } - - Map propertiesToMatchHighest = new HashMap<>(); - propertiesToMatchHighest.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - propertiesToMatchHighest.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); - if (componentType == ComponentTypeEnum.RESOURCE) { - propertiesToMatchHighest.put(GraphPropertyEnum.IS_ABSTRACT, false); - } - - Map propertiesHasNotToMatchHighest = new HashMap<>(); - propertiesHasNotToMatchHighest.put(GraphPropertyEnum.IS_DELETED, true); - propertiesHasNotToMatchHighest.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - - Either, TitanOperationStatus> highestNode = titanDao.getByCriteria(ToscaElementTypeEnum.getVertexTypeByToscaType(toscaElement), propertiesToMatchHighest, propertiesHasNotToMatchHighest, JsonParseFlagEnum.ParseMetadata); - if (highestNode.isRight() && highestNode.right().value() != TitanOperationStatus.NOT_FOUND) { - return Either.right(highestNode.right().value()); + if (certifiedNotHighestNodes.isRight() && certifiedNotHighestNodes.right().value() != TitanOperationStatus.NOT_FOUND) { + return Either.right(certifiedNotHighestNodes.right().value()); } long endFetchAllStates = System.currentTimeMillis(); List allNodes = new ArrayList<>(); - if (certifiedNodes.isLeft()) { - allNodes.addAll(certifiedNodes.left().value()); - } - if (highestNode.isLeft()) { - allNodes.addAll(highestNode.left().value()); - } - - int certifiedSize; - int nonCertifiedSize; - - if (certifiedNodes.isRight()) { - certifiedSize = 0; - } else { - certifiedSize = certifiedNodes.left().value().size(); + if (certifiedNotHighestNodes.isLeft()) { + allNodes.addAll(certifiedNotHighestNodes.left().value()); } - - if (highestNode.isRight()) { - nonCertifiedSize = 0; - } else { - nonCertifiedSize = highestNode.left().value().size(); + if (highestNodes.isLeft()) { + allNodes.addAll(highestNodes.left().value()); } - log.debug("Fetch catalog {}s all states: certified {}, noncertified {}", componentType, certifiedSize, nonCertifiedSize); log.debug("Fetch catalog {}s all states from graph took {} ms", componentType, endFetchAllStates - startFetchAllStates); return Either.left(allNodes); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacade.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacade.java index 8999340f0a..64424a8070 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacade.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacade.java @@ -21,9 +21,9 @@ package org.openecomp.sdc.be.model.jsontitan.operations; import java.util.*; +import fj.data.Either; import java.util.Map.Entry; import java.util.stream.Collectors; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; @@ -36,45 +36,11 @@ import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty; -import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; -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.DistributionStatusEnum; -import org.openecomp.sdc.be.model.GroupDefinition; -import org.openecomp.sdc.be.model.GroupInstance; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.PropertyDefinition; -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.User; +import org.openecomp.sdc.be.datatypes.elements.*; +import org.openecomp.sdc.be.datatypes.enums.*; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; @@ -88,2088 +54,2121 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import java.util.*; +import java.util.Map.Entry; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("tosca-operation-facade") public class ToscaOperationFacade { - @Autowired - private NodeTypeOperation nodeTypeOperation; - @Autowired - private TopologyTemplateOperation topologyTemplateOperation; - @Autowired - private NodeTemplateOperation nodeTemplateOperation; - @Autowired - private GroupsOperation groupsOperation; - @Autowired - private TitanDao titanDao; - - private static Logger log = LoggerFactory.getLogger(ToscaOperationFacade.class.getName()); - - public Either getToscaElement(String componentId) { + @Autowired + private NodeTypeOperation nodeTypeOperation; + @Autowired + private TopologyTemplateOperation topologyTemplateOperation; + @Autowired + private NodeTemplateOperation nodeTemplateOperation; + @Autowired + private GroupsOperation groupsOperation; + @Autowired + private TitanDao titanDao; + + private static Logger log = LoggerFactory.getLogger(ToscaOperationFacade.class.getName()); + + public Either getToscaElement(String componentId) { + + return getToscaElement(componentId, JsonParseFlagEnum.ParseAll); + + } + + public Either getToscaFullElement(String componentId) { + ComponentParametersView filters = new ComponentParametersView(); + filters.setIgnoreCapabiltyProperties(false); + + return getToscaElement(componentId, filters); + } + + public Either getToscaElement(String componentId, ComponentParametersView filters) { + + Either getVertexEither = titanDao.getVertexById(componentId, filters.detectParseFlag()); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + return getToscaElementByOperation(getVertexEither.left().value(), filters); + } + + public Either getToscaElement(String componentId, JsonParseFlagEnum parseFlag) { + + Either getVertexEither = titanDao.getVertexById(componentId, parseFlag); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + return getToscaElementByOperation(getVertexEither.left().value()); + } + + public Either getToscaElement(GraphVertex componentVertex) { + return getToscaElementByOperation(componentVertex); + } + + public Either validateComponentExists(String componentId) { + + Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + TitanOperationStatus status = getVertexEither.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + return Either.left(false); + } else { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + } + } + return Either.left(true); + } + + public Either findLastCertifiedToscaElementByUUID(T component) { + Map props = new HashMap<>(); + props.put(GraphPropertyEnum.UUID, component.getUUID()); + props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + Either, TitanOperationStatus> getVertexEither = titanDao.getByCriteria(ModelConverter.getVertexType(component), props); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", component.getUniqueId(), getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + return getToscaElementByOperation(getVertexEither.left().value().get(0)); + } + + private Either getToscaElementByOperation(GraphVertex componentV) { + return getToscaElementByOperation(componentV, new ComponentParametersView()); + } + + private Either getToscaElementByOperation(GraphVertex componentV, ComponentParametersView filters) { + VertexTypeEnum label = componentV.getLabel(); + + ToscaElementOperation toscaOperation = getToscaElementOperation(componentV); + Either toscaElement; + String componentId = componentV.getUniqueId(); + if (toscaOperation != null) { + log.debug("Need to fetch tosca element for id {}", componentId); + toscaElement = toscaOperation.getToscaElement(componentV, filters); + } else { + log.debug("not supported tosca type {} for id {}", label, componentId); + toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST); + } + if (toscaElement.isRight()) { + return Either.right(toscaElement.right().value()); + } + return Either.left(ModelConverter.convertFromToscaElement(toscaElement.left().value())); + } + + private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) { + VertexTypeEnum label = componentV.getLabel(); + switch (label) { + case NODE_TYPE: + return nodeTypeOperation; + case TOPOLOGY_TEMPLATE: + return topologyTemplateOperation; + default: + return null; + } + } + + /** + * + * @param resource + * @return + */ + public Either createToscaComponent(T resource) { + ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource); + + ToscaElementOperation toscaElementOperation = getToscaElementOperation(resource); + Either createToscaElement = toscaElementOperation.createToscaElement(toscaElement); + if (createToscaElement.isLeft()) { + log.debug("Component created successfully!!!"); + T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value()); + return Either.left(dataModel); + } + return Either.right(createToscaElement.right().value()); + } + + /** + * + * @param componentToDelete + * @return + */ + public StorageOperationStatus markComponentToDelete(Component componentToDelete) { + + if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) { + // component already marked for delete + return StorageOperationStatus.OK; + } else { + + Either getResponse = titanDao.getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll); + if (getResponse.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentToDelete.getUniqueId(), getResponse.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value()); + + } + GraphVertex componentV = getResponse.left().value(); + + // same operation for node type and topology template operations + Either result = nodeTypeOperation.markComponentToDelete(componentV); + if (result.isRight()) { + return result.right().value(); + } + return StorageOperationStatus.OK; + } + } + + /** + * + * @param componentId + * @return + */ + public Either deleteToscaComponent(String componentId) { + + Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + Either deleteElement = deleteToscaElement(getVertexEither.left().value()); + if (deleteElement.isRight()) { + log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value()); + return Either.right(deleteElement.right().value()); + } + T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value()); + + return Either.left(dataModel); + } + + private Either deleteToscaElement(GraphVertex componentV) { + VertexTypeEnum label = componentV.getLabel(); + Either toscaElement; + Object componentId = componentV.getUniqueId(); + switch (label) { + case NODE_TYPE: + log.debug("Need to fetch node type for id {}", componentId); + toscaElement = nodeTypeOperation.deleteToscaElement(componentV); + break; + case TOPOLOGY_TEMPLATE: + log.debug("Need to fetch topology template for id {}", componentId); + toscaElement = topologyTemplateOperation.deleteToscaElement(componentV); + break; + default: + log.debug("not supported tosca type {} for id {}", label, componentId); + toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST); + break; + } + return toscaElement; + } + + private ToscaElementOperation getToscaElementOperation(Component component) { + return ModelConverter.isAtomicComponent(component) ? nodeTypeOperation : topologyTemplateOperation; + } + + public Either getLatestByToscaResourceName(String toscaResourceName) { + return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName); + + } + + public Either getLatestByName(String resourceName) { + return getLatestByName(GraphPropertyEnum.NAME, resourceName); + + } + + public Either validateCsarUuidUniqueness(String csarUUID) { + Either, StorageOperationStatus> byCsar = null; + + Map properties = new HashMap(); + properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID); + + Either, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata); + + if (resources.isRight()) { + if (resources.right().value() == TitanOperationStatus.NOT_FOUND) { + return Either.left(new Integer(0)); + } else { + log.debug("failed to get resources from graph with property name: {}", csarUUID); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value())); + } + } + + List resourceList = (resources.isLeft() ? resources.left().value() : null); + + return Either.left(new Integer(resourceList.size())); + + } - return getToscaElement(componentId, JsonParseFlagEnum.ParseAll); - - } - - public Either getToscaFullElement(String componentId) { - ComponentParametersView filters = new ComponentParametersView(); - filters.setIgnoreCapabiltyProperties(false); + public Either, StorageOperationStatus> getFollowed(String userId, Set lifecycleStates, Set lastStateStates, ComponentTypeEnum componentType) { + Either, StorageOperationStatus> followedResources; + if (componentType == ComponentTypeEnum.RESOURCE) { + followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType); + } else { + followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType); + } - return getToscaElement(componentId, filters); - } + Set components = new HashSet<>(); + if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) { + return Either.right(followedResources.right().value()); + } + if (followedResources.isLeft()) { + List toscaElements = followedResources.left().value(); + toscaElements.forEach(te -> { + T component = ModelConverter.convertFromToscaElement(te); + components.add(component); + }); + } + return Either.left(components); + } + + public Either getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) { + + return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata); + } + + public Either getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) { + + Either result = null; + Map props = new HashMap(); + props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + Either, TitanOperationStatus> getLatestRes = titanDao.getByCriteria(vertexType, props, parseFlag); + + if (getLatestRes.isRight()) { + TitanOperationStatus status = getLatestRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + if (result == null) { + List resources = getLatestRes.left().value(); + double version = 0.0; + GraphVertex highestResource = null; + for (GraphVertex resource : resources) { + double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION)); + if (resourceVersion > version) { + version = resourceVersion; + highestResource = resource; + } + } + result = getToscaElement(highestResource.getUniqueId()); + } + return result; + } + + public Either validateToscaResourceNameExists(String templateName) { + Either validateUniquenessRes = validateToscaResourceNameUniqueness(templateName); + if (validateUniquenessRes.isLeft()) { + return Either.left(!validateUniquenessRes.left().value()); + } + return validateUniquenessRes; + } + + public Either dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { + return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef); + + } + + public StorageOperationStatus associateResourceInstances(String componentId, List relations) { + Either, StorageOperationStatus> status = nodeTemplateOperation.associateResourceInstances(componentId, relations); + if (status.isRight()) { + return status.right().value(); + } + return StorageOperationStatus.OK; + } + + protected Either validateToscaResourceNameUniqueness(String name) { + + Map properties = new HashMap(); + properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name); + + Either, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata); + + if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("failed to get resources from graph with property name: {}", name); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value())); + } + List resourceList = (resources.isLeft() ? resources.left().value() : null); + if (resourceList != null && resourceList.size() > 0) { + if (log.isDebugEnabled()) { + StringBuilder builder = new StringBuilder(); + for (GraphVertex resourceData : resourceList) { + builder.append(resourceData.getUniqueId() + "|"); + } + log.debug("resources with property name:{} exists in graph. found {}", name, builder.toString()); + } + return Either.left(false); + } else { + log.debug("resources with property name:{} does not exists in graph", name); + return Either.left(true); + } + + } + + /** + * + * @param newComponent + * @param oldComponent + * @return + */ + public Either overrideComponent(T newComponent, T oldComponent) { + + // TODO + // newComponent.setInterfaces(oldComponent.getInterfaces); + newComponent.setArtifacts(oldComponent.getArtifacts()); + newComponent.setDeploymentArtifacts(oldComponent.getDeploymentArtifacts()); + newComponent.setGroups(oldComponent.getGroups()); + newComponent.setInputs(null); + newComponent.setLastUpdateDate(null); + newComponent.setHighestVersion(true); + + Either componentVEither = titanDao.getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse); + if (componentVEither.isRight()) { + log.debug("Falied to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentVEither.right().value())); + } + GraphVertex componentv = componentVEither.left().value(); + Either parentVertexEither = titanDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); + if (parentVertexEither.isRight() && parentVertexEither.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("Falied to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertexEither.right().value())); + } + + Either deleteToscaComponent = deleteToscaElement(componentv); + if (deleteToscaComponent.isRight()) { + log.debug("Falied to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value()); + return Either.right(deleteToscaComponent.right().value()); + } + Either createToscaComponent = createToscaComponent(newComponent); + if (createToscaComponent.isRight()) { + log.debug("Falied to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value()); + return Either.right(createToscaComponent.right().value()); + } + T newElement = createToscaComponent.left().value(); + Either newVersionEither = titanDao.getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse); + if (newVersionEither.isRight()) { + log.debug("Falied to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(newVersionEither.right().value())); + } + if (parentVertexEither.isLeft()) { + GraphVertex previousVersionV = parentVertexEither.left().value(); + TitanOperationStatus createEdge = titanDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null); + if (createEdge != TitanOperationStatus.OK) { + log.debug("Falied to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge)); + } + } + return Either.left(newElement); + } + + /** + * + * @param componentToUpdate + * @return + */ + public Either updateToscaElement(T componentToUpdate) { + return updateToscaElement(componentToUpdate, new ComponentParametersView()); + } + + /** + * + * @param componentToUpdate + * @param type + * @param filterResult + * @return + */ + public Either updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) { + String componentId = componentToUpdate.getUniqueId(); + Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + } + GraphVertex elementV = getVertexEither.left().value(); + ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV); + + ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate); + Either updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult); + if (updateToscaElement.isRight()) { + log.debug("Failed to update tosca element {} error {}", componentId, updateToscaElement.right().value()); + return Either.right(updateToscaElement.right().value()); + } + return Either.left(ModelConverter.convertFromToscaElement(updateToscaElement.left().value())); + } + + private Either getLatestByName(GraphPropertyEnum property, String nodeName) { + Either result; + + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + + propertiesToMatch.put(property, nodeName); + propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + Either, TitanOperationStatus> highestResources = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata); + if (highestResources.isRight()) { + TitanOperationStatus status = highestResources.right().value(); + log.debug("failed to find resource with name {}. status={} ", nodeName, status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return result; + } + + List resources = highestResources.left().value(); + double version = 0.0; + GraphVertex highestResource = null; + for (GraphVertex vertex : resources) { + Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION); + double resourceVersion = Double.valueOf((String) versionObj); + if (resourceVersion > version) { + version = resourceVersion; + highestResource = vertex; + } + } + return getToscaElementByOperation(highestResource); + } + + public Either, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) { + + Either, StorageOperationStatus> result = null; + Either getComponentRes; + List components = new ArrayList<>(); + List componentVertices; + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + + propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName); + if (componentType != null) + propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + Either, TitanOperationStatus> getComponentsRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); + if (getComponentsRes.isRight()) { + TitanOperationStatus status = getComponentsRes.right().value(); + log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + if (result == null) { + componentVertices = getComponentsRes.left().value(); + for (GraphVertex componentVertex : componentVertices) { + getComponentRes = getToscaElementByOperation(componentVertex); + if (getComponentRes.isRight()) { + log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value()); + result = Either.right(getComponentRes.right().value()); + break; + } + T componentBySystemName = getComponentRes.left().value(); + log.debug("Found component, id: {}", componentBySystemName.getUniqueId()); + components.add(componentBySystemName); + } + } + if (result == null) { + result = Either.left(components); + } + return result; + } + + public Either getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) { + return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll); + } + + public Either getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) { + Either result; + + Map hasProperties = new EnumMap<>(GraphPropertyEnum.class); + Map hasNotProperties = new EnumMap<>(GraphPropertyEnum.class); + + hasProperties.put(GraphPropertyEnum.NAME, name); + hasProperties.put(GraphPropertyEnum.VERSION, version); + hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true); + if (componentType != null) { + hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + } + Either, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag); + if (getResourceRes.isRight()) { + TitanOperationStatus status = getResourceRes.right().value(); + log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return result; + } + return getToscaElementByOperation(getResourceRes.left().value().get(0)); + } + + public Either, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, List excludeTypes, boolean isHighestVersions) { + List components = new ArrayList<>(); + Either, StorageOperationStatus> catalogDataResult; + List toscaElements = new ArrayList<>(); + List excludedResourceTypes = + Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()) + .stream() + .filter(type -> !type.equals(OriginTypeEnum.SERVICE)) + .map(type -> ResourceTypeEnum.getTypeByName(type.name())).collect(Collectors.toList()); + + switch (componentType) { + case RESOURCE: + catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE,excludedResourceTypes , isHighestVersions); + if (catalogDataResult.isRight()) { + return Either.right(catalogDataResult.right().value()); + } + toscaElements = catalogDataResult.left().value(); + break; + case SERVICE: + if (excludeTypes!= null && excludeTypes.contains(OriginTypeEnum.SERVICE)) { + break; + } + catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, isHighestVersions); + if (catalogDataResult.isRight()) { + return Either.right(catalogDataResult.right().value()); + } + toscaElements = catalogDataResult.left().value(); + break; + default: + log.debug("Not supported component type {}", componentType); + return Either.right(StorageOperationStatus.BAD_REQUEST); + } + toscaElements.forEach(te -> { + T component = ModelConverter.convertFromToscaElement(te); + components.add(component); + }); + return Either.left(components); + } + + public Either, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) { + Either, StorageOperationStatus> allComponentsMarkedForDeletion; + List deleted = new ArrayList<>(); + switch (componentType) { + case RESOURCE: + allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType); + break; + case SERVICE: + case PRODUCT: + allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType); + break; + default: + log.debug("Not supported component type {}", componentType); + return Either.right(StorageOperationStatus.BAD_REQUEST); + } + if (allComponentsMarkedForDeletion.isRight()) { + return Either.right(allComponentsMarkedForDeletion.right().value()); + } + List allMarked = allComponentsMarkedForDeletion.left().value(); + + Either, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements(); + if (allNotDeletedElements.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value())); + } + List allNonMarked = allNotDeletedElements.left().value(); + for (GraphVertex elementV : allMarked) { + if (topologyTemplateOperation.isInUse(elementV, allNonMarked) == false) { + Either deleteToscaElement = deleteToscaElement(elementV); + if (deleteToscaElement.isRight()) { + log.debug("Failed to delete marked element {} error {}", elementV.getUniqueId(), deleteToscaElement.right().value()); + } + } else { + deleted.add(elementV.getUniqueId()); + log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId()); + } + } + return Either.left(deleted); + } + + public Either, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) { + Either, StorageOperationStatus> allComponentsMarkedForDeletion; + switch (componentType) { + case RESOURCE: + allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType); + break; + case SERVICE: + case PRODUCT: + allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType); + break; + default: + log.debug("Not supported component type {}", componentType); + return Either.right(StorageOperationStatus.BAD_REQUEST); + } + if (allComponentsMarkedForDeletion.isRight()) { + return Either.right(allComponentsMarkedForDeletion.right().value()); + } + return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(v -> v.getUniqueId()).collect(Collectors.toList())); + } + + public Either isComponentInUse(String componentId) { + Either result; + Either, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements(); + if (allNotDeletedElements.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value())); + } else { + result = Either.left(topologyTemplateOperation.isInUse(componentId, allNotDeletedElements.left().value())); + } + return result; + } + + public Either, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) { + + Either, StorageOperationStatus> result = null; + Either updateContainerComponentRes = null; + componentInstance.setIcon(origComponent.getIcon()); + Either, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), + ModelConverter.convertToToscaElement(origComponent), getNextComponentInstanceCounter(containerComponent, origComponent.getName()), componentInstance, allowDeleted, user); + + if (addResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName()); + result = Either.right(addResult.right().value()); + } + if (result == null) { + updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId()); + if (updateContainerComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName()); + result = Either.right(updateContainerComponentRes.right().value()); + } + } + if (result == null) { + Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value()); + String createdInstanceId = addResult.left().value().getRight(); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName()); + result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId)); + } + return result; + } + + public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map resourcesInstancesMap, boolean allowDeleted) { + + StorageOperationStatus result = null; + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId()); + + Either metadataVertex = titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll); + if (metadataVertex.isRight()) { + TitanOperationStatus status = metadataVertex.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + if (result == null) { + result = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted); + } + return result; + } + + public Either, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) { + + Either, StorageOperationStatus> result = null; + + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName()); + componentInstance.setIcon(origComponent.getIcon()); + Either, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), + ModelConverter.convertToToscaElement(origComponent), componentInstance); + if (updateResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName()); + result = Either.right(updateResult.right().value()); + } + if (result == null) { + Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft()); + String createdInstanceId = updateResult.left().value().getRight(); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName()); + result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId)); + } + return result; + } + + public Either updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) { + + Either result = null; + + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName()); + + Either updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent)); + if (updateResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ", containerComponent.getName()); + result = Either.right(updateResult.right().value()); + } + if (result == null) { + Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value()); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName()); + result = Either.left(updatedComponent); + } + return result; + } + + public Either, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) { + + Either, StorageOperationStatus> result = null; + + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName()); + + Either, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId); + if (updateResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName()); + result = Either.right(updateResult.right().value()); + } + if (result == null) { + Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft()); + String deletedInstanceId = updateResult.left().value().getRight(); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName()); + result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId)); + } + return result; + } + + private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) { + + Integer nextCounter = 0; + + if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) { + + String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName); + Integer maxCounterFromNames = getMaxCounterFromNames(containerComponent, normalizedName); + Integer maxCounterFromIds = getMaxCounterFromIds(containerComponent, normalizedName); + + if (maxCounterFromNames == null && maxCounterFromIds != null) { + nextCounter = maxCounterFromIds + 1; + } else if (maxCounterFromIds == null && maxCounterFromNames != null) { + nextCounter = maxCounterFromNames + 1; + } else if (maxCounterFromIds != null && maxCounterFromNames != null) { + nextCounter = maxCounterFromNames > maxCounterFromIds ? maxCounterFromNames + 1 : maxCounterFromIds + 1; + } + } + return nextCounter.toString(); + } + + private Integer getMaxCounterFromNames(Component containerComponent, String normalizedName) { + + Integer maxCounter = 0; + List countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName)).map(ci -> ci.getNormalizedName().split(normalizedName)[1]) + .collect(Collectors.toList()); + + if (CollectionUtils.isEmpty(countersStr)) { + return null; + } + Integer currCounter = null; + for (String counter : countersStr) { + if (StringUtils.isEmpty(counter)) { + continue; + } + try { + currCounter = Integer.parseInt(counter); + } catch (Exception e) { + continue; + } + maxCounter = maxCounter < currCounter ? currCounter : maxCounter; + } + if (currCounter == null) { + return null; + } + return maxCounter; + } + + private Integer getMaxCounterFromIds(Component containerComponent, String normalizedName) { + + Integer maxCounter = 0; + List countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName)).map(ci -> ci.getUniqueId().split(normalizedName)[1]) + .collect(Collectors.toList()); + + if (CollectionUtils.isEmpty(countersStr)) { + return null; + } + Integer currCounter = null; + for (String counter : countersStr) { + if (StringUtils.isEmpty(counter)) { + continue; + } + try { + currCounter = Integer.parseInt(counter); + } catch (Exception e) { + continue; + } + maxCounter = maxCounter < currCounter ? currCounter : maxCounter; + } + if (currCounter == null) { + return null; + } + return maxCounter; + } + + public Either associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { + return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef); + + } + + public Either, StorageOperationStatus> createAndAssociateInputs(Map inputs, String componentId) { + + Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + + GraphVertex vertex = getVertexEither.left().value(); + Map inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue()))); + + StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId); + + if (StorageOperationStatus.OK == status) { + log.debug("Component created successfully!!!"); + List inputsResList = null; + if (inputsMap != null && !inputsMap.isEmpty()) { + inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList()); + } + return Either.left(inputsResList); + } + return Either.right(status); + + } + + public Either, StorageOperationStatus> addInputsToComponent(Map inputs, String componentId) { + + Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + + GraphVertex vertex = getVertexEither.left().value(); + Map inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue()))); + + StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME); + + if (StorageOperationStatus.OK == status) { + log.debug("Component created successfully!!!"); + List inputsResList = null; + if (inputsMap != null && !inputsMap.isEmpty()) { + inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList()); + } + return Either.left(inputsResList); + } + return Either.right(status); + + } + + public Either>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map> instProperties, String componentId) { + + Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + + GraphVertex vertex = getVertexEither.left().value(); + Map instPropsMap = new HashMap<>(); + if (instProperties != null) { - public Either getToscaElement(String componentId, ComponentParametersView filters) { + MapPropertiesDataDefinition propertiesMap; + for (Entry> entry : instProperties.entrySet()) { + propertiesMap = new MapPropertiesDataDefinition(); - Either getVertexEither = titanDao.getVertexById(componentId, filters.detectParseFlag()); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e))); + + instPropsMap.put(entry.getKey(), propertiesMap); + } + } + + StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap); - } - return getToscaElementByOperation(getVertexEither.left().value(), filters); - } + if (StorageOperationStatus.OK == status) { + log.debug("Component created successfully!!!"); + return Either.left(instProperties); + } + return Either.right(status); - public Either getToscaElement(String componentId, JsonParseFlagEnum parseFlag) { + } + public Either>, StorageOperationStatus> associateComponentInstanceInputsToComponent(Map> instInputs, String componentId) { - Either getVertexEither = titanDao.getVertexById(componentId, parseFlag); + Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); if (getVertexEither.isRight()) { log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); } - return getToscaElementByOperation(getVertexEither.left().value()); - } + GraphVertex vertex = getVertexEither.left().value(); + Map instPropsMap = new HashMap<>(); + if (instInputs != null) { - public Either getToscaElement(GraphVertex componentVertex) { - return getToscaElementByOperation(componentVertex); - } + MapPropertiesDataDefinition propertiesMap; + for (Entry> entry : instInputs.entrySet()) { + propertiesMap = new MapPropertiesDataDefinition(); - public Either validateComponentExists(String componentId) { + propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e))); - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - TitanOperationStatus status = getVertexEither.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - return Either.left(false); - } else { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + instPropsMap.put(entry.getKey(), propertiesMap); } } - return Either.left(true); - } - - public Either findLastCertifiedToscaElementByUUID(T component) { - Map props = new HashMap<>(); - props.put(GraphPropertyEnum.UUID, component.getUUID()); - props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - - Either, TitanOperationStatus> getVertexEither = titanDao.getByCriteria(ModelConverter.getVertexType(component), props); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", component.getUniqueId(), getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - return getToscaElementByOperation(getVertexEither.left().value().get(0)); - } - - private Either getToscaElementByOperation(GraphVertex componentV) { - return getToscaElementByOperation(componentV, new ComponentParametersView()); - } - - private Either getToscaElementByOperation(GraphVertex componentV, ComponentParametersView filters) { - VertexTypeEnum label = componentV.getLabel(); - - ToscaElementOperation toscaOperation = getToscaElementOperation(componentV); - Either toscaElement; - String componentId = componentV.getUniqueId(); - if (toscaOperation != null) { - log.debug("Need to fetch tosca element for id {}", componentId); - toscaElement = toscaOperation.getToscaElement(componentV, filters); - } else { - log.debug("not supported tosca type {} for id {}", label, componentId); - toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST); - } - if (toscaElement.isRight()) { - return Either.right(toscaElement.right().value()); - } - return Either.left(ModelConverter.convertFromToscaElement(toscaElement.left().value())); - } - private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) { - VertexTypeEnum label = componentV.getLabel(); - switch (label) { - case NODE_TYPE: - return nodeTypeOperation; - case TOPOLOGY_TEMPLATE: - return topologyTemplateOperation; - default: - return null; - } - } + StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap); - /** - * - * @param resource - * @return - */ - public Either createToscaComponent(T resource) { - ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource); - - ToscaElementOperation toscaElementOperation = getToscaElementOperation(toscaElement); - Either createToscaElement = toscaElementOperation.createToscaElement(toscaElement); - if (createToscaElement.isLeft()) { + if (StorageOperationStatus.OK == status) { log.debug("Component created successfully!!!"); - T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value()); - return Either.left(dataModel); - } - return Either.right(createToscaElement.right().value()); - } - - /** - * - * @param componentToDelete - * @return - */ - public StorageOperationStatus markComponentToDelete(Component componentToDelete) { - - if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) { - // component already marked for delete - return StorageOperationStatus.OK; - } else { - - Either getResponse = titanDao.getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll); - if (getResponse.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentToDelete.getUniqueId(), getResponse.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value()); - - } - GraphVertex componentV = getResponse.left().value(); - - // same operation for node type and topology template operations - Either result = nodeTypeOperation.markComponentToDelete(componentV); - if (result.isRight()) { - return result.right().value(); - } - return StorageOperationStatus.OK; - } - } - - /** - * - * @param componentId - * @return - */ - public Either deleteToscaComponent(String componentId) { - - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - Either deleteElement = deleteToscaElement(getVertexEither.left().value()); - if (deleteElement.isRight()) { - log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value()); - return Either.right(deleteElement.right().value()); + return Either.left(instInputs); } - T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value()); - - return Either.left(dataModel); - } - - private Either deleteToscaElement(GraphVertex componentV) { - VertexTypeEnum label = componentV.getLabel(); - Either toscaElement; - Object componentId = componentV.getUniqueId(); - switch (label) { - case NODE_TYPE: - log.debug("Need to fetch node type for id {}", componentId); - toscaElement = nodeTypeOperation.deleteToscaElement(componentV); - break; - case TOPOLOGY_TEMPLATE: - log.debug("Need to fetch topology template for id {}", componentId); - toscaElement = topologyTemplateOperation.deleteToscaElement(componentV); - break; - default: - log.debug("not supported tosca type {} for id {}", label, componentId); - toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST); - break; - } - return toscaElement; - } - - private ToscaElementOperation getToscaElementOperation(ToscaElement toscaElement) { - - ComponentTypeEnum componentType = toscaElement.getComponentType(); - switch (componentType) { - case RESOURCE: - ResourceTypeEnum resourceType = toscaElement.getResourceType(); - if (resourceType == ResourceTypeEnum.VF) { - return topologyTemplateOperation; - } else { - return nodeTypeOperation; - } - case SERVICE: - case PRODUCT: - return topologyTemplateOperation; - default: - break; - } - return null; - } - - private ToscaElementOperation getToscaElementOperation(Component component) { - - switch (component.getComponentType()) { - case RESOURCE: - ResourceTypeEnum resourceType = ((Resource) component).getResourceType(); - if (resourceType != null && resourceType == ResourceTypeEnum.VF) { - return topologyTemplateOperation; - } else { - return nodeTypeOperation; - } - case SERVICE: - case PRODUCT: - return topologyTemplateOperation; - default: - break; - } - return null; - } - - public Either getLatestByToscaResourceName(String toscaResourceName) { - return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName); - - } - - public Either getLatestByName(String resourceName) { - return getLatestByName(GraphPropertyEnum.NAME, resourceName); + return Either.right(status); } + public Either>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map> instProperties) { + + StorageOperationStatus status = StorageOperationStatus.OK; + if (instProperties != null) { + + for (Entry> entry : instProperties.entrySet()) { + List props = entry.getValue(); + String componentInstanseId = entry.getKey(); + if (props != null && !props.isEmpty()) { + for (ComponentInstanceInput property : props) { + List componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanseId); + Optional instanceProperty = componentInstancesInputs.stream().filter(p -> p.getName().equals(property.getName())).findAny(); + if (instanceProperty.isPresent()) { + status = updateComponentInstanceInput(containerComponent, componentInstanseId, property); + } else { + status = addComponentInstanceInput(containerComponent, componentInstanseId, property); + } + if (status != StorageOperationStatus.OK) { + log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanseId, status); + return Either.right(status); + } else { + log.trace("instance input {} for instance {} updated", property, componentInstanseId); + } + } + } + } + } + return Either.left(instProperties); + } + + public StorageOperationStatus deleteComponentInstanceInputsToComponent(Map> instProperties, String componentId) { - public Either validateCsarUuidUniqueness(String csarUUID) { - Either, StorageOperationStatus> byCsar = null; - - Map properties = new HashMap(); - properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID); - - Either, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata); - - if (resources.isRight()) { - if (resources.right().value() == TitanOperationStatus.NOT_FOUND) { - return Either.left(new Integer(0)); - } else { - log.debug("failed to get resources from graph with property name: {}", csarUUID); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value())); - } - } + Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); - List resourceList = (resources.isLeft() ? resources.left().value() : null); + } - return Either.left(new Integer(resourceList.size())); + GraphVertex vertex = getVertexEither.left().value(); + Map instPropsMap = new HashMap<>(); + if (instProperties != null) { - } + MapPropertiesDataDefinition propertiesMap; + for (Entry> entry : instProperties.entrySet()) { + propertiesMap = new MapPropertiesDataDefinition(); - public Either, StorageOperationStatus> getFollowed(String userId, Set lifecycleStates, Set lastStateStates, ComponentTypeEnum componentType) { - Either, StorageOperationStatus> followedResources; - if (componentType == ComponentTypeEnum.RESOURCE) { - followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType); - } else { - followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType); - } + propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e))); - Set components = new HashSet<>(); - if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) { - return Either.right(followedResources.right().value()); - } - if (followedResources.isLeft()) { - List toscaElements = followedResources.left().value(); - toscaElements.forEach(te -> { - T component = ModelConverter.convertFromToscaElement(te); - components.add(component); - }); - } - return Either.left(components); - } + instPropsMap.put(entry.getKey(), propertiesMap); + } + } - public Either getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) { + return topologyTemplateOperation.deleteInstInputsToComponent(vertex, instPropsMap); - return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata); - } + } - public Either getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) { + public Either>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map> instProperties, String componentId) { - Either result = null; - Map props = new HashMap(); - props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - Either, TitanOperationStatus> getLatestRes = titanDao.getByCriteria(vertexType, props, parseFlag); + StorageOperationStatus status = StorageOperationStatus.OK; + if (instProperties != null) { - if (getLatestRes.isRight()) { - TitanOperationStatus status = getLatestRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - if (result == null) { - List resources = getLatestRes.left().value(); - double version = 0.0; - GraphVertex highestResource = null; - for (GraphVertex resource : resources) { - double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION)); - if (resourceVersion > version) { - version = resourceVersion; - highestResource = resource; - } - } - result = getToscaElement(highestResource.getUniqueId()); - } - return result; - } + for (Entry> entry : instProperties.entrySet()) { + List props = entry.getValue(); + String componentInstanseId = entry.getKey(); + List instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanseId); + if (props != null && !props.isEmpty()) { + for (ComponentInstanceProperty property : props) { + Optional instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); + if (instanceProperty.isPresent()) { + status = updateComponentInstanceProperty(containerComponent, componentInstanseId, property); + } else { + status = addComponentInstanceProperty(containerComponent, componentInstanseId, property); + } - public Either validateToscaResourceNameExists(String templateName) { - Either validateUniquenessRes = validateToscaResourceNameUniqueness(templateName); - if (validateUniquenessRes.isLeft()) { - return Either.left(!validateUniquenessRes.left().value()); - } - return validateUniquenessRes; - } + } + } + } + } - public Either dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { - return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef); + return Either.left(instProperties); - } + } - public StorageOperationStatus associateResourceInstances(String componentId, List relations) { - Either, StorageOperationStatus> status = nodeTemplateOperation.associateResourceInstances(componentId, relations); - if (status.isRight()) { - return status.right().value(); - } - return StorageOperationStatus.OK; - } + public StorageOperationStatus associateArtifactToInstances(Map> instArtifacts, String componentId, User user) { - protected Either validateToscaResourceNameUniqueness(String name) { + Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); - Map properties = new HashMap(); - properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name); + } - Either, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata); + GraphVertex vertex = getVertexEither.left().value(); + Map instArtMap = new HashMap<>(); + if (instArtifacts != null) { - if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("failed to get resources from graph with property name: {}", name); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value())); - } - List resourceList = (resources.isLeft() ? resources.left().value() : null); - if (resourceList != null && resourceList.size() > 0) { - if (log.isDebugEnabled()) { - StringBuilder builder = new StringBuilder(); - for (GraphVertex resourceData : resourceList) { - builder.append(resourceData.getUniqueId() + "|"); - } - log.debug("resources with property name:{} exists in graph. found {}", name, builder.toString()); - } - return Either.left(false); - } else { - log.debug("resources with property name:{} does not exists in graph", name); - return Either.left(true); - } + MapArtifactDataDefinition artifactsMap; + for (Entry> entry : instArtifacts.entrySet()) { + Map artList = entry.getValue(); + Map artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME); - } + instArtMap.put(entry.getKey(), artifactsMap); + } + } + + return topologyTemplateOperation.associateInstArtifactToComponent(vertex, instArtMap); + + } + + public StorageOperationStatus associateInstAttributeToComponentToInstances(Map> instArttributes, String componentId) { + + Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); - /** - * - * @param newComponent - * @param oldComponent - * @return - */ - public Either overrideComponent(T newComponent, T oldComponent) { - - // TODO - // newComponent.setInterfaces(oldComponent.getInterfaces); - newComponent.setArtifacts(oldComponent.getArtifacts()); - newComponent.setDeploymentArtifacts(oldComponent.getDeploymentArtifacts()); - newComponent.setGroups(oldComponent.getGroups()); - newComponent.setInputs(null); - newComponent.setLastUpdateDate(null); - newComponent.setHighestVersion(true); - - Either componentVEither = titanDao.getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse); - if (componentVEither.isRight()) { - log.debug("Falied to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentVEither.right().value())); - } - GraphVertex componentv = componentVEither.left().value(); - Either parentVertexEither = titanDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); - if (parentVertexEither.isRight() && parentVertexEither.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("Falied to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertexEither.right().value())); - } + } - Either deleteToscaComponent = deleteToscaElement(componentv); - if (deleteToscaComponent.isRight()) { - log.debug("Falied to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value()); - return Either.right(deleteToscaComponent.right().value()); - } - Either createToscaComponent = createToscaComponent(newComponent); - if (createToscaComponent.isRight()) { - log.debug("Falied to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value()); - return Either.right(createToscaComponent.right().value()); - } - T newElement = createToscaComponent.left().value(); - Either newVersionEither = titanDao.getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse); - if (newVersionEither.isRight()) { - log.debug("Falied to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(newVersionEither.right().value())); - } - if (parentVertexEither.isLeft()) { - GraphVertex previousVersionV = parentVertexEither.left().value(); - TitanOperationStatus createEdge = titanDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null); - if (createEdge != TitanOperationStatus.OK) { - log.debug("Falied to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge)); - } - } - return Either.left(newElement); - } + GraphVertex vertex = getVertexEither.left().value(); + Map instAttr = new HashMap<>(); + if (instArttributes != null) { - /** - * - * @param componentToUpdate - * @return - */ - public Either updateToscaElement(T componentToUpdate) { - return updateToscaElement(componentToUpdate, new ComponentParametersView()); - } + MapPropertiesDataDefinition attributesMap; + for (Entry> entry : instArttributes.entrySet()) { + attributesMap = new MapPropertiesDataDefinition(); + attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e))); + instAttr.put(entry.getKey(), attributesMap); + } + } - /** - * - * @param componentToUpdate - * @param type - * @param filterResult - * @return - */ - public Either updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) { - String componentId = componentToUpdate.getUniqueId(); - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - } - GraphVertex elementV = getVertexEither.left().value(); - ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV); - - ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate); - Either updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult); - if (updateToscaElement.isRight()) { - log.debug("Failed to update tosca element {} error {}", componentId, updateToscaElement.right().value()); - return Either.right(updateToscaElement.right().value()); - } - return Either.left(ModelConverter.convertFromToscaElement(updateToscaElement.left().value())); - } + return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr); - private Either getLatestByName(GraphPropertyEnum property, String nodeName) { - Either result; + } - Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + public StorageOperationStatus associateCalculatedCapReq(Map>> instCapabilties, Map>> instReg, String componentId) { + Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); - propertiesToMatch.put(property, nodeName); - propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + } - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + GraphVertex vertex = getVertexEither.left().value(); - Either, TitanOperationStatus> highestResources = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata); - if (highestResources.isRight()) { - TitanOperationStatus status = highestResources.right().value(); - log.debug("failed to find resource with name {}. status={} ", nodeName, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } + Map calcRequirements = new HashMap<>(); - List resources = highestResources.left().value(); - double version = 0.0; - GraphVertex highestResource = null; - for (GraphVertex vertex : resources) { - Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION); - double resourceVersion = Double.valueOf((String) versionObj); - if (resourceVersion > version) { - version = resourceVersion; - highestResource = vertex; - } - } - return getToscaElementByOperation(highestResource); - } + Map calcCapabilty = new HashMap<>(); + Map calculatedCapabilitiesProperties = new HashMap<>(); + ; + if (instCapabilties != null) { + for (Entry>> entry : instCapabilties.entrySet()) { - public Either, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) { + Map> caps = entry.getValue(); + Map mapToscaDataDefinition = new HashMap<>(); + for (Entry> instCapability : caps.entrySet()) { + mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(iCap -> new CapabilityDataDefinition(iCap)).collect(Collectors.toList()))); + } + + ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey()); + MapListCapabiltyDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance); + + MapCapabiltyProperty mapCapabiltyProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true); + + calcCapabilty.put(entry.getKey().getUniqueId(), capMap); + calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabiltyProperty); + } + } + + if (instReg != null) { + for (Entry>> entry : instReg.entrySet()) { + + Map> req = entry.getValue(); + Map mapToscaDataDefinition = new HashMap<>(); + for (Entry> instReq : req.entrySet()) { + mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(iCap -> new RequirementDataDefinition(iCap)).collect(Collectors.toList()))); + } + + MapListRequirementDataDefinition capMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey())); + + calcRequirements.put(entry.getKey().getUniqueId(), capMap); + } + } + + StorageOperationStatus status = topologyTemplateOperation.associateCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties); + + return status; + } + + private Either, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) { + + Map hasProps = new EnumMap<>(GraphPropertyEnum.class); + Map hasNotProps = new EnumMap<>(GraphPropertyEnum.class); + + fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType); + + Either, TitanOperationStatus> getRes = titanDao.getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata); + if (getRes.isRight()) { + if (getRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { + return Either.left(new ArrayList<>()); + } else { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); + } + } else { + List nonAbstractLatestComponents = new ArrayList<>(); + ComponentParametersView params = new ComponentParametersView(true); + params.setIgnoreAllVersions(false); + for (GraphVertex vertexComponent : getRes.left().value()) { + Either componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params); + if (componentRes.isRight()) { + log.debug("Failed to fetch ligth element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value()); + return Either.right(componentRes.right().value()); + } else { + Component component = ModelConverter.convertFromToscaElement(componentRes.left().value()); + + nonAbstractLatestComponents.add(component); + } + } + + return Either.left(nonAbstractLatestComponents); + } + } + + public Either getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) { + + Either result; + + Map hasProperties = new EnumMap<>(GraphPropertyEnum.class); + + hasProperties.put(GraphPropertyEnum.UUID, componentUuid); + if (isHighest != null) { + hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue()); + } + + Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + Either, TitanOperationStatus> getRes = titanDao.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag); + if (getRes.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); + } else { + List latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList()); + ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0) + : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get(); + result = Either.left(latestVersion); + } + return result; + } + + public Either getComponentMetadata(String componentId) { + + Either result; + Either getRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata); + if (getRes.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); + } else { + ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value()); + result = Either.left(componentMetadata); + } + return result; + } + + private Map findLatestVersion(List resourceDataList) { + Map, ComponentMetadataData> latestVersionMap = new HashMap, ComponentMetadataData>(); + for (ComponentMetadataData resourceData : resourceDataList) { + ComponentMetadataData latestVersionData = resourceData; + + ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition(); + Pair pair = createKeyPair(latestVersionData); + if (latestVersionMap.containsKey(pair)) { + latestVersionData = latestVersionMap.get(pair); + String currentVersion = latestVersionData.getMetadataDataDefinition().getVersion(); + String newVersion = metadataDataDefinition.getVersion(); + if (CommonBeUtils.compareAsdcComponentVersions(newVersion, currentVersion)) { + latestVersionData = resourceData; + } + } + if (log.isDebugEnabled()) + log.debug("last certified version of resource = {} version is {}", latestVersionData.getMetadataDataDefinition().getName(), latestVersionData.getMetadataDataDefinition().getVersion()); + + latestVersionMap.put(pair, latestVersionData); + } + + Map resVersionMap = new HashMap(); + for (ComponentMetadataData resourceData : latestVersionMap.values()) { + ComponentMetadataData latestVersionData = resourceData; + ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition(); + if (resVersionMap.containsKey(metadataDataDefinition.getUUID())) { + latestVersionData = resVersionMap.get(metadataDataDefinition.getUUID()); + String currentVersion = latestVersionData.getMetadataDataDefinition().getVersion(); + String newVersion = metadataDataDefinition.getVersion(); + if (CommonBeUtils.compareAsdcComponentVersions(newVersion, currentVersion)) { + latestVersionData = resourceData; + } + } + if (log.isDebugEnabled()) + log.debug("last uuid version of resource = {} version is {}", latestVersionData.getMetadataDataDefinition().getName(), latestVersionData.getMetadataDataDefinition().getVersion()); + resVersionMap.put(latestVersionData.getMetadataDataDefinition().getUUID(), latestVersionData); + } + + return resVersionMap; + } + + private Pair createKeyPair(ComponentMetadataData metadataData) { + Pair pair; + NodeTypeEnum label = NodeTypeEnum.getByName(metadataData.getLabel()); + switch (label) { + case Resource: + pair = new ImmutablePair<>(metadataData.getMetadataDataDefinition().getName(), ((ResourceMetadataDataDefinition) metadataData.getMetadataDataDefinition()).getResourceType().name()); + break; + default: + pair = new ImmutablePair<>(metadataData.getMetadataDataDefinition().getName(), metadataData.getLabel()); + break; + } + + return pair; + } + + public Either, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List componentUids) { + + Either, StorageOperationStatus> result = null; + List components = new ArrayList<>(); + if (componentUids == null) { + Either, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, isHighest, componentTypeEnum, internalComponentType, componentUids); + if (componentUidsRes.isRight()) { + result = Either.right(componentUidsRes.right().value()); + } else { + componentUids = componentUidsRes.left().value(); + } + } + if (!componentUids.isEmpty()) { + for (String componentUid : componentUids) { + ComponentParametersView componentParametersView = buildComponentViewForNotAbstract(); + if (internalComponentType != null && "vl".equalsIgnoreCase(internalComponentType)) { + componentParametersView.setIgnoreCapabilities(false); + componentParametersView.setIgnoreRequirements(false); + } + Either getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView); + if (getToscaElementRes.isRight()) { + if (log.isDebugEnabled()) + log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value()); + result = Either.right(getToscaElementRes.right().value()); + break; + } + Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value()); + component.setContactId(null); + component.setCreationDate(null); + component.setCreatorUserId(null); + component.setCreatorFullName(null); + component.setLastUpdateDate(null); + component.setLastUpdaterUserId(null); + component.setLastUpdaterFullName(null); + component.setNormalizedName(null); + components.add(component); + } + } + if (result == null) { + result = Either.left(components); + } + return result; + } + + private Either, StorageOperationStatus> getComponentUids(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List componentUids) { + + Either, StorageOperationStatus> result = null; + Either, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType); + if (getToscaElementsRes.isRight()) { + result = Either.right(getToscaElementsRes.right().value()); + } else { + List collection = getToscaElementsRes.left().value(); + if (collection == null) { + componentUids = new ArrayList<>(); + } else { + componentUids = collection.stream().map(p -> p.getUniqueId()).collect(Collectors.toList()); + } + } + if (result == null) { + result = Either.left(componentUids); + } + return result; + } + + private ComponentParametersView buildComponentViewForNotAbstract() { + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreCategories(false); + componentParametersView.setIgnoreAllVersions(false); + return componentParametersView; + } + + public Either validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) { + Either result = validateComponentNameUniqueness(name, resourceType, componentType); + if (result.isLeft()) { + result = Either.left(!result.left().value()); + } + return result; + } + + public Either validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) { + VertexTypeEnum vertexType = ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE; + String normalizedName = ValidationUtils.normaliseComponentName(name); + Map properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName); + properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + + Either, TitanOperationStatus> vertexEither = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse); + if (vertexEither.isRight() && vertexEither.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value())); + } + List vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null; + if (vertexList != null && !vertexList.isEmpty()) { + return Either.left(false); + } else { + return Either.left(true); + } + } + + + private void fillNodeTypePropsMap(Map hasProps, Map hasNotProps, String internalComponentType) { + switch (internalComponentType.toLowerCase()) { + case "vf": + case "cvfc": + hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VFCMT.name()); + break; + case "service": + case "pnf" : + hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFC.name(), ResourceTypeEnum.VFCMT.name())); + break; + case "vl": + hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VL.name()); + break; + default: + break; + } + } + + + private void fillTopologyTemplatePropsMap(Map hasProps, Map hasNotProps, ComponentTypeEnum componentTypeEnum, String internalComponentType) { + switch (componentTypeEnum) { + case RESOURCE: + hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + break; + case SERVICE: + hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + break; + default: + break; + } + switch (internalComponentType.toLowerCase()) { + case "vf": + case "cvfc": + hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name()); + break; + case "service": + hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name()); + break; + default: + break; + } + } + + private void fillPropsMap(Map hasProps, Map hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) { + hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); + + hasNotProps.put(GraphPropertyEnum.IS_DELETED, true); + hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + if (VertexTypeEnum.NODE_TYPE == internalVertexType) { + hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract); + if (internalComponentType != null) { + fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType); + } + } else { + fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum, internalComponentType); + } + } + + private List getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) { + List internalVertexTypes = new ArrayList<>(); + if (ComponentTypeEnum.RESOURCE == componentTypeEnum) { + internalVertexTypes.add(VertexTypeEnum.NODE_TYPE); + } + if (ComponentTypeEnum.SERVICE == componentTypeEnum || "service".equalsIgnoreCase(internalComponentType) || "vf".equalsIgnoreCase(internalComponentType)) { + internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE); + } + return internalVertexTypes; + } + + public Either, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType) { + List internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType); + List result = new ArrayList<>(); + for (VertexTypeEnum vertexType : internalVertexTypes) { + Either, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType, vertexType); + if (listByVertexType.isRight()) { + return listByVertexType; + } + result.addAll(listByVertexType.left().value()); + } + return Either.left(result); + + } + + public Either, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid) { + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + Either, StorageOperationStatus> componentListByUuid = getComponentListByUuid(componentUuid, propertiesToMatch); + return componentListByUuid; + } - Either, StorageOperationStatus> result = null; - Either getComponentRes; - List components = new ArrayList<>(); - List componentVertices; - Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + public Either, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map additionalPropertiesToMatch) { - propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName); - if (componentType != null) - propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + if (additionalPropertiesToMatch != null) { + propertiesToMatch.putAll(additionalPropertiesToMatch); + } - Either, TitanOperationStatus> getComponentsRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); - if (getComponentsRes.isRight()) { - TitanOperationStatus status = getComponentsRes.right().value(); - log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - if (result == null) { - componentVertices = getComponentsRes.left().value(); - for (GraphVertex componentVertex : componentVertices) { - getComponentRes = getToscaElementByOperation(componentVertex); - if (getComponentRes.isRight()) { - log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value()); - result = Either.right(getComponentRes.right().value()); - break; - } - T componentBySystemName = getComponentRes.left().value(); - log.debug("Found component, id: {}", componentBySystemName.getUniqueId()); - components.add(componentBySystemName); - } - } - if (result == null) { - result = Either.left(components); - } - return result; - } + propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid); - public Either getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) { - return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll); - } + Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - public Either getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) { - Either result; + Either, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); - Map hasProperties = new EnumMap<>(GraphPropertyEnum.class); - Map hasNotProperties = new EnumMap<>(GraphPropertyEnum.class); + if (vertexEither.isRight()) { + log.debug("Couldn't fetch metadata for component with type {} and uuid {}, error: {}", componentUuid, vertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value())); + } + List vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null; - hasProperties.put(GraphPropertyEnum.NAME, name); - hasProperties.put(GraphPropertyEnum.VERSION, version); - hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true); - if (componentType != null) { - hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); - } - Either, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag); - if (getResourceRes.isRight()) { - TitanOperationStatus status = getResourceRes.right().value(); - log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - return getToscaElementByOperation(getResourceRes.left().value().get(0)); - } + if (vertexList == null || vertexList.isEmpty()) { + log.debug("Component with uuid {} was not found", componentUuid); + return Either.right(StorageOperationStatus.NOT_FOUND); + } - public Either, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, boolean isHighestVersions) { - List components = new ArrayList<>(); - Either, StorageOperationStatus> catalogDataResult; - List toscaElements; - switch (componentType) { - case RESOURCE: - catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, ToscaElementTypeEnum.NodeType, isHighestVersions); - if (catalogDataResult.isRight()) { - return Either.right(catalogDataResult.right().value()); - } - toscaElements = catalogDataResult.left().value(); - Either, StorageOperationStatus> resourceCatalogData = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, ToscaElementTypeEnum.TopologyTemplate, isHighestVersions); - if (resourceCatalogData.isRight()) { - return Either.right(resourceCatalogData.right().value()); - } - toscaElements.addAll(resourceCatalogData.left().value()); - break; - case SERVICE: - catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, ToscaElementTypeEnum.TopologyTemplate, isHighestVersions); - if (catalogDataResult.isRight()) { - return Either.right(catalogDataResult.right().value()); + ArrayList latestComponents = new ArrayList<>(); + for (GraphVertex vertex : vertexList) { + Either toscaElementByOperation = getToscaElementByOperation(vertex); + + if(toscaElementByOperation.isRight()){ + log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId()); + return Either.right(toscaElementByOperation.right().value()); } - toscaElements = catalogDataResult.left().value(); - break; - default: - log.debug("Not supported component type {}", componentType); - return Either.right(StorageOperationStatus.BAD_REQUEST); - } - toscaElements.forEach(te -> { - T component = ModelConverter.convertFromToscaElement(te); - components.add(component); - }); - return Either.left(components); - } - - public Either, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) { - Either, StorageOperationStatus> allComponentsMarkedForDeletion; - List deleted = new ArrayList<>(); - switch (componentType) { - case RESOURCE: - allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType); - break; - case SERVICE: - case PRODUCT: - allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType); - break; - default: - log.debug("Not supported component type {}", componentType); - return Either.right(StorageOperationStatus.BAD_REQUEST); - } - if (allComponentsMarkedForDeletion.isRight()) { - return Either.right(allComponentsMarkedForDeletion.right().value()); - } - List allMarked = allComponentsMarkedForDeletion.left().value(); - - Either, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements(); - if (allNotDeletedElements.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value())); + + latestComponents.add(toscaElementByOperation.left().value()); } - List allNonMarked = allNotDeletedElements.left().value(); - for (GraphVertex elementV : allMarked) { - if (topologyTemplateOperation.isInUse(elementV, allNonMarked) == false) { - Either deleteToscaElement = deleteToscaElement(elementV); - if (deleteToscaElement.isRight()) { - log.debug("Failed to delete marked element {} error {}", elementV.getUniqueId(), deleteToscaElement.right().value()); + + if(latestComponents.size() > 1) { + for (Component component : latestComponents) { + if(component.isHighestVersion()){ + LinkedList highestComponent = new LinkedList<>(); + highestComponent.add(component); + return Either.left(highestComponent); } - } else { - deleted.add(elementV.getUniqueId()); - log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId()); - } - } - return Either.left(deleted); - } - - public Either, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) { - Either, StorageOperationStatus> allComponentsMarkedForDeletion; - switch (componentType) { - case RESOURCE: - allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType); - break; - case SERVICE: - case PRODUCT: - allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType); - break; - default: - log.debug("Not supported component type {}", componentType); - return Either.right(StorageOperationStatus.BAD_REQUEST); - } - if (allComponentsMarkedForDeletion.isRight()) { - return Either.right(allComponentsMarkedForDeletion.right().value()); - } - return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(v -> v.getUniqueId()).collect(Collectors.toList())); - } - - public Either isComponentInUse(String componentId) { - Either result; - Either, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements(); - if (allNotDeletedElements.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value())); - } else { - result = Either.left(topologyTemplateOperation.isInUse(componentId, allNotDeletedElements.left().value())); - } - return result; - } - - public Either, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) { - - Either, StorageOperationStatus> result = null; - Either updateContainerComponentRes = null; - componentInstance.setIcon(origComponent.getIcon()); - Either, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), - ModelConverter.convertToToscaElement(origComponent), getNextComponentInstanceCounter(containerComponent, origComponent.getName()), componentInstance, allowDeleted, user); - - if (addResult.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName()); - result = Either.right(addResult.right().value()); - } - if (result == null) { - updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId()); - if (updateContainerComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName()); - result = Either.right(updateContainerComponentRes.right().value()); - } - } - if (result == null) { - Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value()); - String createdInstanceId = addResult.left().value().getRight(); - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName()); - result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId)); - } - return result; - } - - public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map resourcesInstancesMap, boolean allowDeleted) { - - StorageOperationStatus result = null; - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId()); - - Either metadataVertex = titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll); - if (metadataVertex.isRight()) { - TitanOperationStatus status = metadataVertex.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (result == null) { - result = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted); - } - return result; - } - - public Either, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) { - - Either, StorageOperationStatus> result = null; - - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName()); - componentInstance.setIcon(origComponent.getIcon()); - Either, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), - ModelConverter.convertToToscaElement(origComponent), componentInstance); - if (updateResult.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName()); - result = Either.right(updateResult.right().value()); - } - if (result == null) { - Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft()); - String createdInstanceId = updateResult.left().value().getRight(); - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName()); - result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId)); - } - return result; - } - - public Either updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) { - - Either result = null; - - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName()); - - Either updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent)); - if (updateResult.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ", containerComponent.getName()); - result = Either.right(updateResult.right().value()); - } - if (result == null) { - Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value()); - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName()); - result = Either.left(updatedComponent); - } - return result; - } - - public Either, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) { - - Either, StorageOperationStatus> result = null; - - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName()); - - Either, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId); - if (updateResult.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName()); - result = Either.right(updateResult.right().value()); - } - if (result == null) { - Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft()); - String deletedInstanceId = updateResult.left().value().getRight(); - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName()); - result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId)); - } - return result; - } - - private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) { - - Integer nextCounter = 0; - - if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) { - - String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName); - Integer maxCounterFromNames = getMaxCounterFromNames(containerComponent, normalizedName); - Integer maxCounterFromIds = getMaxCounterFromIds(containerComponent, normalizedName); - - if (maxCounterFromNames == null && maxCounterFromIds != null) { - nextCounter = maxCounterFromIds + 1; - } else if (maxCounterFromIds == null && maxCounterFromNames != null) { - nextCounter = maxCounterFromNames + 1; - } else if (maxCounterFromIds != null && maxCounterFromNames != null) { - nextCounter = maxCounterFromNames > maxCounterFromIds ? maxCounterFromNames + 1 : maxCounterFromIds + 1; - } - } - return nextCounter.toString(); - } - - private Integer getMaxCounterFromNames(Component containerComponent, String normalizedName) { - - Integer maxCounter = 0; - List countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName)).map(ci -> ci.getNormalizedName().split(normalizedName)[1]) - .collect(Collectors.toList()); - - if (CollectionUtils.isEmpty(countersStr)) { - return null; - } - Integer currCounter = null; - for (String counter : countersStr) { - if (StringUtils.isEmpty(counter)) { - continue; - } - try { - currCounter = Integer.parseInt(counter); - } catch (Exception e) { - continue; } - maxCounter = maxCounter < currCounter ? currCounter : maxCounter; - } - if (currCounter == null) { - return null; - } - return maxCounter; - } - - private Integer getMaxCounterFromIds(Component containerComponent, String normalizedName) { - - Integer maxCounter = 0; - List countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName)).map(ci -> ci.getUniqueId().split(normalizedName)[1]) - .collect(Collectors.toList()); - - if (CollectionUtils.isEmpty(countersStr)) { - return null; - } - Integer currCounter = null; - for (String counter : countersStr) { - if (StringUtils.isEmpty(counter)) { - continue; - } - try { - currCounter = Integer.parseInt(counter); - } catch (Exception e) { - continue; - } - maxCounter = maxCounter < currCounter ? currCounter : maxCounter; - } - if (currCounter == null) { - return null; - } - return maxCounter; - } - - public Either associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { - return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef); - - } - - public Either, StorageOperationStatus> createAndAssociateInputs(Map inputs, String componentId) { - - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - - GraphVertex vertex = getVertexEither.left().value(); - Map inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue()))); - - StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId); - - if (StorageOperationStatus.OK == status) { - log.debug("Component created successfully!!!"); - List inputsResList = null; - if (inputsMap != null && !inputsMap.isEmpty()) { - inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList()); - } - return Either.left(inputsResList); - } - return Either.right(status); - - } - - public Either, StorageOperationStatus> addInputsToComponent(Map inputs, String componentId) { - - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - - GraphVertex vertex = getVertexEither.left().value(); - Map inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue()))); - - StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME); - - if (StorageOperationStatus.OK == status) { - log.debug("Component created successfully!!!"); - List inputsResList = null; - if (inputsMap != null && !inputsMap.isEmpty()) { - inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList()); - } - return Either.left(inputsResList); - } - return Either.right(status); - - } - - public Either>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map> instProperties, String componentId) { - - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - - GraphVertex vertex = getVertexEither.left().value(); - Map instPropsMap = new HashMap<>(); - if (instProperties != null) { - - MapPropertiesDataDefinition propertiesMap; - for (Entry> entry : instProperties.entrySet()) { - propertiesMap = new MapPropertiesDataDefinition(); - - propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e))); - - instPropsMap.put(entry.getKey(), propertiesMap); - } - } - - StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap); - - if (StorageOperationStatus.OK == status) { - log.debug("Component created successfully!!!"); - return Either.left(instProperties); - } - return Either.right(status); - - } - - public Either>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map> instProperties) { - - StorageOperationStatus status = StorageOperationStatus.OK; - if (instProperties != null) { - - for (Entry> entry : instProperties.entrySet()) { - List props = entry.getValue(); - String componentInstanseId = entry.getKey(); - if (props != null && !props.isEmpty()) { - for (ComponentInstanceInput property : props) { - List componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanseId); - Optional instanceProperty = componentInstancesInputs.stream().filter(p -> p.getName().equals(property.getName())).findAny(); - if (instanceProperty.isPresent()) { - status = updateComponentInstanceInput(containerComponent, componentInstanseId, property); - } else { - status = addComponentInstanceInput(containerComponent, componentInstanseId, property); - } - if (status != StorageOperationStatus.OK) { - log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanseId, status); - return Either.right(status); - } else { - log.trace("instance input {} for instance {} updated", property, componentInstanseId); - } - } - } - } - } - return Either.left(instProperties); - } - - public StorageOperationStatus deleteComponentInstanceInputsToComponent(Map> instProperties, String componentId) { - - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); - - } - - GraphVertex vertex = getVertexEither.left().value(); - Map instPropsMap = new HashMap<>(); - if (instProperties != null) { - - MapPropertiesDataDefinition propertiesMap; - for (Entry> entry : instProperties.entrySet()) { - propertiesMap = new MapPropertiesDataDefinition(); - - propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e))); - - instPropsMap.put(entry.getKey(), propertiesMap); - } - } - - return topologyTemplateOperation.deleteInstInputsToComponent(vertex, instPropsMap); - - } - - public Either>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map> instProperties, String componentId) { - - StorageOperationStatus status = StorageOperationStatus.OK; - if (instProperties != null) { - - for (Entry> entry : instProperties.entrySet()) { - List props = entry.getValue(); - String componentInstanseId = entry.getKey(); - List instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanseId); - if (props != null && !props.isEmpty()) { - for (ComponentInstanceProperty property : props) { - Optional instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); - if (instanceProperty.isPresent()) { - status = updateComponentInstanceProperty(containerComponent, componentInstanseId, property); - } else { - status = addComponentInstanceProperty(containerComponent, componentInstanseId, property); - } - - } - } - } - } - - return Either.left(instProperties); - - } - - public StorageOperationStatus associateArtifactToInstances(Map> instArtifacts, String componentId, User user) { - - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); - - } - - GraphVertex vertex = getVertexEither.left().value(); - Map instArtMap = new HashMap<>(); - if (instArtifacts != null) { - - MapArtifactDataDefinition artifactsMap; - for (Entry> entry : instArtifacts.entrySet()) { - Map artList = entry.getValue(); - Map artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); - artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME); - - instArtMap.put(entry.getKey(), artifactsMap); - } - } - - return topologyTemplateOperation.associateInstArtifactToComponent(vertex, instArtMap); - - } - - public StorageOperationStatus associateInstAttributeToComponentToInstances(Map> instArttributes, String componentId) { - - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); - - } - - GraphVertex vertex = getVertexEither.left().value(); - Map instAttr = new HashMap<>(); - if (instArttributes != null) { - - MapPropertiesDataDefinition attributesMap; - for (Entry> entry : instArttributes.entrySet()) { - attributesMap = new MapPropertiesDataDefinition(); - attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e))); - instAttr.put(entry.getKey(), attributesMap); - } - } - - return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr); - - } - - public StorageOperationStatus associateCalculatedCapReq(Map>> instCapabilties, Map>> instReg, String componentId) { - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); - - } - - GraphVertex vertex = getVertexEither.left().value(); - - Map calcRequirements = new HashMap<>(); - - Map calcCapabilty = new HashMap<>(); - Map calculatedCapabilitiesProperties = new HashMap<>(); - ; - if (instCapabilties != null) { - for (Entry>> entry : instCapabilties.entrySet()) { - - Map> caps = entry.getValue(); - Map mapToscaDataDefinition = new HashMap<>(); - for (Entry> instCapability : caps.entrySet()) { - mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(iCap -> new CapabilityDataDefinition(iCap)).collect(Collectors.toList()))); - } - - ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey()); - MapListCapabiltyDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance); - - MapCapabiltyProperty mapCapabiltyProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true); - - calcCapabilty.put(entry.getKey().getUniqueId(), capMap); - calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabiltyProperty); - } - } - - if (instReg != null) { - for (Entry>> entry : instReg.entrySet()) { - - Map> req = entry.getValue(); - Map mapToscaDataDefinition = new HashMap<>(); - for (Entry> instReq : req.entrySet()) { - mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(iCap -> new RequirementDataDefinition(iCap)).collect(Collectors.toList()))); - } - - MapListRequirementDataDefinition capMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey())); - - calcRequirements.put(entry.getKey().getUniqueId(), capMap); - } - } - - StorageOperationStatus status = topologyTemplateOperation.associateCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties); - - return status; - } - - private Either, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) { - - Map hasProps = new EnumMap<>(GraphPropertyEnum.class); - Map hasNotProps = new EnumMap<>(GraphPropertyEnum.class); - - fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType); - - Either, TitanOperationStatus> getRes = titanDao.getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata); - if (getRes.isRight()) { - if (getRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - return Either.left(new ArrayList<>()); - } else { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); - } - } else { - List nonAbstractLatestComponents = new ArrayList<>(); - ComponentParametersView params = new ComponentParametersView(true); - params.setIgnoreAllVersions(false); - for (GraphVertex vertexComponent : getRes.left().value()) { - Either componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params); - if (componentRes.isRight()) { - log.debug("Failed to fetch ligth element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value()); - return Either.right(componentRes.right().value()); - } else { - Component component = ModelConverter.convertFromToscaElement(componentRes.left().value()); - - nonAbstractLatestComponents.add(component); - } - } - - return Either.left(nonAbstractLatestComponents); - } - } - - public Either getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) { - - Either result; - - Map hasProperties = new EnumMap<>(GraphPropertyEnum.class); - - hasProperties.put(GraphPropertyEnum.UUID, componentUuid); - if (isHighest != null) { - hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue()); - } - - Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - - Either, TitanOperationStatus> getRes = titanDao.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag); - if (getRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); - } else { - List latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList()); - ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0) - : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get(); - result = Either.left(latestVersion); - } - return result; - } - - public Either getComponentMetadata(String componentId) { - - Either result; - Either getRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata); - if (getRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); - } else { - ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value()); - result = Either.left(componentMetadata); - } - return result; - } - - private Map findLatestVersion(List resourceDataList) { - Map, ComponentMetadataData> latestVersionMap = new HashMap, ComponentMetadataData>(); - for (ComponentMetadataData resourceData : resourceDataList) { - ComponentMetadataData latestVersionData = resourceData; - - ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition(); - Pair pair = createKeyPair(latestVersionData); - if (latestVersionMap.containsKey(pair)) { - latestVersionData = latestVersionMap.get(pair); - String currentVersion = latestVersionData.getMetadataDataDefinition().getVersion(); - String newVersion = metadataDataDefinition.getVersion(); - if (CommonBeUtils.compareAsdcComponentVersions(newVersion, currentVersion)) { - latestVersionData = resourceData; - } - } - if (log.isDebugEnabled()) - log.debug("last certified version of resource = {} version is {}", latestVersionData.getMetadataDataDefinition().getName(), latestVersionData.getMetadataDataDefinition().getVersion()); - - latestVersionMap.put(pair, latestVersionData); - } - - Map resVersionMap = new HashMap(); - for (ComponentMetadataData resourceData : latestVersionMap.values()) { - ComponentMetadataData latestVersionData = resourceData; - ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition(); - if (resVersionMap.containsKey(metadataDataDefinition.getUUID())) { - latestVersionData = resVersionMap.get(metadataDataDefinition.getUUID()); - String currentVersion = latestVersionData.getMetadataDataDefinition().getVersion(); - String newVersion = metadataDataDefinition.getVersion(); - if (CommonBeUtils.compareAsdcComponentVersions(newVersion, currentVersion)) { - latestVersionData = resourceData; - } - } - if (log.isDebugEnabled()) - log.debug("last uuid version of resource = {} version is {}", latestVersionData.getMetadataDataDefinition().getName(), latestVersionData.getMetadataDataDefinition().getVersion()); - resVersionMap.put(latestVersionData.getMetadataDataDefinition().getUUID(), latestVersionData); - } - - return resVersionMap; - } - - private Pair createKeyPair(ComponentMetadataData metadataData) { - Pair pair; - NodeTypeEnum label = NodeTypeEnum.getByName(metadataData.getLabel()); - switch (label) { - case Resource: - pair = new ImmutablePair<>(metadataData.getMetadataDataDefinition().getName(), ((ResourceMetadataDataDefinition) metadataData.getMetadataDataDefinition()).getResourceType().name()); - break; - default: - pair = new ImmutablePair<>(metadataData.getMetadataDataDefinition().getName(), metadataData.getLabel()); - break; - } - - return pair; - } - - public Either, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List componentUids) { - - Either, StorageOperationStatus> result = null; - List components = new ArrayList<>(); - if (componentUids == null) { - Either, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, isHighest, componentTypeEnum, internalComponentType, componentUids); - if (componentUidsRes.isRight()) { - result = Either.right(componentUidsRes.right().value()); - } else { - componentUids = componentUidsRes.left().value(); - } - } - if (!componentUids.isEmpty()) { - for (String componentUid : componentUids) { - ComponentParametersView componentParametersView = buildComponentViewForNotAbstract(); - if (internalComponentType != null && "vl".equalsIgnoreCase(internalComponentType)) { - componentParametersView.setIgnoreCapabilities(false); - componentParametersView.setIgnoreRequirements(false); - } - Either getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView); - if (getToscaElementRes.isRight()) { - if (log.isDebugEnabled()) - log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value()); - result = Either.right(getToscaElementRes.right().value()); - break; - } - Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value()); - component.setContactId(null); - component.setCreationDate(null); - component.setCreatorUserId(null); - component.setCreatorFullName(null); - component.setLastUpdateDate(null); - component.setLastUpdaterUserId(null); - component.setLastUpdaterFullName(null); - component.setNormalizedName(null); - components.add(component); - } - } - if (result == null) { - result = Either.left(components); - } - return result; - } - - private Either, StorageOperationStatus> getComponentUids(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List componentUids) { - - Either, StorageOperationStatus> result = null; - Either, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType); - if (getToscaElementsRes.isRight()) { - result = Either.right(getToscaElementsRes.right().value()); - } else { - List collection = getToscaElementsRes.left().value(); - if (collection == null) { - componentUids = new ArrayList<>(); - } else { - componentUids = collection.stream().map(p -> p.getUniqueId()).collect(Collectors.toList()); - } - } - if (result == null) { - result = Either.left(componentUids); - } - return result; - } - - private ComponentParametersView buildComponentViewForNotAbstract() { - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreCategories(false); - componentParametersView.setIgnoreAllVersions(false); - return componentParametersView; - } - - public Either validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) { - Either result = validateComponentNameUniqueness(name, resourceType, componentType); - if (result.isLeft()) { - result = Either.left(!result.left().value()); - } - return result; - } - - public Either validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) { - VertexTypeEnum vertexType = getVertexTypeByComponentAndResourceTypeEnum(resourceType, componentType); - String normalizedName = ValidationUtils.normaliseComponentName(name); - Map properties = new EnumMap<>(GraphPropertyEnum.class); - properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName); - properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); - - Either, TitanOperationStatus> vertexEither = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse); - if (vertexEither.isRight() && vertexEither.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value())); - } - List vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null; - if (vertexList != null && !vertexList.isEmpty()) { - return Either.left(false); - } else { - return Either.left(true); - } - } - - // UI query parameter is either VFC/CP/VL(for yaml upload/update) or VF (for CSAR upload/user composed VF) - // TODO implementation of topology template VFCs may require updating this method - depending on UI implementation - private VertexTypeEnum getVertexTypeByComponentAndResourceTypeEnum(ResourceTypeEnum resourceType, ComponentTypeEnum componentType) { - VertexTypeEnum vertexType = VertexTypeEnum.TOPOLOGY_TEMPLATE; - if (ComponentTypeEnum.RESOURCE == componentType && ResourceTypeEnum.VF != resourceType) { - vertexType = VertexTypeEnum.NODE_TYPE; - } - return vertexType; - } - - private void fillNodeTypePropsMap(Map hasProps, Map hasNotProps, String internalComponentType) { - switch (internalComponentType.toLowerCase()) { - case "vf": - hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VF.name()); - hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VFCMT.name()); - break; - case "service": - hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VFC.name()); - hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VFCMT.name()); - break; - case "vl": - hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VL.name()); - break; - default: - break; - } - } - - private void fillTopologyTemplatePropsMap(Map hasProps, ComponentTypeEnum componentTypeEnum) { - switch (componentTypeEnum) { - case RESOURCE: - hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); - break; - case SERVICE: - hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); - break; - default: - break; - } - } - - private void fillPropsMap(Map hasProps, Map hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) { - hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); - - hasNotProps.put(GraphPropertyEnum.IS_DELETED, true); - hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - if (VertexTypeEnum.NODE_TYPE == internalVertexType) { - hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract); - if (internalComponentType != null) { - fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType); - } - } else { - fillTopologyTemplatePropsMap(hasProps, componentTypeEnum); - } - } - - private List getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) { - List internalVertexTypes = new ArrayList<>(); - if (ComponentTypeEnum.RESOURCE == componentTypeEnum) { - internalVertexTypes.add(VertexTypeEnum.NODE_TYPE); - } - if (ComponentTypeEnum.SERVICE == componentTypeEnum || "service".equalsIgnoreCase(internalComponentType)) { - internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE); - } - return internalVertexTypes; - } - - public Either, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType) { - List internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType); - List result = new ArrayList<>(); - for (VertexTypeEnum vertexType : internalVertexTypes) { - Either, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType, vertexType); - if (listByVertexType.isRight()) { - return listByVertexType; - } - result.addAll(listByVertexType.left().value()); - } - return Either.left(result); - - } - - public Either, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid) { - Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - Either, StorageOperationStatus> componentListByUuid = getComponentListByUuid(componentUuid, propertiesToMatch); - return componentListByUuid; - } - - public Either, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map additionalPropertiesToMatch) { - - Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - - if (additionalPropertiesToMatch != null) { - propertiesToMatch.putAll(additionalPropertiesToMatch); - } - - propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid); - - Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - - Either, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); - - if (vertexEither.isRight()) { - log.debug("Couldn't fetch metadata for component with type {} and uuid {}, error: {}", componentUuid, vertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value())); - } - List vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null; - - if (vertexList == null || vertexList.isEmpty()) { - log.debug("Component with uuid {} was not found", componentUuid); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - - ArrayList latestComponents = new ArrayList<>(); - for (GraphVertex vertex : vertexList) { - Either toscaElementByOperation = getToscaElementByOperation(vertex); - - if(toscaElementByOperation.isRight()){ - log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId()); - return Either.right(toscaElementByOperation.right().value()); - } - - latestComponents.add(toscaElementByOperation.left().value()); - } - - if(latestComponents.size() > 1) { - for (Component component : latestComponents) { - if(component.isHighestVersion()){ - LinkedList highestComponent = new LinkedList<>(); - highestComponent.add(component); - return Either.left(highestComponent); - } - } - } + } - return Either.left(latestComponents); - } - - public Either getLatestComponentByUuid(String componentUuid) { - - Either, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid); - - if (latestVersionListEither.isRight()) { - return Either.right(latestVersionListEither.right().value()); - } - - List latestVersionList = latestVersionListEither.left().value(); - - if (latestVersionList.isEmpty()) { - return Either.right(StorageOperationStatus.NOT_FOUND); - } - Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get(); - - return Either.left(component); - } - - public Either, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) { - - List resources = new ArrayList<>(); - Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - - propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract); - if (isHighest != null) { - propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue()); - } - propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - - Either, TitanOperationStatus> getResourcesRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); - - if (getResourcesRes.isRight()) { - log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResourcesRes.right().value())); - } - List resourceVerticies = getResourcesRes.left().value(); - for (GraphVertex resourceV : resourceVerticies) { - Either getResourceRes = getToscaElement(resourceV); - if (getResourceRes.isRight()) { - return Either.right(getResourceRes.right().value()); - } - resources.add(getResourceRes.left().value()); - } - return Either.left(resources); - } - - public Either getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) { - Either result; - - Map hasProperties = new EnumMap<>(GraphPropertyEnum.class); - Map hasNotProperties = new EnumMap<>(GraphPropertyEnum.class); - - hasProperties.put(GraphPropertyEnum.NAME, name); - hasProperties.put(GraphPropertyEnum.VERSION, version); - hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - - hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true); - - Either, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag); - if (getResourceRes.isRight()) { - TitanOperationStatus status = getResourceRes.right().value(); - log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - return getToscaElementByOperation(getResourceRes.left().value().get(0)); - } - - public Either getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) { - return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, false, JsonParseFlagEnum.ParseAll); - } - - public Either getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, boolean allowDeleted, JsonParseFlagEnum parseFlag) { - Map props = new EnumMap<>(GraphPropertyEnum.class); - props.put(GraphPropertyEnum.CSAR_UUID, csarUUID); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - if (componentType != null) { - props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); - } - Map propsHasNot = new EnumMap<>(GraphPropertyEnum.class); - propsHasNot.put(GraphPropertyEnum.IS_DELETED, true); - - GraphVertex resourceMetadataData = null; - List resourceMetadataDataList = null; - Either, TitanOperationStatus> byCsar = titanDao.getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata); - if (byCsar.isRight()) { - if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) { - // Fix Defect DE256036 - if (StringUtils.isEmpty(systemName)) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND)); - } - - props.clear(); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - props.put(GraphPropertyEnum.SYSTEM_NAME, systemName); - Either, TitanOperationStatus> bySystemname = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata); - if (bySystemname.isRight()) { - log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value())); - } - if (bySystemname.left().value().size() > 2) { - log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size()); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - resourceMetadataDataList = bySystemname.left().value(); - if (resourceMetadataDataList.size() == 1) { - resourceMetadataData = resourceMetadataDataList.get(0); - } else { - for (GraphVertex curResource : resourceMetadataDataList) { - if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) { - resourceMetadataData = curResource; - break; - } - } - } - if (resourceMetadataData == null) { - log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions"); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) { - log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID); - // correct error will be returned from create flow. with all - // correct audit records!!!!! - return Either.right(StorageOperationStatus.NOT_FOUND); - } - Either resource = getToscaElement((String) resourceMetadataData.getUniqueId()); - return resource; - } - } else { - resourceMetadataDataList = byCsar.left().value(); - if (resourceMetadataDataList.size() > 2) { - log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size()); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - if (resourceMetadataDataList.size() == 1) { - resourceMetadataData = resourceMetadataDataList.get(0); - } else { - for (GraphVertex curResource : resourceMetadataDataList) { - if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) { - resourceMetadataData = curResource; - break; - } - } - } - if (resourceMetadataData == null) { - log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions"); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - Either resource = getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag); - return resource; - } - return null; - } - - public Either validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) { - - String currentTemplateNameChecked = templateNameExtends; - - while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) { - Either latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked); - - if (latestByToscaResourceName.isRight()) { - return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value()); - } - - Resource value = latestByToscaResourceName.left().value(); - - if (value.getDerivedFrom() != null) { - currentTemplateNameChecked = value.getDerivedFrom().get(0); - } else { - currentTemplateNameChecked = null; - } - } - - return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false); - } - - public Either, StorageOperationStatus> fetchByResourceType(String resourceType) { - - Map props = new EnumMap<>(GraphPropertyEnum.class); - props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - Either, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props); - - if (resourcesByTypeEither.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourcesByTypeEither.right().value())); - } - - List vertexList = resourcesByTypeEither.left().value(); - List components = new ArrayList<>(); - - for (GraphVertex vertex : vertexList) { - components.add(getToscaElementByOperation(vertex).left().value()); - } - - return Either.left(components); - - } - - public void commit() { - titanDao.commit(); - } - - public Either updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) { - Either updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus); - if (updateDistributionStatus.isRight()) { - return Either.right(updateDistributionStatus.right().value()); - } - GraphVertex serviceV = updateDistributionStatus.left().value(); - service.setDistributionStatus(distributionStatus); - service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE)); - return Either.left(service); - } - - public Either updateComponentLastUpdateDateOnGraph(Component component, Long modificationTime) { - - Either result = null; - GraphVertex serviceVertex; - Either updateRes = null; - Either getRes = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata); - if (getRes.isRight()) { - TitanOperationStatus status = getRes.right().value(); - log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - if (result == null) { - serviceVertex = getRes.left().value(); - long lastUpdateDate = System.currentTimeMillis(); - serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate); - component.setLastUpdateDate(lastUpdateDate); - updateRes = titanDao.updateVertex(serviceVertex); - if (updateRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value())); - } - } - if (result == null) { - result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value())); - } - return result; - } - - public TitanDao getTitanDao() { - return titanDao; - } - - public Either, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set distStatus) { - Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - - return getServicesWithDistStatus(distStatus, propertiesToMatch); - } - - public Either, StorageOperationStatus> getServicesWithDistStatus(Set distStatus, Map additionalPropertiesToMatch) { - - List servicesAll = new ArrayList<>(); - - Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - - if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) { - propertiesToMatch.putAll(additionalPropertiesToMatch); - } - - propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); - - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - - if (distStatus != null && !distStatus.isEmpty()) { - for (DistributionStatusEnum state : distStatus) { - propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name()); - Either, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch); - if (fetchServicesByCriteria.isRight()) { - return fetchServicesByCriteria; - } else { - servicesAll = fetchServicesByCriteria.left().value(); - } - } - return Either.left(servicesAll); - } else { - return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch); - } - } - - // private Either, StorageOperationStatus> fetchServicesByCriteria(List servicesAll, Map propertiesToMatch, Map propertiesNotToMatch) { - // Either, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); - // if (getRes.isRight()) { - // if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) { - // CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value()); - // return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); - // } - // } else { - // for (GraphVertex vertex : getRes.left().value()) { - // Either getServiceRes = getToscaElementByOperation(vertex); - // if (getServiceRes.isRight()) { - // CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value()); - // return Either.right(getServiceRes.right().value()); - // } else { - // servicesAll.add((Service) getToscaElementByOperation(vertex).left().value()); - // } - // } - // } - // return Either.left(servicesAll); - // } - - private Either, StorageOperationStatus> fetchServicesByCriteria(List servicesAll, Map propertiesToMatch, Map propertiesNotToMatch) { - Either, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); - if (getRes.isRight()) { - if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); - } - } else { - for (GraphVertex vertex : getRes.left().value()) { - // Either getServiceRes = getToscaElementByOperation(vertex); - Either getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true)); - - if (getServiceRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value()); - return Either.right(getServiceRes.right().value()); - } else { - servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value())); - } - } - } - return Either.left(servicesAll); - } - - public void rollback() { - titanDao.rollback(); - } - - public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map finalDeploymentArtifacts) { - Map instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); - - return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts); - } - - public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) { - return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId); - } - - public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List groupInstances) { - return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances); - } - - public Either addPropertyToResource(String propertyName, PropertyDefinition newPropertyDefinition, Resource resource) { - - Either result = null; - Either getUpdatedComponentRes = null; - newPropertyDefinition.setName(propertyName); - newPropertyDefinition.setParentUniqueId(resource.getUniqueId()); - StorageOperationStatus status = getToscaElementOperation(resource).addToscaDataToToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", propertyName, resource.getName(), status); - result = Either.right(status); - } - if (result == null) { - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreProperties(false); - getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter); - if (getUpdatedComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value()); - result = Either.right(status); - } - } - if (result == null) { - PropertyDefinition newProperty = null; - List properties = ((Resource) getUpdatedComponentRes.left().value()).getProperties(); - if (CollectionUtils.isNotEmpty(properties)) { - Optional newPropertyOptional = properties.stream().filter(p -> p.getName().equals(propertyName)).findAny(); - if (newPropertyOptional.isPresent()) { - newProperty = newPropertyOptional.get(); - } - } - if (newProperty == null) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", propertyName, resource.getUniqueId(), StorageOperationStatus.NOT_FOUND); - result = Either.right(StorageOperationStatus.NOT_FOUND); - } else { - result = Either.left(newProperty); - } - } - return result; - } - - public StorageOperationStatus deletePropertyOfResource(Resource resource, String propertyName) { - return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME); - } - - public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) { - return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME); - } - - public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) { - return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME); - } - - public Either updatePropertyOfResource(Resource resource, PropertyDefinition newPropertyDefinition) { - - Either getUpdatedComponentRes = null; - Either result = null; - StorageOperationStatus status = getToscaElementOperation(resource).updateToscaDataOfToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getName(), status); - result = Either.right(status); - } - if (result == null) { - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreProperties(false); - getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter); - if (getUpdatedComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value()); - result = Either.right(status); - } - } - if (result == null) { - Optional newProperty = ((Resource) getUpdatedComponentRes.left().value()).getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny(); - if (newProperty.isPresent()) { - result = Either.left(newProperty.get()); - } else { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getUniqueId(), StorageOperationStatus.NOT_FOUND); - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - return result; - } - - public Either addAttributeOfResource(Component component, PropertyDefinition newAttributeDef) { - - Either getUpdatedComponentRes = null; - Either result = null; - if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) { - String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName()); - newAttributeDef.setUniqueId(attUniqueId); - } - - StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status); - result = Either.right(status); - } - if (result == null) { - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreAttributesFrom(false); - getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); - if (getUpdatedComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value()); - result = Either.right(status); - } - } - if (result == null) { - Optional newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny(); - if (newAttribute.isPresent()) { - result = Either.left(newAttribute.get()); - } else { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - return result; - } - - public Either updateAttributeOfResource(Component component, PropertyDefinition newAttributeDef) { - - Either getUpdatedComponentRes = null; - Either result = null; - StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status); - result = Either.right(status); - } - if (result == null) { - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreAttributesFrom(false); - getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); - if (getUpdatedComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value()); - result = Either.right(status); - } - } - if (result == null) { - Optional newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny(); - if (newProperty.isPresent()) { - result = Either.left(newProperty.get()); - } else { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - return result; - } - - public Either updateInputOfComponent(Component component, InputDefinition newInputDefinition) { - - Either getUpdatedComponentRes = null; - Either result = null; - StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status); - result = Either.right(status); - } - if (result == null) { - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreInputs(false); - getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); - if (getUpdatedComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value()); - result = Either.right(status); - } - } - if (result == null) { - Optional updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny(); - if (updatedInput.isPresent()) { - result = Either.left(updatedInput.get()); - } else { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - return result; - } - - public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List groups, Map> groupInstancesArtifacts) { - return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts); - } - - public Either, StorageOperationStatus> updateGroupsOnComponent(Component component, ComponentTypeEnum componentType, List updatedGroups) { - return groupsOperation.updateGroups(component, componentType, updatedGroups); - } - - public Either, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, ComponentTypeEnum componentType, String instanceId, List updatedGroupInstances) { - return groupsOperation.updateGroupInstances(component, componentType, instanceId, updatedGroupInstances); - } - - public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List groupInstances) { - return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances); - } - - public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map deploymentArtifacts) { - return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts); - } - - public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) { - return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property); - } - - public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) { - return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property); - } - - public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) { - return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property); - } - - public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) { - return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property); - } - - public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) { - this.nodeTypeOperation = nodeTypeOperation; - } - - public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) { - this.topologyTemplateOperation = topologyTemplateOperation; + return Either.left(latestComponents); + } + + public Either getLatestComponentByUuid(String componentUuid) { + + Either, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid); + + if (latestVersionListEither.isRight()) { + return Either.right(latestVersionListEither.right().value()); + } + + List latestVersionList = latestVersionListEither.left().value(); + + if (latestVersionList.isEmpty()) { + return Either.right(StorageOperationStatus.NOT_FOUND); + } + Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get(); + + return Either.left(component); + } + + public Either, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) { + + List resources = new ArrayList<>(); + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + + propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract); + if (isHighest != null) { + propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue()); + } + propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + Either, TitanOperationStatus> getResourcesRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); + + if (getResourcesRes.isRight()) { + log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResourcesRes.right().value())); + } + List resourceVerticies = getResourcesRes.left().value(); + for (GraphVertex resourceV : resourceVerticies) { + Either getResourceRes = getToscaElement(resourceV); + if (getResourceRes.isRight()) { + return Either.right(getResourceRes.right().value()); + } + resources.add(getResourceRes.left().value()); + } + return Either.left(resources); + } + + public Either getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) { + Either result; + + Map hasProperties = new EnumMap<>(GraphPropertyEnum.class); + Map hasNotProperties = new EnumMap<>(GraphPropertyEnum.class); + + hasProperties.put(GraphPropertyEnum.NAME, name); + hasProperties.put(GraphPropertyEnum.VERSION, version); + hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true); + + Either, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag); + if (getResourceRes.isRight()) { + TitanOperationStatus status = getResourceRes.right().value(); + log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return result; + } + return getToscaElementByOperation(getResourceRes.left().value().get(0)); + } + + public Either getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) { + return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, false, JsonParseFlagEnum.ParseAll); + } + + public Either getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, boolean allowDeleted, JsonParseFlagEnum parseFlag) { + Map props = new EnumMap<>(GraphPropertyEnum.class); + props.put(GraphPropertyEnum.CSAR_UUID, csarUUID); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + if (componentType != null) { + props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + } + Map propsHasNot = new EnumMap<>(GraphPropertyEnum.class); + propsHasNot.put(GraphPropertyEnum.IS_DELETED, true); + + GraphVertex resourceMetadataData = null; + List resourceMetadataDataList = null; + Either, TitanOperationStatus> byCsar = titanDao.getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata); + if (byCsar.isRight()) { + if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) { + // Fix Defect DE256036 + if (StringUtils.isEmpty(systemName)) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND)); + } + + props.clear(); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + props.put(GraphPropertyEnum.SYSTEM_NAME, systemName); + Either, TitanOperationStatus> bySystemname = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata); + if (bySystemname.isRight()) { + log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value())); + } + if (bySystemname.left().value().size() > 2) { + log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size()); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + resourceMetadataDataList = bySystemname.left().value(); + if (resourceMetadataDataList.size() == 1) { + resourceMetadataData = resourceMetadataDataList.get(0); + } else { + for (GraphVertex curResource : resourceMetadataDataList) { + if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) { + resourceMetadataData = curResource; + break; + } + } + } + if (resourceMetadataData == null) { + log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions"); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) { + log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID); + // correct error will be returned from create flow. with all + // correct audit records!!!!! + return Either.right(StorageOperationStatus.NOT_FOUND); + } + Either resource = getToscaElement((String) resourceMetadataData.getUniqueId()); + return resource; + } + } else { + resourceMetadataDataList = byCsar.left().value(); + if (resourceMetadataDataList.size() > 2) { + log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size()); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + if (resourceMetadataDataList.size() == 1) { + resourceMetadataData = resourceMetadataDataList.get(0); + } else { + for (GraphVertex curResource : resourceMetadataDataList) { + if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) { + resourceMetadataData = curResource; + break; + } + } + } + if (resourceMetadataData == null) { + log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions"); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + Either resource = getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag); + return resource; + } + return null; + } + + public Either validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) { + + String currentTemplateNameChecked = templateNameExtends; + + while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) { + Either latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked); + + if (latestByToscaResourceName.isRight()) { + return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value()); + } + + Resource value = latestByToscaResourceName.left().value(); + + if (value.getDerivedFrom() != null) { + currentTemplateNameChecked = value.getDerivedFrom().get(0); + } else { + currentTemplateNameChecked = null; + } + } + + return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false); + } + + public Either, StorageOperationStatus> fetchByResourceType(String resourceType) { + + Map props = new EnumMap<>(GraphPropertyEnum.class); + props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + Either, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props); + + if (resourcesByTypeEither.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourcesByTypeEither.right().value())); + } + + List vertexList = resourcesByTypeEither.left().value(); + List components = new ArrayList<>(); + + for (GraphVertex vertex : vertexList) { + components.add(getToscaElementByOperation(vertex).left().value()); + } + + return Either.left(components); + + } + + public void commit() { + titanDao.commit(); + } + + public Either updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) { + Either updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus); + if (updateDistributionStatus.isRight()) { + return Either.right(updateDistributionStatus.right().value()); + } + GraphVertex serviceV = updateDistributionStatus.left().value(); + service.setDistributionStatus(distributionStatus); + service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE)); + return Either.left(service); + } + + public Either updateComponentLastUpdateDateOnGraph(Component component, Long modificationTime) { + + Either result = null; + GraphVertex serviceVertex; + Either updateRes = null; + Either getRes = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata); + if (getRes.isRight()) { + TitanOperationStatus status = getRes.right().value(); + log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + if (result == null) { + serviceVertex = getRes.left().value(); + long lastUpdateDate = System.currentTimeMillis(); + serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate); + component.setLastUpdateDate(lastUpdateDate); + updateRes = titanDao.updateVertex(serviceVertex); + if (updateRes.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value())); + } + } + if (result == null) { + result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value())); + } + return result; + } + + public TitanDao getTitanDao() { + return titanDao; + } + + public Either, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set distStatus) { + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + + return getServicesWithDistStatus(distStatus, propertiesToMatch); + } + + public Either, StorageOperationStatus> getServicesWithDistStatus(Set distStatus, Map additionalPropertiesToMatch) { + + List servicesAll = new ArrayList<>(); + + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + + if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) { + propertiesToMatch.putAll(additionalPropertiesToMatch); + } + + propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + if (distStatus != null && !distStatus.isEmpty()) { + for (DistributionStatusEnum state : distStatus) { + propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name()); + Either, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch); + if (fetchServicesByCriteria.isRight()) { + return fetchServicesByCriteria; + } else { + servicesAll = fetchServicesByCriteria.left().value(); + } + } + return Either.left(servicesAll); + } else { + return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch); + } + } + + // private Either, StorageOperationStatus> fetchServicesByCriteria(List servicesAll, Map propertiesToMatch, Map propertiesNotToMatch) { + // Either, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); + // if (getRes.isRight()) { + // if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) { + // CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value()); + // return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); + // } + // } else { + // for (GraphVertex vertex : getRes.left().value()) { + // Either getServiceRes = getToscaElementByOperation(vertex); + // if (getServiceRes.isRight()) { + // CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value()); + // return Either.right(getServiceRes.right().value()); + // } else { + // servicesAll.add((Service) getToscaElementByOperation(vertex).left().value()); + // } + // } + // } + // return Either.left(servicesAll); + // } + + private Either, StorageOperationStatus> fetchServicesByCriteria(List servicesAll, Map propertiesToMatch, Map propertiesNotToMatch) { + Either, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); + if (getRes.isRight()) { + if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); + } + } else { + for (GraphVertex vertex : getRes.left().value()) { + // Either getServiceRes = getToscaElementByOperation(vertex); + Either getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true)); + + if (getServiceRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value()); + return Either.right(getServiceRes.right().value()); + } else { + servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value())); + } + } + } + return Either.left(servicesAll); + } + + public void rollback() { + titanDao.rollback(); + } + + public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map finalDeploymentArtifacts) { + Map instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + + return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts); + } + + public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) { + return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId); + } + + public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List groupInstances) { + return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances); + } + + public Either addPropertyToResource(String propertyName, PropertyDefinition newPropertyDefinition, Resource resource) { + + Either result = null; + Either getUpdatedComponentRes = null; + newPropertyDefinition.setName(propertyName); + newPropertyDefinition.setParentUniqueId(resource.getUniqueId()); + StorageOperationStatus status = getToscaElementOperation(resource).addToscaDataToToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", propertyName, resource.getName(), status); + result = Either.right(status); + } + if (result == null) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreProperties(false); + getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter); + if (getUpdatedComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value()); + result = Either.right(status); + } + } + if (result == null) { + PropertyDefinition newProperty = null; + List properties = ((Resource) getUpdatedComponentRes.left().value()).getProperties(); + if (CollectionUtils.isNotEmpty(properties)) { + Optional newPropertyOptional = properties.stream().filter(p -> p.getName().equals(propertyName)).findAny(); + if (newPropertyOptional.isPresent()) { + newProperty = newPropertyOptional.get(); + } + } + if (newProperty == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", propertyName, resource.getUniqueId(), StorageOperationStatus.NOT_FOUND); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } else { + result = Either.left(newProperty); + } + } + return result; + } + + public StorageOperationStatus deletePropertyOfResource(Resource resource, String propertyName) { + return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME); + } + + public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) { + return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME); + } + + public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) { + return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME); + } + + public Either updatePropertyOfResource(Resource resource, PropertyDefinition newPropertyDefinition) { + + Either getUpdatedComponentRes = null; + Either result = null; + StorageOperationStatus status = getToscaElementOperation(resource).updateToscaDataOfToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getName(), status); + result = Either.right(status); + } + if (result == null) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreProperties(false); + getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter); + if (getUpdatedComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value()); + result = Either.right(status); + } + } + if (result == null) { + Optional newProperty = ((Resource) getUpdatedComponentRes.left().value()).getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny(); + if (newProperty.isPresent()) { + result = Either.left(newProperty.get()); + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getUniqueId(), StorageOperationStatus.NOT_FOUND); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + return result; + } + + public Either addAttributeOfResource(Component component, PropertyDefinition newAttributeDef) { + + Either getUpdatedComponentRes = null; + Either result = null; + if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) { + String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName()); + newAttributeDef.setUniqueId(attUniqueId); + } + + StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status); + result = Either.right(status); + } + if (result == null) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreAttributesFrom(false); + getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); + if (getUpdatedComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value()); + result = Either.right(status); + } + } + if (result == null) { + Optional newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny(); + if (newAttribute.isPresent()) { + result = Either.left(newAttribute.get()); + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + return result; + } + + public Either updateAttributeOfResource(Component component, PropertyDefinition newAttributeDef) { + + Either getUpdatedComponentRes = null; + Either result = null; + StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status); + result = Either.right(status); + } + if (result == null) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreAttributesFrom(false); + getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); + if (getUpdatedComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value()); + result = Either.right(status); + } + } + if (result == null) { + Optional newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny(); + if (newProperty.isPresent()) { + result = Either.left(newProperty.get()); + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + return result; + } + + public Either updateInputOfComponent(Component component, InputDefinition newInputDefinition) { + + Either getUpdatedComponentRes = null; + Either result = null; + StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status); + result = Either.right(status); + } + if (result == null) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreInputs(false); + getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); + if (getUpdatedComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value()); + result = Either.right(status); + } + } + if (result == null) { + Optional updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny(); + if (updatedInput.isPresent()) { + result = Either.left(updatedInput.get()); + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + return result; + } + + /** + * method - ename the group instances after referenced container name renamed + * flow - VF rename -(triggers)-> Group rename + * + * @param containerComponent - container such as service + * @param componentInstance - context component + * @param componentInstanceId - id + * + * @return - successfull/failed status + * **/ + public Either cleanAndAddGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, String componentInstanceId){ + String uniqueId = componentInstance.getUniqueId(); + StorageOperationStatus status = nodeTemplateOperation.deleteToscaDataDeepElementsBlockToToscaElement( containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, uniqueId ); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status); + return Either.right(status); + } + status = addGroupInstancesToComponentInstance( containerComponent , componentInstance, componentInstance.getGroupInstances() ); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId, status); + return Either.right(status); + } + return Either.left(status); + } + + public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List groups, Map> groupInstancesArtifacts) { + return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts); + } + + public Either, StorageOperationStatus> updateGroupsOnComponent(Component component, ComponentTypeEnum componentType, List updatedGroups) { + return groupsOperation.updateGroups(component, componentType, updatedGroups); + } + + public Either, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, ComponentTypeEnum componentType, String instanceId, List updatedGroupInstances) { + return groupsOperation.updateGroupInstances(component, componentType, instanceId, updatedGroupInstances); + } + + public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List groupInstances) { + return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances); + } + + public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map deploymentArtifacts) { + return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts); + } + + public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) { + return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property); + } + + public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) { + return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property); + } + + public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) { + return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property); + } + + public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) { + return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property); + } + + public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) { + this.nodeTypeOperation = nodeTypeOperation; + } + + public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) { + this.topologyTemplateOperation = topologyTemplateOperation; + } + + public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent, ComponentTypeEnum componentType, List inputsToDelete) { + return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS, inputsToDelete.stream().map(i -> i.getName()).collect(Collectors.toList())); } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java index 0ac5a8dbe4..03a5f41d55 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java @@ -117,8 +117,8 @@ public class ModelConverter { return vertexType; } - private static boolean isAtomicComponent(ResourceTypeEnum resourceType) { - if (resourceType == null || resourceType == ResourceTypeEnum.VF) + public static boolean isAtomicComponent(ResourceTypeEnum resourceType) { + if (resourceType == null || resourceType == ResourceTypeEnum.VF || resourceType == ResourceTypeEnum.PNF || resourceType == ResourceTypeEnum.CVFC) return false; return true; } @@ -302,7 +302,7 @@ public class ModelConverter { relationshipPair.setId(relation.getUniqueId()); relationshipPair.setCapabilityOwnerId(relation.getCapabilityOwnerId()); - relationshipPair.setCapabilityUid(relation.getCapabiltyId()); + relationshipPair.setCapabilityUid(relation.getCapabilityId()); relationshipPair.setRequirementOwnerId(relation.getRequirementOwnerId()); relationshipPair.setRequirementUid(relation.getRequirementId()); relationshipPair.setRequirement(relation.getRequirement()); @@ -326,7 +326,7 @@ public class ModelConverter { requirementCapabilityRelDef.setToId(relation.getToNode()); requirementCapabilityRelDef.setUniqueId(p.getId()); requirementCapabilityRelDef.setCapabilityOwnerId(p.getCapabilityOwnerId()); - requirementCapabilityRelDef.setCapabiltyId(p.getCapabilityUid()); + requirementCapabilityRelDef.setCapabilityId(p.getCapabilityUid()); requirementCapabilityRelDef.setRequirementOwnerId(p.getRequirementOwnerId()); requirementCapabilityRelDef.setRequirementId(p.getRequirementUid()); requirementCapabilityRelDef.setRequirement(p.getRequirement()); @@ -518,6 +518,24 @@ public class ModelConverter { resource.setToscaResourceName((String) toscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); resource.setVendorName((String) toscaElement.getMetadataValue(JsonPresentationFields.VENDOR_NAME)); resource.setVendorRelease((String) toscaElement.getMetadataValue(JsonPresentationFields.VENDOR_RELEASE)); + // field isn't mandatory , but shouldn't be null(should be an empty string instead) + if (((String) toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER)) != null){ + resource.setResourceVendorModelNumber(((String) toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER))); + } else { + resource.setResourceVendorModelNumber(""); + } + } else if (component.getComponentType() == ComponentTypeEnum.SERVICE) { + Service service = (Service) component; + if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_TYPE)) != null){ + service.setServiceType(((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_TYPE))); + } else { + service.setServiceType(""); + } + if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_ROLE)) != null){ + service.setServiceRole(((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_ROLE))); + } else { + service.setServiceRole(""); + } } component.setConformanceLevel((String) toscaElement.getMetadataValue(JsonPresentationFields.CONFORMANCE_LEVEL)); component.setIcon((String) toscaElement.getMetadataValue(JsonPresentationFields.ICON)); @@ -945,6 +963,24 @@ public class ModelConverter { toscaElement.setMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME, ((Resource) component).getToscaResourceName()); toscaElement.setMetadataValue(JsonPresentationFields.VENDOR_NAME, ((Resource) component).getVendorName()); toscaElement.setMetadataValue(JsonPresentationFields.VENDOR_RELEASE, ((Resource) component).getVendorRelease()); + // field isn't mandatory , but shouldn't be null(should be an empty string instead) + if (((Resource) component).getResourceVendorModelNumber() != null){ + toscaElement.setMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER, ((Resource) component).getResourceVendorModelNumber()); + } else { + toscaElement.setMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER, ""); + } + } else if (component.getComponentType() == ComponentTypeEnum.SERVICE) { + // field isn't mandatory , but shouldn't be null(should be an empty string instead) + if (((Service) component).getServiceType() != null){ + toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_TYPE, ((Service) component).getServiceType()); + } else { + toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_TYPE, ""); + } + if (((Service) component).getServiceRole() != null){ + toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_ROLE, ((Service) component).getServiceRole()); + } else { + toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_ROLE, ""); + } } toscaElement.setMetadataValue(JsonPresentationFields.CONFORMANCE_LEVEL, component.getConformanceLevel()); toscaElement.setMetadataValue(JsonPresentationFields.IS_DELETED, component.getIsDeleted()); @@ -955,7 +991,7 @@ public class ModelConverter { toscaElement.setMetadataValue(JsonPresentationFields.CONTACT_ID, component.getContactId()); } - private static boolean isAtomicComponent(Component component) { + public static boolean isAtomicComponent(Component component) { ComponentTypeEnum componentType = component.getComponentType(); if (!componentType.equals(ComponentTypeEnum.RESOURCE)) { return false; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IServiceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IServiceOperation.java index f08c52e0fa..51f21ce5b8 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IServiceOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IServiceOperation.java @@ -24,10 +24,7 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.openecomp.sdc.be.model.DistributionStatusEnum; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import fj.data.Either; @@ -41,6 +38,8 @@ public interface IServiceOperation extends IComponentOperation { public Either getService(String uniqueId, boolean inTransaction); + public Either getService(String uniqueId, ComponentParametersView componentParametersView, boolean inTransaction); + public Either deleteService(String uniqueId); public Either deleteService(String uniqueId, boolean inTransaction); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java index 2847367999..f0e4056663 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java @@ -39,7 +39,6 @@ import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.IComplexDefaultValue; import org.openecomp.sdc.be.model.PropertyConstraint; @@ -50,8 +49,6 @@ import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter; import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter; import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator; -import org.openecomp.sdc.be.resources.data.CapabilityInstData; -import org.openecomp.sdc.be.resources.data.PropertyValueData; import org.openecomp.sdc.be.resources.data.ResourceMetadataData; import org.openecomp.sdc.be.resources.data.UniqueIdData; import org.slf4j.Logger; @@ -118,6 +115,7 @@ public abstract class AbstractOperation { log.debug("Before adding {} to graph. data = {}", defName, someData); + @SuppressWarnings("unchecked") Either eitherSomeData = titanGenericDao.createNode(someData); log.debug("After adding {} to graph. status is = {}", defName, eitherSomeData); @@ -329,7 +327,7 @@ public abstract class AbstractOperation { value = jsonElement.toString(); } - return value; + return value; } protected Either getInnerType(ToscaPropertyType type, Supplier schemeGen) { @@ -368,7 +366,7 @@ public abstract class AbstractOperation { public List convertConstraints(List constraints) { - if (constraints == null || constraints.size() == 0) { + if (constraints == null || constraints.isEmpty()) { return null; } @@ -378,7 +376,6 @@ public abstract class AbstractOperation { Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); return constraints.stream().map(c -> gson.fromJson(c, PropertyConstraint.class)).collect(Collectors.toList()); - } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java index 43e4d0683b..cb9adeda3f 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java @@ -710,6 +710,13 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo case VL: componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.VL); break; + case CVFC: + componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.CVFC); + break; + case PNF: + componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.PNF); + break; + } break; default: diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java index e06649bf77..9d9814efcb 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java @@ -1963,6 +1963,7 @@ public abstract class ComponentOperation { case "service": properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VFC.name())); properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VFCMT.name())); + properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.CVFC.name())); // properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VL.name())); // hasNotPpropertiesToMatch.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), // ResourceTypeEnum.VFC.name()); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java index f9057217a6..413ce4c2fa 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java @@ -155,7 +155,6 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO @Override public Either getGroupType(String uniqueId, boolean inTransaction) { return getElementType(this::getGroupTypeByUid, uniqueId, inTransaction); - } @Override diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java index adea89b9ea..70efe12b86 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java @@ -167,7 +167,6 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp @Override public Either getPolicyType(String uniqueId, boolean inTransaction) { return getElementType(this::getPolicyTypeByUid, uniqueId, inTransaction); - } private Either getPolicyTypeByUid(String uniqueId) { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java index c40c59facf..0673033546 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java @@ -188,6 +188,9 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T private Object convertDataTypeToToscaMap(String innerType, Map dataTypes, final boolean isScalarF, JsonElement entryValue) { Object convertedValue; + if (entryValue.isJsonPrimitive()) { + return json2JavaPrimitive(entryValue.getAsJsonPrimitive()); + } JsonObject asJsonObjectIn = entryValue.getAsJsonObject(); DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatStringValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatStringValidator.java index 0e7b7f6648..8c63090e03 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatStringValidator.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatStringValidator.java @@ -44,8 +44,8 @@ public class HeatStringValidator implements PropertyTypeValidator { return true; } - String coverted = ValidationUtils.removeNoneUtf8Chars(value); - return ValidationUtils.validateIsEnglish(coverted); + String converted = ValidationUtils.removeNoneUtf8Chars(value); + return ValidationUtils.validateIsEnglish(converted); } @Override diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/KeyValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/KeyValidator.java index 4b11e26d05..73b5e939ef 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/KeyValidator.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/KeyValidator.java @@ -49,8 +49,8 @@ public class KeyValidator implements PropertyTypeValidator { if (value.length() > STRING_MAXIMUM_LENGTH) { return false; } - String coverted = ValidationUtils.removeNoneUtf8Chars(value); - return ValidationUtils.validateIsEnglish(coverted); + String converted = ValidationUtils.removeNoneUtf8Chars(value); + return ValidationUtils.validateIsEnglish(converted); } @Override diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java index 750941cc0b..a096990ad7 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java @@ -68,8 +68,8 @@ public class StringValidator implements PropertyTypeValidator { log.debug("parameter String length {} is higher than configured({})", value.length(), STRING_MAXIMUM_LENGTH); return false; } - String coverted = ValidationUtils.removeNoneUtf8Chars(value); - boolean isValid = ValidationUtils.validateIsAscii(coverted); + String converted = ValidationUtils.removeNoneUtf8Chars(value); + boolean isValid = ValidationUtils.validateIsAscii(converted); if (false == isValid && log.isDebugEnabled()) { log.debug("parameter String value {} is not an ascii string.", value.substring(0, Math.min(value.length(), 20))); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceMetadata.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceMetadata.java index a2695f8c79..68abb4d749 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceMetadata.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceMetadata.java @@ -29,6 +29,7 @@ public class UiResourceMetadata extends UiComponentMetadata { private String vendorName; private String vendorRelease; + private String resourceVendorModelNumber; private ResourceTypeEnum resourceType = ResourceTypeEnum.VFC; private Boolean isAbstract; private String cost; @@ -41,6 +42,7 @@ public class UiResourceMetadata extends UiComponentMetadata { super(categories, metadata); this.vendorName = metadata.getVendorName(); this.vendorRelease = metadata.getVendorRelease(); + this.resourceVendorModelNumber = metadata.getResourceVendorModelNumber(); this.resourceType = metadata.getResourceType(); this.cost = metadata.getCost(); this.licenseType = metadata.getLicenseType(); @@ -75,6 +77,14 @@ public class UiResourceMetadata extends UiComponentMetadata { public void setVendorRelease(String vendorRelease) { this.vendorRelease = vendorRelease; } + + public String getResourceVendorModelNumber() { + return resourceVendorModelNumber; + } + + public void setResourceVendorModelNumber(String resourceVendorModelNumber) { + this.resourceVendorModelNumber = resourceVendorModelNumber; + } public ResourceTypeEnum getResourceType() { return resourceType; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java index 99d586afd2..9a79a26881 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java @@ -30,12 +30,16 @@ public class UiServiceMetadata extends UiComponentMetadata { private String distributionStatus; private Boolean ecompGeneratedNaming; private String namingPolicy; + private String serviceType; + private String serviceRole; public UiServiceMetadata(List categories, ServiceMetadataDataDefinition metadata) { super(categories, metadata); this.distributionStatus = metadata.getDistributionStatus(); this.ecompGeneratedNaming = metadata.isEcompGeneratedNaming(); this.namingPolicy = metadata.getNamingPolicy(); + this.serviceType = metadata.getServiceType(); + this.serviceRole = metadata.getServiceRole(); } public String getDistributionStatus() { @@ -61,5 +65,21 @@ public class UiServiceMetadata extends UiComponentMetadata { public void setNamingPolicy(String namingPolicy) { this.namingPolicy = namingPolicy; } + + public String getServiceType() { + return serviceType; + } + + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + + public String getServiceRole() { + return serviceRole; + } + + public void setServiceRole(String serviceRole) { + this.serviceRole = serviceRole; + } } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperationsTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperationsTest.java new file mode 100644 index 0000000000..3f80806292 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperationsTest.java @@ -0,0 +1,85 @@ +package org.openecomp.sdc.be.model.jsontitan.operations; + +import fj.data.Either; +import org.junit.Test; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.*; + +public class ArtifactsOperationsTest { + + private static final String SERVICE_ID = "serviceId"; + private static final String INSTANCE_ID = "instanceId"; + private ArtifactsOperations testInstance = mock(ArtifactsOperations.class, CALLS_REAL_METHODS); + + @Test + public void getInstanceArtifacts_collectAllInstanceArtifacts() throws Exception { + Map instanceArtifacts = Collections.singletonMap(INSTANCE_ID, getArtifactsByInstance("name1")); + + Map instanceDeploymentArtifacts = new HashMap<>(); + instanceDeploymentArtifacts.put(INSTANCE_ID, getArtifactsByInstance("name2", "name3")); + instanceDeploymentArtifacts.put("instanceId2", getArtifactsByInstance("name4")); + + doReturn(Either.left(instanceArtifacts)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INSTANCE_ARTIFACTS); + doReturn(Either.left(instanceDeploymentArtifacts)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); + Either, StorageOperationStatus> allInstArtifacts = testInstance.getAllInstanceArtifacts(SERVICE_ID, INSTANCE_ID); + + assertTrue(allInstArtifacts.isLeft()); + assertEquals(allInstArtifacts.left().value().size(), 3); + assertTrue(allInstArtifacts.left().value().containsKey("name1")); + assertTrue(allInstArtifacts.left().value().containsKey("name2")); + assertTrue(allInstArtifacts.left().value().containsKey("name3")); + assertFalse(allInstArtifacts.left().value().containsKey("name4"));//this key is of different instance + } + + @Test + public void getInstanceArtifacts_noArtifactsForInstance() throws Exception { + Map instanceArtifacts = Collections.singletonMap(INSTANCE_ID, getArtifactsByInstance("name1")); + + doReturn(Either.left(instanceArtifacts)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INSTANCE_ARTIFACTS); + doReturn(Either.left(new HashMap<>())).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); + Either, StorageOperationStatus> allInstArtifacts = testInstance.getAllInstanceArtifacts(SERVICE_ID, "someOtherInstance"); + + assertTrue(allInstArtifacts.isLeft()); + assertTrue(allInstArtifacts.left().value().isEmpty()); + } + + @Test + public void getInstanceArtifacts_errorGettingInstanceArtifacts() throws Exception { + doReturn(Either.right(TitanOperationStatus.GENERAL_ERROR)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INSTANCE_ARTIFACTS); + Either, StorageOperationStatus> allInstArtifacts = testInstance.getAllInstanceArtifacts(SERVICE_ID, INSTANCE_ID); + verify(testInstance, times(0)).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); + assertTrue(allInstArtifacts.isRight()); + } + + @Test + public void getAllInstanceArtifacts_errorGettingDeploymentArtifacts() throws Exception { + doReturn(Either.left(new HashMap<>())).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INSTANCE_ARTIFACTS); + doReturn(Either.right(TitanOperationStatus.GENERAL_ERROR)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); + Either, StorageOperationStatus> allInstArtifacts = testInstance.getAllInstanceArtifacts(SERVICE_ID, INSTANCE_ID); + assertTrue(allInstArtifacts.isRight()); + } + + private ToscaDataDefinition getArtifactsByInstance(String ... artifactsNames) { + MapArtifactDataDefinition artifactsByInstance = new MapArtifactDataDefinition(); + Map artifactsByName = new HashMap<>(); + for (String artifactName : artifactsNames) { + artifactsByName.put(artifactName, new ArtifactDataDefinition()); + } + artifactsByInstance.setMapToscaDataDefinition(artifactsByName); + return artifactsByInstance; + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTest.java new file mode 100644 index 0000000000..339023f9a4 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTest.java @@ -0,0 +1,344 @@ +package org.openecomp.sdc.be.model.jsontitan.operations; + +import fj.data.Either; +import org.apache.cassandra.cql3.CQL3Type; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TestName; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsontitan.utils.GraphTestUtils; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.*; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Created by chaya on 6/12/2017. + */ + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +public class ToscaElementOperationTest extends ModelTestBase{ + + private List allVertices = new ArrayList<>(); + private boolean isInitialized = false; + + @javax.annotation.Resource + ToscaElementOperationTestImpl toscaElementOperation; + + @javax.annotation.Resource + TitanDao titanDao; + + @BeforeClass + public static void initTest(){ + ModelTestBase.init(); + + } + + @Rule + public TestName testName = new TestName(); + + @Before + public void beforeTest() { + if (!isInitialized) { + GraphTestUtils.clearGraph(titanDao); + //exportGraphMl(titanDao.getGraph().left().value(),""); + initGraphForTest(); + isInitialized = true; + } + } + + @Test + public void testGetAllHighestResourcesNoFilter() { + + Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, null, true); + assertTrue(highestResourcesRes.isLeft()); + List highestResources = highestResourcesRes.left().value(); + // calculate expected count value + long highestResourcesExpectedCount = calculateCount(new HashMap() { + { + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + } + }, null); + assertEquals(highestResources.stream().count(), highestResourcesExpectedCount); + } + + @Test + public void testGetAllResourcesCertifiedNoFilter() { + Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, null, false); + assertTrue(highestResourcesRes.isLeft()); + List highestResources = highestResourcesRes.left().value(); + // calculate expected count value + long highestResourcesExpectedCount = calculateCount(new HashMap() { + { + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + } + }, null); + highestResourcesExpectedCount += calculateCount(new HashMap() { + { + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + } + }, new HashMap() { + { + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + } + }); + assertEquals(highestResources.stream().count(), highestResourcesExpectedCount); + } + + @Test + public void testGetHighestResourcesExclude() { + + // exclude VFCMT + List excludeList = Arrays.asList(ResourceTypeEnum.VFCMT); + assertTrue(genericTestGetResourcesWithExcludeList(excludeList)); + + // exclude CP & VL + excludeList = Arrays.asList(ResourceTypeEnum.VL, ResourceTypeEnum.CP); + assertTrue(genericTestGetResourcesWithExcludeList(excludeList)); + + // exclude CP & VL & VF & VFC + excludeList = Arrays.asList(ResourceTypeEnum.VL, ResourceTypeEnum.CP, ResourceTypeEnum.VF, ResourceTypeEnum.VFC); + assertTrue(genericTestGetResourcesWithExcludeList(excludeList)); + } + + @Test + public void testGetAllResourcesCertifiedExclude() { + // exclude VFCMT + List excludeList = Arrays.asList(ResourceTypeEnum.VFCMT); + assertTrue(genericTestGetCertifiedResourcesWithExcludeList(excludeList)); + + // exclude CP & VL + excludeList = Arrays.asList(ResourceTypeEnum.VL, ResourceTypeEnum.CP); + assertTrue(genericTestGetCertifiedResourcesWithExcludeList(excludeList)); + + // exclude CP & VL & VF & VFC + excludeList = Arrays.asList(ResourceTypeEnum.VL, ResourceTypeEnum.CP, ResourceTypeEnum.VF, ResourceTypeEnum.VFC); + assertTrue(genericTestGetCertifiedResourcesWithExcludeList(excludeList)); + } + + @Test + public void testGetAllHighestServicesNoFilter() { + Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, true); + assertTrue(highestResourcesRes.isLeft()); + List highestResources = highestResourcesRes.left().value(); + // calculate expected count value + long highestResourcesExpectedCount = calculateCount(new HashMap() { + { + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + } + }, null); + assertEquals(highestResources.stream().count(), highestResourcesExpectedCount); + } + + @Test + public void testGetAllCertifiedServicesNoFilter() { + Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, false); + assertTrue(highestResourcesRes.isLeft()); + List highestResources = highestResourcesRes.left().value(); + // calculate expected count value + long highestResourcesExpectedCount = calculateCount(new HashMap() { + { + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + } + }, null); + highestResourcesExpectedCount += calculateCount(new HashMap() { + { + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + } + }, new HashMap() { + { + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + } + }); + assertEquals(highestResources.stream().count(), highestResourcesExpectedCount); + } + + @Test + public void testGetServicesExcludeList() { + List excludeList = Arrays.asList(ResourceTypeEnum.VF, ResourceTypeEnum.VFCMT); + Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, excludeList, true); + assertTrue(highestResourcesRes.isLeft()); + List highestResources = highestResourcesRes.left().value(); + // calculate expected count value + long highestResourcesExpectedCount = calculateCount(new HashMap() { + { + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + } + }, null); + assertEquals(highestResources.stream().count(), highestResourcesExpectedCount); + } + + @Test + public void testGetCertifiedServicesExcludeList() { + List excludeList = Arrays.asList(ResourceTypeEnum.VL); + Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, excludeList, false); + assertTrue(highestResourcesRes.isLeft()); + List highestResources = highestResourcesRes.left().value(); + // calculate expected count value + long highestResourcesExpectedCount = calculateCount(new HashMap() { + { + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + } + }, null); + highestResourcesExpectedCount += calculateCount(new HashMap() { + { + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + } + }, new HashMap() { + { + put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + } + }); + assertEquals(highestResources.stream().count(), highestResourcesExpectedCount); + } + + private boolean genericTestGetResourcesWithExcludeList(List excludeList) { + Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE,excludeList, true); + assertTrue(highestResourcesRes.isLeft()); + List highestResources = highestResourcesRes.left().value(); + // calculate expected count value + long highestResourcesExpectedCount = calculateCount(new HashMap() { + { + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + } + }, new HashMap() { + { + put(GraphPropertyEnum.RESOURCE_TYPE, excludeList); + } + }); + return highestResources.stream().count() == (highestResourcesExpectedCount); + } + + private boolean genericTestGetCertifiedResourcesWithExcludeList(List excludeList) { + Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludeList, false); + assertTrue(highestResourcesRes.isLeft()); + List highestResources = highestResourcesRes.left().value(); + // calculate expected count value + long highestResourcesExpectedCount = calculateCount(new HashMap() { + { + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + } + }, new HashMap() { + { + put(GraphPropertyEnum.RESOURCE_TYPE, excludeList); + } + }); + highestResourcesExpectedCount += calculateCount(new HashMap() { + { + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + } + }, new HashMap() { + { + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + put(GraphPropertyEnum.RESOURCE_TYPE, excludeList); + } + }); + return highestResources.stream().count() == highestResourcesExpectedCount; + } + + private void initGraphForTest() { + Map highstVerticesProps = new HashMap() { + { + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + } + }; + + Map certifiedVerticesProps = new HashMap() { + { + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + } + }; + + // add vertices with higestVersion = true + allVertices.add(GraphTestUtils.createResourceVertex(titanDao, highstVerticesProps, ResourceTypeEnum.VF)); + allVertices.add(GraphTestUtils.createResourceVertex(titanDao, highstVerticesProps, ResourceTypeEnum.VFC)); + allVertices.add(GraphTestUtils.createResourceVertex(titanDao, highstVerticesProps, ResourceTypeEnum.VFCMT)); + allVertices.add(GraphTestUtils.createResourceVertex(titanDao, highstVerticesProps, ResourceTypeEnum.VL)); + allVertices.add(GraphTestUtils.createResourceVertex(titanDao, highstVerticesProps, ResourceTypeEnum.CP)); + allVertices.add(GraphTestUtils.createServiceVertex(titanDao, highstVerticesProps)); + + // add vertices with non-additional properties + for (int i=0 ; i<2 ; i++) { + allVertices.add(GraphTestUtils.createResourceVertex(titanDao, new HashMap<>(), ResourceTypeEnum.VF)); + allVertices.add(GraphTestUtils.createResourceVertex(titanDao, new HashMap<>(), ResourceTypeEnum.VFC)); + allVertices.add(GraphTestUtils.createResourceVertex(titanDao, new HashMap<>(), ResourceTypeEnum.VFCMT)); + allVertices.add(GraphTestUtils.createResourceVertex(titanDao, new HashMap<>(), ResourceTypeEnum.VL)); + allVertices.add(GraphTestUtils.createResourceVertex(titanDao, new HashMap<>(), ResourceTypeEnum.CP)); + allVertices.add(GraphTestUtils.createServiceVertex(titanDao, new HashMap<>())); + } + + // add certified vertices + for (int i=0; i<3; i++) { + allVertices.add(GraphTestUtils.createResourceVertex(titanDao, certifiedVerticesProps, ResourceTypeEnum.VF)); + allVertices.add(GraphTestUtils.createResourceVertex(titanDao, certifiedVerticesProps, ResourceTypeEnum.VFC)); + allVertices.add(GraphTestUtils.createResourceVertex(titanDao, certifiedVerticesProps, ResourceTypeEnum.VFCMT)); + allVertices.add(GraphTestUtils.createResourceVertex(titanDao, certifiedVerticesProps, ResourceTypeEnum.VL)); + allVertices.add(GraphTestUtils.createResourceVertex(titanDao, certifiedVerticesProps, ResourceTypeEnum.CP)); + allVertices.add(GraphTestUtils.createServiceVertex(titanDao, certifiedVerticesProps)); + } + //allVertices.stream().forEach( v -> System.out.println("type: "+v.getMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE))); + //String result = GraphTestUtils.exportGraphMl(titanDao.getGraph().left().value(), ""); + //System.out.println("graph is: " + result); + } + + private long calculateCount(HashMap hasProps, Map doesntHaveProps){ + return allVertices.stream(). + filter(v -> { + Map vertexProps = v.getMetadataProperties(); + if (hasProps != null) { + for (Map.Entry prop: hasProps.entrySet()){ + Object value = vertexProps.get(prop.getKey()); + if ( value == null || !value.equals(prop.getValue())) { + return false; + } + } + } + + if (doesntHaveProps != null) { + for (Map.Entry prop : doesntHaveProps.entrySet()) { + Object value = vertexProps.get(prop.getKey()); + Object propValue = prop.getValue(); + if ( value != null && propValue != null && propValue instanceof List ) { + for (ResourceTypeEnum propVal : (List)propValue) { + if (propVal.name().equals(value)) { + return false; + } + } + } + else if (value != null && value.equals(propValue)){ + return false; + } + } + } + return true; + }).count(); + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTestImpl.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTestImpl.java new file mode 100644 index 0000000000..27fbce4776 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTestImpl.java @@ -0,0 +1,74 @@ +package org.openecomp.sdc.be.model.jsontitan.operations; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +/** + * Created by cb478c on 6/13/2017. + */ +@org.springframework.stereotype.Component("test-tosca-element-operation") +public class ToscaElementOperationTestImpl extends ToscaElementOperation { + + @Override + protected Either getLightComponent(GraphVertex vertexComponent, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) { + titanDao.parseVertexProperties(vertexComponent, JsonParseFlagEnum.ParseMetadata); + T toscaElement = convertToComponent(vertexComponent); + return Either.left(toscaElement); + } + + @Override + public Either getToscaElement(String uniqueId, ComponentParametersView componentParametersView) { + return null; + } + + @Override + public Either getToscaElement(GraphVertex toscaElementVertex, ComponentParametersView componentParametersView) { + return null; + } + + @Override + public Either deleteToscaElement(GraphVertex toscaElementVertex) { + return null; + } + + @Override + public Either createToscaElement(ToscaElement toscaElement) { + return null; + } + + @Override + protected TitanOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement) { + return null; + } + + @Override + protected TitanOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement) { + return null; + } + + @Override + protected TitanOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement) { + return null; + } + + @Override + protected StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV) { + return null; + } + + @Override + protected StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV) { + return null; + } + + @Override + public void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag) { + + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/GraphTestUtils.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/GraphTestUtils.java new file mode 100644 index 0000000000..8e2a283559 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/GraphTestUtils.java @@ -0,0 +1,114 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.jsontitan.utils; + +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; +import org.apache.tinkerpop.gremlin.structure.io.IoCore; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.util.Iterator; +import java.util.Map; +import java.util.UUID; + +public final class GraphTestUtils { + + public static GraphVertex createResourceVertex(TitanDao titanDao, Map metadataProps, ResourceTypeEnum type) { + GraphVertex vertex = new GraphVertex(); + if (type == ResourceTypeEnum.VF) { + vertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE); + vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.TOPOLOGY_TEMPLATE); + } else { + vertex.setLabel(VertexTypeEnum.NODE_TYPE); + vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.NODE_TYPE); + } + String uuid = UUID.randomUUID().toString(); + vertex.setUniqueId(uuid); + + vertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uuid); + vertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + vertex.addMetadataProperty(GraphPropertyEnum.RESOURCE_TYPE, type.name()); + vertex.addMetadataProperty(GraphPropertyEnum.IS_ABSTRACT, false); + for (Map.Entry prop : metadataProps.entrySet()) { + vertex.addMetadataProperty(prop.getKey(), prop.getValue()); + } + titanDao.createVertex(vertex); + titanDao.commit(); + return vertex; + } + + public static GraphVertex createServiceVertex(TitanDao titanDao, Map metadataProps){ + GraphVertex vertex = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE); + String uuid = UUID.randomUUID().toString(); + vertex.setUniqueId(uuid); + vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.TOPOLOGY_TEMPLATE); + vertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uuid); + vertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + for (Map.Entry prop : metadataProps.entrySet()) { + vertex.addMetadataProperty(prop.getKey(), prop.getValue()); + } + titanDao.createVertex(vertex); + titanDao.commit(); + return vertex; + } + + public static void clearGraph(TitanDao titanDao) { + Either graphResult = titanDao.getGraph(); + TitanGraph graph = graphResult.left().value(); + + Iterable vertices = graph.query().vertices(); + if (vertices != null) { + Iterator iterator = vertices.iterator(); + while (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + vertex.remove(); + } + } + titanDao.commit(); + } + + public static String exportGraphMl(TitanGraph graph, String outputDirectory) { + String result = null; + String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".graphml"; + try { + try (final OutputStream os = new BufferedOutputStream(new FileOutputStream(outputFile))) { + graph.io(IoCore.graphml()).writer().normalize(true).create().writeGraph(os, graph); + } + result = outputFile; + graph.tx().commit(); + } catch (Exception e) { + graph.tx().rollback(); + e.printStackTrace(); + } + return result; + } +} -- cgit 1.2.3-korg