diff options
author | Michael Lando <ml636r@att.com> | 2017-07-17 21:12:03 +0300 |
---|---|---|
committer | Michael Lando <ml636r@att.com> | 2017-07-17 21:12:03 +0300 |
commit | 75aacbbe1acf78fa53378f07f0a8c7769449a17e (patch) | |
tree | 68a9799eb8f4704dd9a3d513401df9bb11af7739 /catalog-model/src/main/java/org | |
parent | dec02e7cc74e1c401be51bd9d266575e1e008f5f (diff) |
[SDC] rebase 1710 code
Change-Id: I532ed68979fee7840ea8a5395e7e965b155fb9f9
Signed-off-by: Michael Lando <ml636r@att.com>
Diffstat (limited to 'catalog-model/src/main/java/org')
32 files changed, 2578 insertions, 2269 deletions
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<String, ArtifactDefinition> getAllArtifacts() { + HashMap<String, ArtifactDefinition> 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<CategoryDefinition> 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<PropertyRule> 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<String, byte[]> csar; + Map<String, String> createdNodesToscaResourceNames; + Queue<String> cvfcToCreateQueue; + + public ImportCsarInfo(String vfResourceName, User modifier, String csarUUID, Map<String, byte[]> 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<String, byte[]> getCsar() { + return csar; + } + + public void setCsar(Map<String, byte[]> csar) { + this.csar = csar; + } + + public Map<String, String> getCreatedNodesToscaResourceNames() { + return createdNodesToscaResourceNames; + } + + public void setCreatedNodesToscaResourceNames(Map<String, String> createdNodesToscaResourceNames) { + this.createdNodesToscaResourceNames = createdNodesToscaResourceNames; + } + + public Queue<String> getCvfcToCreateQueue() { + return cvfcToCreateQueue; + } + + public void setCvfcToCreateQueue(Queue<String> 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<String> derivedFrom; + boolean isNested; + Map<String, Object> 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<String> getDerivedFrom() { + return derivedFrom; + } + public void setDerivedFrom(List<String> derivedFrom) { + this.derivedFrom = derivedFrom; + } + public boolean isNested() { + return isNested; + } + public void setNested(boolean isNested) { + this.isNested = isNested; + } + + public Map<String, Object> getMappedToscaTemplate() { + return mappedToscaTemplate; + } + + public void setMappedToscaTemplate(Map<String, Object> 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<String, List<UploadCapInfo>> capabilities; private Map<String, List<UploadReqInfo>> requirements; private Map<String, List<UploadPropInfo>> properties; + private Map<String, String> capabilitiesNamesToUpdate; + private Map<String, String> requirementsNamesToUpdate; public Map<String, List<UploadPropInfo>> getProperties() { return properties; @@ -70,4 +72,20 @@ public class UploadComponentInstanceInfo { this.requirements = requirements; } + public Map<String, String> getCapabilitiesNamesToUpdate() { + return capabilitiesNamesToUpdate; + } + + public void setCapabilitiesNamesToUpdate(Map<String, String> capabilitiesNamesToUpdate) { + this.capabilitiesNamesToUpdate = capabilitiesNamesToUpdate; + } + + public Map<String, String> getRequirementsNamesToUpdate() { + return requirementsNamesToUpdate; + } + + public void setRequirementsNamesToUpdate(Map<String, String> 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<Map<String, ArtifactDefinition>, StorageOperationStatus> getAllInstanceArtifacts(String parentId, String instanceId) { + Map<String, ArtifactDataDefinition> resMap = new HashMap<>(); + Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> instArtifacts = getInstanceArtifactsByLabel(parentId, instanceId, EdgeLabelEnum.INSTANCE_ARTIFACTS); + if (instArtifacts.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(instArtifacts.right().value())); + } + Either<Map<String, ArtifactDataDefinition>, 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<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId) { Either<Map<String, ArtifactDefinition>, TitanOperationStatus> foundArtifact = null; @@ -384,36 +405,36 @@ public class ArtifactsOperations extends BaseOperation { } private Either<Map<String, ArtifactDefinition>, TitanOperationStatus> getArtifactByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) { + Either<Map<String, ArtifactDataDefinition>, 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<String, ArtifactDataDefinition> artifactDataMap = artifactsEither.left().value(); + return Either.left(convertArtifactMapToArtifactDefinitionMap(artifactDataMap)); + } - Map<String, ArtifactDefinition> artMap = null; - Map<String, ArtifactDataDefinition> artifactDataMap = null; + private Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> getArtifactsDataByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) { + return edgeLabelEnum.isInstanceArtifactsLabel() ? getInstanceArtifactsByLabel(parentId, instanceId, edgeLabelEnum) : getDataFromGraph(parentId, edgeLabelEnum); + } - if (edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) { - Either<Map<String, ArtifactDataDefinition>, 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<Map<String, MapArtifactDataDefinition>, 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<String, MapArtifactDataDefinition> mapArtifacts = resultEither.left().value(); - MapArtifactDataDefinition artifactPerInstance = mapArtifacts.get(instanceId); - if (artifactPerInstance != null) { - artifactDataMap = artifactPerInstance.getMapToscaDataDefinition(); - } - } + private Map<String, ArtifactDefinition> convertArtifactMapToArtifactDefinitionMap(Map<String, ArtifactDataDefinition> artifactDataMap) { + Map<String, ArtifactDefinition> 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<Map<String, ArtifactDataDefinition>, TitanOperationStatus> getInstanceArtifactsByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) { + Either<Map<String, MapArtifactDataDefinition>, 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<String, MapArtifactDataDefinition> mapArtifacts = resultEither.left().value(); + MapArtifactDataDefinition artifactPerInstance = mapArtifacts.get(instanceId); + return artifactPerInstance != null ? Either.left(artifactPerInstance.getMapToscaDataDefinition()) : Either.left(new HashMap<>()); } private Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> 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<String> uniqueKeys, JsonPresentationFields mapKeyField) { + public StorageOperationStatus deleteToscaDataElements(String toscaElementUid, EdgeLabelEnum edgeLabel, List<String> uniqueKeys) { StorageOperationStatus statusRes = StorageOperationStatus.OK; Either<GraphVertex, TitanOperationStatus> 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<String> 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<String> 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<String> uniqueKeys) { StorageOperationStatus result = null; GraphVertex toscaDataVertex; - Map<String, ToscaDataDefinition> existingToscaDataMap = null; + Map<String, ToscaDataDefinition> existingToscaDataMap; Either<GraphVertex, TitanOperationStatus> 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<String> 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<GraphVertex, TitanOperationStatus> 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<String, CompositionDataDefinition> jsonComposition = (Map<String, CompositionDataDefinition>) containerV.getJson(); CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue()); Map<String, ComponentInstanceDataDefinition> componentInstances = compositionDataDefinition.getComponentInstances(); @@ -1092,16 +1092,15 @@ public class NodeTemplateOperation extends BaseOperation { Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES); if (capResult.isRight()) { return Either.right(capResult.right().value()); - } - Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty = capResult.left().value().getRight(); + Map<String, MapListCapabiltyDataDefinition> calculatedCapability = capResult.left().value().getRight(); Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); if (capResult.isRight()) { return Either.right(capResult.right().value()); } - Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty = capFullResult.left().value().getRight(); + Map<String, MapListCapabiltyDataDefinition> fulfilledCapability = capFullResult.left().value().getRight(); Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, 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<String, MapListRequirementDataDefinition> fullfilledRequirement = reqFullResult.left().value().getRight(); + Map<String, MapListRequirementDataDefinition> fulfilledRequirement = reqFullResult.left().value().getRight(); for (RequirementAndRelationshipPair relationPair : relationPairList) { Iterator<Entry<String, RelationshipInstDataDefinition>> 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<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListRequirementDataDefinition> 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<RequirementDataDefinition> 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<RequirementDataDefinition> 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<String, MapListCapabiltyDataDefinition> calculatedCapabilty, Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty, String toResInstanceUid, + + private StorageOperationStatus updateCalculatedCapabiltyAfterDeleteRelation(Map<String, MapListCapabiltyDataDefinition> calculatedCapability, Map<String, MapListCapabiltyDataDefinition> 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<CapabilityDataDefinition> 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<CapabilityDataDefinition> 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<String, MapListCapabiltyDataDefinition> calculatedCapabilty, Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty, String toResInstanceUid, - RelationshipInstDataDefinition relation) { - MapListCapabiltyDataDefinition capByInstance = fullFilledCapabilty.get(toResInstanceUid); + private StorageOperationStatus moveFromFullFilledCapabilty(Map<String, MapListCapabiltyDataDefinition> calculatedCapability, Map<String, MapListCapabiltyDataDefinition> 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<CapabilityDataDefinition> 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<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListRequirementDataDefinition> 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<RequirementDataDefinition> 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<CapabilityDataDefinition> 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<GraphPropertyEnum, Object> 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<List<String>>() { - }.getType(); + Type listTypeCat = new TypeToken<List<String>>() {}.getType(); List<String> 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<String, ToscaElement> origCompMap) { - fixToscaComponentName(vfInst, origCompMap); + public boolean resolveToscaComponentName(ComponentInstanceDataDefinition vfInst, Map<String, ToscaElement> origCompMap) { + return fixToscaComponentName(vfInst, origCompMap); } private boolean fixToscaComponentName(ComponentInstanceDataDefinition vfInst, Map<String, ToscaElement> 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<ToscaElement,StorageOperationStatus> forceCerificationOfToscaElement(String toscaElementId, String modifierId, String ownerId) { + Either<GraphVertex, StorageOperationStatus> resultUpdate = null; + Either<ToscaElement, StorageOperationStatus> result = null; + GraphVertex toscaElement = null; + GraphVertex modifier = null; + GraphVertex owner; + try { + Either<Map<String, GraphVertex>, 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<EdgePropertyEnum, Object> 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 <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getElementCatalogData(ComponentTypeEnum componentType, ToscaElementTypeEnum toscaElement, boolean isHighestVersions) { + public <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getElementCatalogData(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes, boolean isHighestVersions) { Either<List<GraphVertex>, 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<T, StorageOperationStatus> 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<List<GraphVertex>, TitanOperationStatus> getListOfHighestComponents(ComponentTypeEnum componentType, ToscaElementTypeEnum toscaElement) { + private Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestComponents(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes) { Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<>(); + Map<GraphPropertyEnum, Object> 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<GraphPropertyEnum, Object> 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<List<GraphVertex>, TitanOperationStatus> getListOfHighestAndAllCertifiedComponents(ComponentTypeEnum componentType, ToscaElementTypeEnum toscaElement) { + // highest + (certified && !highest) + public Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestAndAllCertifiedComponents(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes) { long startFetchAllStates = System.currentTimeMillis(); + Either<List<GraphVertex>, TitanOperationStatus> highestNodes = getListOfHighestComponents(componentType, excludeTypes); + Map<GraphPropertyEnum, Object> propertiesToMatchCertified = new HashMap<>(); + Map<GraphPropertyEnum, Object> 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<GraphPropertyEnum, Object> propertiesHasNotToMatchCertified = new HashMap<>(); propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_DELETED, true); + propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - Either<List<GraphVertex>, TitanOperationStatus> certifiedNodes = titanDao.getByCriteria(ToscaElementTypeEnum.getVertexTypeByToscaType(toscaElement), propertiesToMatchCertified, propertiesHasNotToMatchCertified, + Either<List<GraphVertex>, 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<GraphPropertyEnum, Object> 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<GraphPropertyEnum, Object> propertiesHasNotToMatchHighest = new HashMap<>(); - propertiesHasNotToMatchHighest.put(GraphPropertyEnum.IS_DELETED, true); - propertiesHasNotToMatchHighest.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - - Either<List<GraphVertex>, 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<GraphVertex> 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,932 +54,935 @@ 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 <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId) { - - return getToscaElement(componentId, JsonParseFlagEnum.ParseAll); - - } - - public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) { - ComponentParametersView filters = new ComponentParametersView(); - filters.setIgnoreCapabiltyProperties(false); - - return getToscaElement(componentId, filters); - } - - public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, ComponentParametersView filters) { - - Either<GraphVertex, TitanOperationStatus> 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 <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, JsonParseFlagEnum parseFlag) { - - Either<GraphVertex, TitanOperationStatus> 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 <T extends Component> Either<T, StorageOperationStatus> getToscaElement(GraphVertex componentVertex) { - return getToscaElementByOperation(componentVertex); - } - - public Either<Boolean, StorageOperationStatus> validateComponentExists(String componentId) { - - Either<GraphVertex, TitanOperationStatus> 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 <T extends Component> Either<T, StorageOperationStatus> findLastCertifiedToscaElementByUUID(T component) { - Map<GraphPropertyEnum, Object> props = new HashMap<>(); - props.put(GraphPropertyEnum.UUID, component.getUUID()); - props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - - Either<List<GraphVertex>, 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 <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV) { - return getToscaElementByOperation(componentV, new ComponentParametersView()); - } - - private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV, ComponentParametersView filters) { - VertexTypeEnum label = componentV.getLabel(); - - ToscaElementOperation toscaOperation = getToscaElementOperation(componentV); - Either<ToscaElement, StorageOperationStatus> 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 <T extends Component> Either<T, StorageOperationStatus> createToscaComponent(T resource) { - ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource); - - ToscaElementOperation toscaElementOperation = getToscaElementOperation(toscaElement); - Either<ToscaElement, StorageOperationStatus> 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<GraphVertex, TitanOperationStatus> 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<GraphVertex, StorageOperationStatus> result = nodeTypeOperation.markComponentToDelete(componentV); - if (result.isRight()) { - return result.right().value(); - } - return StorageOperationStatus.OK; - } - } - - /** - * - * @param componentId - * @return - */ - public <T extends Component> Either<T, StorageOperationStatus> deleteToscaComponent(String componentId) { - - Either<GraphVertex, TitanOperationStatus> 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<ToscaElement, StorageOperationStatus> 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<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex componentV) { - VertexTypeEnum label = componentV.getLabel(); - Either<ToscaElement, StorageOperationStatus> 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 <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) { - return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName); - - } - - public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) { - return getLatestByName(GraphPropertyEnum.NAME, resourceName); - - } - - public Either<Integer, StorageOperationStatus> validateCsarUuidUniqueness(String csarUUID) { - Either<List<ToscaElement>, StorageOperationStatus> byCsar = null; - - Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>(); - properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID); - - Either<List<GraphVertex>, 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<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null); - - return Either.left(new Integer(resourceList.size())); - - } + @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 <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId) { + + return getToscaElement(componentId, JsonParseFlagEnum.ParseAll); + + } + + public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) { + ComponentParametersView filters = new ComponentParametersView(); + filters.setIgnoreCapabiltyProperties(false); + + return getToscaElement(componentId, filters); + } + + public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, ComponentParametersView filters) { + + Either<GraphVertex, TitanOperationStatus> 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 <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, JsonParseFlagEnum parseFlag) { + + Either<GraphVertex, TitanOperationStatus> 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 <T extends Component> Either<T, StorageOperationStatus> getToscaElement(GraphVertex componentVertex) { + return getToscaElementByOperation(componentVertex); + } + + public Either<Boolean, StorageOperationStatus> validateComponentExists(String componentId) { + + Either<GraphVertex, TitanOperationStatus> 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 <T extends Component> Either<T, StorageOperationStatus> findLastCertifiedToscaElementByUUID(T component) { + Map<GraphPropertyEnum, Object> props = new HashMap<>(); + props.put(GraphPropertyEnum.UUID, component.getUUID()); + props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + Either<List<GraphVertex>, 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 <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV) { + return getToscaElementByOperation(componentV, new ComponentParametersView()); + } + + private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV, ComponentParametersView filters) { + VertexTypeEnum label = componentV.getLabel(); + + ToscaElementOperation toscaOperation = getToscaElementOperation(componentV); + Either<ToscaElement, StorageOperationStatus> 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 <T extends Component> Either<T, StorageOperationStatus> createToscaComponent(T resource) { + ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource); + + ToscaElementOperation toscaElementOperation = getToscaElementOperation(resource); + Either<ToscaElement, StorageOperationStatus> 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<GraphVertex, TitanOperationStatus> 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<GraphVertex, StorageOperationStatus> result = nodeTypeOperation.markComponentToDelete(componentV); + if (result.isRight()) { + return result.right().value(); + } + return StorageOperationStatus.OK; + } + } + + /** + * + * @param componentId + * @return + */ + public <T extends Component> Either<T, StorageOperationStatus> deleteToscaComponent(String componentId) { + + Either<GraphVertex, TitanOperationStatus> 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<ToscaElement, StorageOperationStatus> 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<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex componentV) { + VertexTypeEnum label = componentV.getLabel(); + Either<ToscaElement, StorageOperationStatus> 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 <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) { + return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName); + + } + + public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) { + return getLatestByName(GraphPropertyEnum.NAME, resourceName); + + } + + public Either<Integer, StorageOperationStatus> validateCsarUuidUniqueness(String csarUUID) { + Either<List<ToscaElement>, StorageOperationStatus> byCsar = null; + + Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>(); + properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID); + + Either<List<GraphVertex>, 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<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null); + + return Either.left(new Integer(resourceList.size())); + + } public <T extends Component> Either<Set<T>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum componentType) { - Either<List<ToscaElement>, StorageOperationStatus> followedResources; - if (componentType == ComponentTypeEnum.RESOURCE) { - followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType); - } else { - followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType); - } + Either<List<ToscaElement>, StorageOperationStatus> followedResources; + if (componentType == ComponentTypeEnum.RESOURCE) { + followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType); + } else { + followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType); + } Set<T> components = new HashSet<>(); - if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) { - return Either.right(followedResources.right().value()); - } - if (followedResources.isLeft()) { - List<ToscaElement> toscaElements = followedResources.left().value(); - toscaElements.forEach(te -> { - T component = ModelConverter.convertFromToscaElement(te); - components.add(component); - }); - } - return Either.left(components); - } - - public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) { - - return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata); - } - - public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) { - - Either<Resource, StorageOperationStatus> result = null; - Map<GraphPropertyEnum, Object> props = new HashMap<GraphPropertyEnum, Object>(); - props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - Either<List<GraphVertex>, 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<GraphVertex> 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; - } + if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) { + return Either.right(followedResources.right().value()); + } + if (followedResources.isLeft()) { + List<ToscaElement> toscaElements = followedResources.left().value(); + toscaElements.forEach(te -> { + T component = ModelConverter.convertFromToscaElement(te); + components.add(component); + }); + } + return Either.left(components); + } + + public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) { + + return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata); + } + + public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) { + + Either<Resource, StorageOperationStatus> result = null; + Map<GraphPropertyEnum, Object> props = new HashMap<GraphPropertyEnum, Object>(); + props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + Either<List<GraphVertex>, 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<GraphVertex> 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<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) { + Either<Boolean, StorageOperationStatus> validateUniquenessRes = validateToscaResourceNameUniqueness(templateName); + if (validateUniquenessRes.isLeft()) { + return Either.left(!validateUniquenessRes.left().value()); + } + return validateUniquenessRes; + } + + public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { + return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef); + + } + + public StorageOperationStatus associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) { + Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> status = nodeTemplateOperation.associateResourceInstances(componentId, relations); + if (status.isRight()) { + return status.right().value(); + } + return StorageOperationStatus.OK; + } + + protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) { + + Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>(); + properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name); + + Either<List<GraphVertex>, 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<GraphVertex> 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 <T extends Component> Either<T, StorageOperationStatus> 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<GraphVertex, TitanOperationStatus> 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<GraphVertex, TitanOperationStatus> 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<ToscaElement, StorageOperationStatus> 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<T, StorageOperationStatus> 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<GraphVertex, TitanOperationStatus> 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 <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) { + return updateToscaElement(componentToUpdate, new ComponentParametersView()); + } + + /** + * + * @param componentToUpdate + * @param type + * @param filterResult + * @return + */ + public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) { + String componentId = componentToUpdate.getUniqueId(); + Either<GraphVertex, TitanOperationStatus> 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<ToscaElement, StorageOperationStatus> 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 <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) { + Either<T, StorageOperationStatus> result; + + Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + + propertiesToMatch.put(property, nodeName); + propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + Either<List<GraphVertex>, 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<GraphVertex> 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 <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) { + + Either<List<T>, StorageOperationStatus> result = null; + Either<T, StorageOperationStatus> getComponentRes; + List<T> components = new ArrayList<>(); + List<GraphVertex> componentVertices; + Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map<GraphPropertyEnum, Object> 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<List<GraphVertex>, 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 <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) { + return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll); + } + + public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) { + Either<T, StorageOperationStatus> result; + + Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class); + Map<GraphPropertyEnum, Object> 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<List<GraphVertex>, 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 <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, List<OriginTypeEnum> excludeTypes, boolean isHighestVersions) { + List<T> components = new ArrayList<>(); + Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult; + List<ToscaElement> toscaElements = new ArrayList<>(); + List<ResourceTypeEnum> 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<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) { + Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion; + List<String> 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<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value(); + + Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements(); + if (allNotDeletedElements.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value())); + } + List<GraphVertex> allNonMarked = allNotDeletedElements.left().value(); + for (GraphVertex elementV : allMarked) { + if (topologyTemplateOperation.isInUse(elementV, allNonMarked) == false) { + Either<ToscaElement, StorageOperationStatus> 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<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) { + Either<List<GraphVertex>, 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<Boolean, StorageOperationStatus> isComponentInUse(String componentId) { + Either<Boolean, StorageOperationStatus> result; + Either<List<GraphVertex>, 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<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) { + + Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null; + Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null; + componentInstance.setIcon(origComponent.getIcon()); + Either<ImmutablePair<TopologyTemplate, String>, 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<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted) { + + StorageOperationStatus result = null; + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId()); + + Either<GraphVertex, TitanOperationStatus> 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<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) { + + Either<ImmutablePair<Component, String>, 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<ImmutablePair<TopologyTemplate, String>, 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<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) { + + Either<Component, StorageOperationStatus> result = null; + + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName()); + + Either<TopologyTemplate, StorageOperationStatus> 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<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) { + + Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null; + + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName()); + + Either<ImmutablePair<TopologyTemplate, String>, 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<String> 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<String> 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<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { + return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef); + + } + + public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) { + + Either<GraphVertex, TitanOperationStatus> 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<String, PropertyDataDefinition> 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<InputDefinition> 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<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) { + + Either<GraphVertex, TitanOperationStatus> 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<String, PropertyDataDefinition> 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<InputDefinition> 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<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) { + + Either<GraphVertex, TitanOperationStatus> 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<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>(); + if (instProperties != null) { - public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) { - Either<Boolean, StorageOperationStatus> validateUniquenessRes = validateToscaResourceNameUniqueness(templateName); - if (validateUniquenessRes.isLeft()) { - return Either.left(!validateUniquenessRes.left().value()); - } - return validateUniquenessRes; - } - - public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { - return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef); - - } - - public StorageOperationStatus associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) { - Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> status = nodeTemplateOperation.associateResourceInstances(componentId, relations); - if (status.isRight()) { - return status.right().value(); - } - return StorageOperationStatus.OK; - } - - protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) { - - Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>(); - properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name); - - Either<List<GraphVertex>, 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<GraphVertex> 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 <T extends Component> Either<T, StorageOperationStatus> 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<GraphVertex, TitanOperationStatus> 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<GraphVertex, TitanOperationStatus> 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<ToscaElement, StorageOperationStatus> 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<T, StorageOperationStatus> 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<GraphVertex, TitanOperationStatus> 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 <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) { - return updateToscaElement(componentToUpdate, new ComponentParametersView()); - } + MapPropertiesDataDefinition propertiesMap; + for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) { + propertiesMap = new MapPropertiesDataDefinition(); - /** - * - * @param componentToUpdate - * @param type - * @param filterResult - * @return - */ - public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) { - String componentId = componentToUpdate.getUniqueId(); - Either<GraphVertex, TitanOperationStatus> 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<ToscaElement, StorageOperationStatus> 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 <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) { - Either<T, StorageOperationStatus> result; - - Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + 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); - propertiesToMatch.put(property, nodeName); - propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + if (StorageOperationStatus.OK == status) { + log.debug("Component created successfully!!!"); + return Either.left(instProperties); + } + return Either.right(status); - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - - Either<List<GraphVertex>, 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<GraphVertex> 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 <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) { - - Either<List<T>, StorageOperationStatus> result = null; - Either<T, StorageOperationStatus> getComponentRes; - List<T> components = new ArrayList<>(); - List<GraphVertex> componentVertices; - Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - Map<GraphPropertyEnum, Object> 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<List<GraphVertex>, 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 <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) { - return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll); - } - - public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) { - Either<T, StorageOperationStatus> result; - - Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class); - Map<GraphPropertyEnum, Object> 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<List<GraphVertex>, 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 <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, boolean isHighestVersions) { - List<T> components = new ArrayList<>(); - Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult; - List<ToscaElement> 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<List<ToscaElement>, 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()); - } - 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<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) { - Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion; - List<String> 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<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value(); - - Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements(); - if (allNotDeletedElements.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value())); - } - List<GraphVertex> allNonMarked = allNotDeletedElements.left().value(); - for (GraphVertex elementV : allMarked) { - if (topologyTemplateOperation.isInUse(elementV, allNonMarked) == false) { - Either<ToscaElement, StorageOperationStatus> 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<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) { - Either<List<GraphVertex>, 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<Boolean, StorageOperationStatus> isComponentInUse(String componentId) { - Either<Boolean, StorageOperationStatus> result; - Either<List<GraphVertex>, 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<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) { - - Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null; - Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null; - componentInstance.setIcon(origComponent.getIcon()); - Either<ImmutablePair<TopologyTemplate, String>, 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<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted) { - - StorageOperationStatus result = null; - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId()); - - Either<GraphVertex, TitanOperationStatus> 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<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) { - - Either<ImmutablePair<Component, String>, 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<ImmutablePair<TopologyTemplate, String>, 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<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) { - - Either<Component, StorageOperationStatus> result = null; - - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName()); - - Either<TopologyTemplate, StorageOperationStatus> 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<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) { - - Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null; - - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName()); - - Either<ImmutablePair<TopologyTemplate, String>, 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<String> 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<String> 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<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { - return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef); - - } - - public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) { - - Either<GraphVertex, TitanOperationStatus> 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<String, PropertyDataDefinition> 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<InputDefinition> 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<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) { - - Either<GraphVertex, TitanOperationStatus> 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<String, PropertyDataDefinition> 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<InputDefinition> 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<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) { + } + public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) { Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); if (getVertexEither.isRight()) { @@ -1021,13 +990,12 @@ public class ToscaOperationFacade { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); } - GraphVertex vertex = getVertexEither.left().value(); Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>(); - if (instProperties != null) { + if (instInputs != null) { MapPropertiesDataDefinition propertiesMap; - for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) { + for (Entry<String, List<ComponentInstanceInput>> entry : instInputs.entrySet()) { propertiesMap = new MapPropertiesDataDefinition(); propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e))); @@ -1036,551 +1004,553 @@ public class ToscaOperationFacade { } } - StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap); + StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap); if (StorageOperationStatus.OK == status) { log.debug("Component created successfully!!!"); - return Either.left(instProperties); + return Either.left(instInputs); } return Either.right(status); } + public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) { + + StorageOperationStatus status = StorageOperationStatus.OK; + if (instProperties != null) { + + for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) { + List<ComponentInstanceInput> props = entry.getValue(); + String componentInstanseId = entry.getKey(); + if (props != null && !props.isEmpty()) { + for (ComponentInstanceInput property : props) { + List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanseId); + Optional<ComponentInstanceInput> 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<String, List<ComponentInstanceInput>> instProperties, String componentId) { - public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) { - - StorageOperationStatus status = StorageOperationStatus.OK; - if (instProperties != null) { - - for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) { - List<ComponentInstanceInput> props = entry.getValue(); - String componentInstanseId = entry.getKey(); - if (props != null && !props.isEmpty()) { - for (ComponentInstanceInput property : props) { - List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanseId); - Optional<ComponentInstanceInput> 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); - } + Either<GraphVertex, TitanOperationStatus> 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()); - public StorageOperationStatus deleteComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instProperties, String componentId) { + } - Either<GraphVertex, TitanOperationStatus> 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<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>(); + if (instProperties != null) { - } + MapPropertiesDataDefinition propertiesMap; + for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) { + propertiesMap = new MapPropertiesDataDefinition(); - GraphVertex vertex = getVertexEither.left().value(); - Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>(); - if (instProperties != null) { + propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e))); - MapPropertiesDataDefinition propertiesMap; - for (Entry<String, List<ComponentInstanceInput>> 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<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) { - - StorageOperationStatus status = StorageOperationStatus.OK; - if (instProperties != null) { - - for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) { - List<ComponentInstanceProperty> props = entry.getValue(); - String componentInstanseId = entry.getKey(); - List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanseId); - if (props != null && !props.isEmpty()) { - for (ComponentInstanceProperty property : props) { - Optional<ComponentInstanceProperty> 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<String, Map<String, ArtifactDefinition>> instArtifacts, String componentId, User user) { - - Either<GraphVertex, TitanOperationStatus> 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<String, MapArtifactDataDefinition> instArtMap = new HashMap<>(); - if (instArtifacts != null) { - - MapArtifactDataDefinition artifactsMap; - for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) { - Map<String, ArtifactDefinition> artList = entry.getValue(); - Map<String, ArtifactDataDefinition> 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<String, List<PropertyDefinition>> instArttributes, String componentId) { - - Either<GraphVertex, TitanOperationStatus> 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<String, MapPropertiesDataDefinition> instAttr = new HashMap<>(); - if (instArttributes != null) { - - MapPropertiesDataDefinition attributesMap; - for (Entry<String, List<PropertyDefinition>> 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<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, String componentId) { - Either<GraphVertex, TitanOperationStatus> 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<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>(); - - Map<String, MapListCapabiltyDataDefinition> calcCapabilty = new HashMap<>(); - Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties = new HashMap<>(); - ; - if (instCapabilties != null) { - for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) { - - Map<String, List<CapabilityDefinition>> caps = entry.getValue(); - Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>(); - for (Entry<String, List<CapabilityDefinition>> 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<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) { - - Map<String, List<RequirementDefinition>> req = entry.getValue(); - Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>(); - for (Entry<String, List<RequirementDefinition>> 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<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) { - - Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class); - Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class); - - fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType); - - Either<List<GraphVertex>, 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<Component> nonAbstractLatestComponents = new ArrayList<>(); - ComponentParametersView params = new ComponentParametersView(true); - params.setIgnoreAllVersions(false); - for (GraphVertex vertexComponent : getRes.left().value()) { - Either<ToscaElement, StorageOperationStatus> 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<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) { + instPropsMap.put(entry.getKey(), propertiesMap); + } + } - Either<ComponentMetadataData, StorageOperationStatus> result; + return topologyTemplateOperation.deleteInstInputsToComponent(vertex, instPropsMap); - Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class); - - hasProperties.put(GraphPropertyEnum.UUID, componentUuid); - if (isHighest != null) { - hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue()); - } - - Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - - Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag); - if (getRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); - } else { - List<ComponentMetadataData> 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<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) { + public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) { - Either<ComponentMetadataData, StorageOperationStatus> result; - Either<GraphVertex, TitanOperationStatus> 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; - } + StorageOperationStatus status = StorageOperationStatus.OK; + if (instProperties != null) { - private Map<String, ComponentMetadataData> findLatestVersion(List<ComponentMetadataData> resourceDataList) { - Map<Pair<String, String>, ComponentMetadataData> latestVersionMap = new HashMap<Pair<String, String>, ComponentMetadataData>(); - for (ComponentMetadataData resourceData : resourceDataList) { - ComponentMetadataData latestVersionData = resourceData; - - ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition(); - Pair<String, String> 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()); + for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) { + List<ComponentInstanceProperty> props = entry.getValue(); + String componentInstanseId = entry.getKey(); + List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanseId); + if (props != null && !props.isEmpty()) { + for (ComponentInstanceProperty property : props) { + Optional<ComponentInstanceProperty> 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); + } - latestVersionMap.put(pair, latestVersionData); - } + } + } + } + } - Map<String, ComponentMetadataData> resVersionMap = new HashMap<String, ComponentMetadataData>(); - 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 Either.left(instProperties); - return resVersionMap; - } + } - private Pair<String, String> createKeyPair(ComponentMetadataData metadataData) { - Pair<String, String> 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; - } + public StorageOperationStatus associateArtifactToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, String componentId, User user) { - return pair; - } + Either<GraphVertex, TitanOperationStatus> 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()); - public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) { + } - Either<List<Component>, StorageOperationStatus> result = null; - List<Component> components = new ArrayList<>(); - if (componentUids == null) { - Either<List<String>, 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<ToscaElement, StorageOperationStatus> 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; - } + GraphVertex vertex = getVertexEither.left().value(); + Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>(); + if (instArtifacts != null) { - private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) { - - Either<List<String>, StorageOperationStatus> result = null; - Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType); - if (getToscaElementsRes.isRight()) { - result = Either.right(getToscaElementsRes.right().value()); - } else { - List<Component> 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; - } + MapArtifactDataDefinition artifactsMap; + for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) { + Map<String, ArtifactDefinition> artList = entry.getValue(); + Map<String, ArtifactDataDefinition> 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); - private ComponentParametersView buildComponentViewForNotAbstract() { - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreCategories(false); - componentParametersView.setIgnoreAllVersions(false); - return componentParametersView; - } + instArtMap.put(entry.getKey(), artifactsMap); + } + } + + return topologyTemplateOperation.associateInstArtifactToComponent(vertex, instArtMap); + + } + + public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<PropertyDefinition>> instArttributes, String componentId) { + + Either<GraphVertex, TitanOperationStatus> 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()); - public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) { - Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType); - if (result.isLeft()) { - result = Either.left(!result.left().value()); - } - return result; - } + } - public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) { - VertexTypeEnum vertexType = getVertexTypeByComponentAndResourceTypeEnum(resourceType, componentType); - String normalizedName = ValidationUtils.normaliseComponentName(name); - Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class); - properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName); - properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); - - Either<List<GraphVertex>, 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<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null; - if (vertexList != null && !vertexList.isEmpty()) { - return Either.left(false); - } else { - return Either.left(true); - } - } + GraphVertex vertex = getVertexEither.left().value(); + Map<String, MapPropertiesDataDefinition> instAttr = new HashMap<>(); + if (instArttributes != null) { - // 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; - } + MapPropertiesDataDefinition attributesMap; + for (Entry<String, List<PropertyDefinition>> 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); + } + } - private void fillNodeTypePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> 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; - } - } + return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr); - private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> 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<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) { - hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); + public StorageOperationStatus associateCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, String componentId) { + Either<GraphVertex, TitanOperationStatus> 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()); - 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<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) { - List<VertexTypeEnum> 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; - } + GraphVertex vertex = getVertexEither.left().value(); - public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType) { - List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType); - List<Component> result = new ArrayList<>(); - for (VertexTypeEnum vertexType : internalVertexTypes) { - Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType, vertexType); - if (listByVertexType.isRight()) { - return listByVertexType; - } - result.addAll(listByVertexType.left().value()); - } - return Either.left(result); + Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>(); - } + Map<String, MapListCapabiltyDataDefinition> calcCapabilty = new HashMap<>(); + Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties = new HashMap<>(); + ; + if (instCapabilties != null) { + for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) { - public Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid) { - Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + Map<String, List<CapabilityDefinition>> caps = entry.getValue(); + Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>(); + for (Entry<String, List<CapabilityDefinition>> 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<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) { + + Map<String, List<RequirementDefinition>> req = entry.getValue(); + Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>(); + for (Entry<String, List<RequirementDefinition>> 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<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) { + + Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class); + Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class); + + fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType); + + Either<List<GraphVertex>, 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<Component> nonAbstractLatestComponents = new ArrayList<>(); + ComponentParametersView params = new ComponentParametersView(true); + params.setIgnoreAllVersions(false); + for (GraphVertex vertexComponent : getRes.left().value()) { + Either<ToscaElement, StorageOperationStatus> 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<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) { + + Either<ComponentMetadataData, StorageOperationStatus> result; + + Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class); + + hasProperties.put(GraphPropertyEnum.UUID, componentUuid); + if (isHighest != null) { + hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue()); + } + + Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag); + if (getRes.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); + } else { + List<ComponentMetadataData> 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<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) { + + Either<ComponentMetadataData, StorageOperationStatus> result; + Either<GraphVertex, TitanOperationStatus> 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<String, ComponentMetadataData> findLatestVersion(List<ComponentMetadataData> resourceDataList) { + Map<Pair<String, String>, ComponentMetadataData> latestVersionMap = new HashMap<Pair<String, String>, ComponentMetadataData>(); + for (ComponentMetadataData resourceData : resourceDataList) { + ComponentMetadataData latestVersionData = resourceData; + + ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition(); + Pair<String, String> 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<String, ComponentMetadataData> resVersionMap = new HashMap<String, ComponentMetadataData>(); + 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<String, String> createKeyPair(ComponentMetadataData metadataData) { + Pair<String, String> 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<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) { + + Either<List<Component>, StorageOperationStatus> result = null; + List<Component> components = new ArrayList<>(); + if (componentUids == null) { + Either<List<String>, 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<ToscaElement, StorageOperationStatus> 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<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) { + + Either<List<String>, StorageOperationStatus> result = null; + Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType); + if (getToscaElementsRes.isRight()) { + result = Either.right(getToscaElementsRes.right().value()); + } else { + List<Component> 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<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) { + Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType); + if (result.isLeft()) { + result = Either.left(!result.left().value()); + } + return result; + } + + public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) { + VertexTypeEnum vertexType = ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE; + String normalizedName = ValidationUtils.normaliseComponentName(name); + Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName); + properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + + Either<List<GraphVertex>, 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<GraphVertex> 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<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> 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<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> 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<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> 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<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) { + List<VertexTypeEnum> 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<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType) { + List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType); + List<Component> result = new ArrayList<>(); + for (VertexTypeEnum vertexType : internalVertexTypes) { + Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType, vertexType); + if (listByVertexType.isRight()) { + return listByVertexType; + } + result.addAll(listByVertexType.left().value()); + } + return Either.left(result); + + } + + public Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid) { + Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); Either<List<Component>, StorageOperationStatus> componentListByUuid = getComponentListByUuid(componentUuid, propertiesToMatch); return componentListByUuid; - } + } - public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) { + public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) { - Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - if (additionalPropertiesToMatch != null) { - propertiesToMatch.putAll(additionalPropertiesToMatch); - } + if (additionalPropertiesToMatch != null) { + propertiesToMatch.putAll(additionalPropertiesToMatch); + } - propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid); + propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid); - Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); + Either<List<GraphVertex>, 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<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null; + 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<GraphVertex> 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); - } + if (vertexList == null || vertexList.isEmpty()) { + log.debug("Component with uuid {} was not found", componentUuid); + return Either.right(StorageOperationStatus.NOT_FOUND); + } ArrayList<Component> latestComponents = new ArrayList<>(); - for (GraphVertex vertex : vertexList) { + for (GraphVertex vertex : vertexList) { Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex); if(toscaElementByOperation.isRight()){ @@ -1599,577 +1569,606 @@ public class ToscaOperationFacade { return Either.left(highestComponent); } } - } + } - return Either.left(latestComponents); - } - - public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) { - - Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid); - - if (latestVersionListEither.isRight()) { - return Either.right(latestVersionListEither.right().value()); - } - - List<Component> 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<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) { - - List<Resource> resources = new ArrayList<>(); - Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - Map<GraphPropertyEnum, Object> 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<List<GraphVertex>, 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<GraphVertex> resourceVerticies = getResourcesRes.left().value(); - for (GraphVertex resourceV : resourceVerticies) { - Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV); - if (getResourceRes.isRight()) { - return Either.right(getResourceRes.right().value()); - } - resources.add(getResourceRes.left().value()); - } - return Either.left(resources); - } - - public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) { - Either<T, StorageOperationStatus> result; - - Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class); - Map<GraphPropertyEnum, Object> 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<List<GraphVertex>, 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<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) { - return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, false, JsonParseFlagEnum.ParseAll); - } - - public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, boolean allowDeleted, JsonParseFlagEnum parseFlag) { - Map<GraphPropertyEnum, Object> 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<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class); - propsHasNot.put(GraphPropertyEnum.IS_DELETED, true); - - GraphVertex resourceMetadataData = null; - List<GraphVertex> resourceMetadataDataList = null; - Either<List<GraphVertex>, 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<List<GraphVertex>, 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, StorageOperationStatus> 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, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag); - return resource; - } - return null; - } - - public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) { - - String currentTemplateNameChecked = templateNameExtends; - - while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) { - Either<Resource, StorageOperationStatus> 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<List<Component>, StorageOperationStatus> fetchByResourceType(String resourceType) { - - Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class); - props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - Either<List<GraphVertex>, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props); - - if (resourcesByTypeEither.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourcesByTypeEither.right().value())); - } - - List<GraphVertex> vertexList = resourcesByTypeEither.left().value(); - List<Component> components = new ArrayList<>(); - - for (GraphVertex vertex : vertexList) { - components.add(getToscaElementByOperation(vertex).left().value()); - } - - return Either.left(components); - - } - - public void commit() { - titanDao.commit(); - } - - public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) { - Either<GraphVertex, StorageOperationStatus> 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<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component, Long modificationTime) { - - Either<ComponentMetadataData, StorageOperationStatus> result = null; - GraphVertex serviceVertex; - Either<GraphVertex, TitanOperationStatus> updateRes = null; - Either<GraphVertex, TitanOperationStatus> 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<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) { - Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - - return getServicesWithDistStatus(distStatus, propertiesToMatch); - } - - public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) { - - List<Service> servicesAll = new ArrayList<>(); - - Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - Map<GraphPropertyEnum, Object> 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<List<Service>, 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<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) { - // Either<List<GraphVertex>, 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<Component, StorageOperationStatus> 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<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) { - Either<List<GraphVertex>, 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<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex); - Either<ToscaElement, StorageOperationStatus> 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<String, ArtifactDefinition> finalDeploymentArtifacts) { - Map<String, ArtifactDataDefinition> 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<String> groupInstances) { - return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances); - } - - public Either<PropertyDefinition, StorageOperationStatus> addPropertyToResource(String propertyName, PropertyDefinition newPropertyDefinition, Resource resource) { - - Either<PropertyDefinition, StorageOperationStatus> result = null; - Either<Component, StorageOperationStatus> 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<PropertyDefinition> properties = ((Resource) getUpdatedComponentRes.left().value()).getProperties(); - if (CollectionUtils.isNotEmpty(properties)) { - Optional<PropertyDefinition> 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<PropertyDefinition, StorageOperationStatus> updatePropertyOfResource(Resource resource, PropertyDefinition newPropertyDefinition) { - - Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; - Either<PropertyDefinition, StorageOperationStatus> 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<PropertyDefinition> 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<PropertyDefinition, StorageOperationStatus> addAttributeOfResource(Component component, PropertyDefinition newAttributeDef) { - - Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; - Either<PropertyDefinition, StorageOperationStatus> 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<PropertyDefinition> 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<PropertyDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, PropertyDefinition newAttributeDef) { - - Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; - Either<PropertyDefinition, StorageOperationStatus> 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<PropertyDefinition> 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<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) { - - Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; - Either<InputDefinition, StorageOperationStatus> 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<InputDefinition> 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<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) { - return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts); - } - - public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, ComponentTypeEnum componentType, List<GroupDataDefinition> updatedGroups) { - return groupsOperation.updateGroups(component, componentType, updatedGroups); - } - - public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, ComponentTypeEnum componentType, String instanceId, List<GroupInstance> updatedGroupInstances) { - return groupsOperation.updateGroupInstances(component, componentType, instanceId, updatedGroupInstances); - } - - public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) { - return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances); - } - - public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> 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<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) { + + Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid); + + if (latestVersionListEither.isRight()) { + return Either.right(latestVersionListEither.right().value()); + } + + List<Component> 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<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) { + + List<Resource> resources = new ArrayList<>(); + Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map<GraphPropertyEnum, Object> 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<List<GraphVertex>, 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<GraphVertex> resourceVerticies = getResourcesRes.left().value(); + for (GraphVertex resourceV : resourceVerticies) { + Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV); + if (getResourceRes.isRight()) { + return Either.right(getResourceRes.right().value()); + } + resources.add(getResourceRes.left().value()); + } + return Either.left(resources); + } + + public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) { + Either<T, StorageOperationStatus> result; + + Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class); + Map<GraphPropertyEnum, Object> 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<List<GraphVertex>, 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<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) { + return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, false, JsonParseFlagEnum.ParseAll); + } + + public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, boolean allowDeleted, JsonParseFlagEnum parseFlag) { + Map<GraphPropertyEnum, Object> 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<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class); + propsHasNot.put(GraphPropertyEnum.IS_DELETED, true); + + GraphVertex resourceMetadataData = null; + List<GraphVertex> resourceMetadataDataList = null; + Either<List<GraphVertex>, 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<List<GraphVertex>, 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, StorageOperationStatus> 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, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag); + return resource; + } + return null; + } + + public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) { + + String currentTemplateNameChecked = templateNameExtends; + + while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) { + Either<Resource, StorageOperationStatus> 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<List<Component>, StorageOperationStatus> fetchByResourceType(String resourceType) { + + Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class); + props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + Either<List<GraphVertex>, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props); + + if (resourcesByTypeEither.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourcesByTypeEither.right().value())); + } + + List<GraphVertex> vertexList = resourcesByTypeEither.left().value(); + List<Component> components = new ArrayList<>(); + + for (GraphVertex vertex : vertexList) { + components.add(getToscaElementByOperation(vertex).left().value()); + } + + return Either.left(components); + + } + + public void commit() { + titanDao.commit(); + } + + public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) { + Either<GraphVertex, StorageOperationStatus> 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<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component, Long modificationTime) { + + Either<ComponentMetadataData, StorageOperationStatus> result = null; + GraphVertex serviceVertex; + Either<GraphVertex, TitanOperationStatus> updateRes = null; + Either<GraphVertex, TitanOperationStatus> 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<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) { + Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + + return getServicesWithDistStatus(distStatus, propertiesToMatch); + } + + public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) { + + List<Service> servicesAll = new ArrayList<>(); + + Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map<GraphPropertyEnum, Object> 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<List<Service>, 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<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) { + // Either<List<GraphVertex>, 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<Component, StorageOperationStatus> 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<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) { + Either<List<GraphVertex>, 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<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex); + Either<ToscaElement, StorageOperationStatus> 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<String, ArtifactDefinition> finalDeploymentArtifacts) { + Map<String, ArtifactDataDefinition> 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<String> groupInstances) { + return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances); + } + + public Either<PropertyDefinition, StorageOperationStatus> addPropertyToResource(String propertyName, PropertyDefinition newPropertyDefinition, Resource resource) { + + Either<PropertyDefinition, StorageOperationStatus> result = null; + Either<Component, StorageOperationStatus> 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<PropertyDefinition> properties = ((Resource) getUpdatedComponentRes.left().value()).getProperties(); + if (CollectionUtils.isNotEmpty(properties)) { + Optional<PropertyDefinition> 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<PropertyDefinition, StorageOperationStatus> updatePropertyOfResource(Resource resource, PropertyDefinition newPropertyDefinition) { + + Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; + Either<PropertyDefinition, StorageOperationStatus> 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<PropertyDefinition> 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<PropertyDefinition, StorageOperationStatus> addAttributeOfResource(Component component, PropertyDefinition newAttributeDef) { + + Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; + Either<PropertyDefinition, StorageOperationStatus> 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<PropertyDefinition> 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<PropertyDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, PropertyDefinition newAttributeDef) { + + Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; + Either<PropertyDefinition, StorageOperationStatus> 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<PropertyDefinition> 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<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) { + + Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; + Either<InputDefinition, StorageOperationStatus> 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<InputDefinition> 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<StorageOperationStatus,StorageOperationStatus> 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<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) { + return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts); + } + + public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, ComponentTypeEnum componentType, List<GroupDataDefinition> updatedGroups) { + return groupsOperation.updateGroups(component, componentType, updatedGroups); + } + + public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, ComponentTypeEnum componentType, String instanceId, List<GroupInstance> updatedGroupInstances) { + return groupsOperation.updateGroupInstances(component, componentType, instanceId, updatedGroupInstances); + } + + public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) { + return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances); + } + + public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> 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<InputDefinition> 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<Service, StorageOperationStatus> getService(String uniqueId, boolean inTransaction); + public Either<Service, StorageOperationStatus> getService(String uniqueId, ComponentParametersView componentParametersView, boolean inTransaction); + public Either<Service, StorageOperationStatus> deleteService(String uniqueId); public Either<Service, StorageOperationStatus> 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<TitanVertex, TitanOperationStatus> 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<String, TitanOperationStatus> getInnerType(ToscaPropertyType type, Supplier<SchemaDefinition> schemeGen) { @@ -368,7 +366,7 @@ public abstract class AbstractOperation { public List<PropertyConstraint> convertConstraints(List<String> 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<GroupTypeDefinition, StorageOperationStatus> 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<PolicyTypeDefinition, StorageOperationStatus> getPolicyType(String uniqueId, boolean inTransaction) { return getElementType(this::getPolicyTypeByUid, uniqueId, inTransaction); - } private Either<PolicyTypeDefinition, TitanOperationStatus> 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<String, DataTypeDefinition> 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<CategoryDefinition> 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; + } } |